qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
82,929
<p>I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.</p> <p>For example, here's the options if sorted alphabetically: </p> <pre><code>Calgary Edmonton Halifax Montreal Toronto </code></pre> <p>What I would like the list to be is more like this: </p> <pre><code>**Montreal** Calgary Edmonton Halifax Toronto </code></pre> <p>Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results?</p>
[ { "answer_id": 82944, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT name FROM options ORDER BY name = \"Montreal\", name;\n</code></pre>\n\n<p>Note: This works with MySQL, not SQL 2000 like the OP requested.</p>\n" }, { "answer_id": 82955, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 0, "selected": false, "text": "<pre><code>create table Places (\n add Name varchar(30),\n add Priority bit\n)\n\nselect Name\nfrom Places\norder by Priority desc,\n Name\n</code></pre>\n" }, { "answer_id": 82984, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 4, "selected": true, "text": "<pre><code>SELECT name\nFROM locations\nORDER BY\n CASE\n WHEN name = 'Montreal' \n THEN 0\n ELSE 1\n END, name\n</code></pre>\n" }, { "answer_id": 83051, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem on a website I built full of case reports. I wanted the case reports where the victim name is known to sort to the top, because they are more compelling. Conversely I wanted all the John Doe cases to be at the bottom. Since this also involved people's names, I had the firstname/lastname sorting problem as well. I didn't want to split it into two name fields because some cases aren't people at all.</p>\n\n<p>My solution:</p>\n\n<p>I have a \"Name\" field which is what is displayed. I also have a \"NameSorted\" field that is used in all queries but is never displayed. My input UI takes care of converting \"LAST, FIRST\" entered into the sorting field into the display version automatically.</p>\n\n<p>Finally, to \"rig\" the sorting I simply put appropriate characters at the beginning of the sort field. Since I want stuff to come out at the end, I put \"zzz\" at the beginning. To sort at the top you could put \"!\" at the beginning. Again your editing UI can take care of this for you.</p>\n\n<p>Yes, I admit its a bit cheezy, but it works. One advantage for me is I have to do more complex queries with joins in different places to generate pages versus RSS etc, and I don't have to keep remembering a complex expression to get the sorting right, its always just sort by the \"NameSorted\" field.</p>\n\n<p>Click my profile to see the resulting website.</p>\n" }, { "answer_id": 58755206, "author": "Deepstop", "author_id": 11606193, "author_profile": "https://Stackoverflow.com/users/11606193", "pm_score": 0, "selected": false, "text": "<p>I ended up with this</p>\n\n<pre><code>SELECT name\nFROM locations\nLEFT JOIN (VALUES ('Toronto', 1), ('Montreal', 2)) city (name, rank)\n ON locations.name = city.name\nORDER BY city.rank, locations.name;\n</code></pre>\n\n<p>Which may be overkill for this example but can be extended for more complex needs.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37/" ]
I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically. For example, here's the options if sorted alphabetically: ``` Calgary Edmonton Halifax Montreal Toronto ``` What I would like the list to be is more like this: ``` **Montreal** Calgary Edmonton Halifax Toronto ``` Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results?
``` SELECT name FROM locations ORDER BY CASE WHEN name = 'Montreal' THEN 0 ELSE 1 END, name ```
82,949
<p>I'm trying to preform setup and teardown for a set of integration tests, using jUnit 4.4 to execute the tests. The teardown needs to be run reliably. I'm having other problems with TestNG, so I'm looking to port back to jUnit. What hooks are available for execution before any tests are run and after all tests have completed?</p> <p>Note: we're using maven 2 for our build. I've tried using maven's <code>pre-</code> &amp; <code>post-integration-test</code> phases, but, if a test fails, maven stops and doesn't run <code>post-integration-test</code>, which is no help.</p>
[ { "answer_id": 83175, "author": "user15299", "author_id": 15299, "author_profile": "https://Stackoverflow.com/users/15299", "pm_score": 0, "selected": false, "text": "<p>As far as I know there is no mechanism for doing this in JUnit, however you could try subclassing Suite and overriding the run() method with a version that does provide hooks.</p>\n" }, { "answer_id": 83223, "author": "Jroc", "author_id": 12200, "author_profile": "https://Stackoverflow.com/users/12200", "pm_score": 3, "selected": false, "text": "<p>Using annotations, you can do something like this:</p>\n\n<pre><code>import org.junit.*;\nimport static org.junit.Assert.*;\nimport java.util.*;\n\nclass SomethingUnitTest {\n @BeforeClass\n public static void runBeforeClass()\n {\n\n }\n\n @AfterClass\n public static void runAfterClass()\n { \n\n }\n\n @Before \n public void setUp()\n {\n\n }\n\n @After\n public void tearDown()\n {\n\n }\n\n @Test\n public void testSomethingOrOther()\n {\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 83428, "author": "Jroc", "author_id": 12200, "author_profile": "https://Stackoverflow.com/users/12200", "pm_score": 0, "selected": false, "text": "<p>The only way I think then to get the functionality you want would be to do something like </p>\n\n<pre><code>import junit.framework.Test; \nimport junit.framework.TestResult; \nimport junit.framework.TestSuite; \n\npublic class AllTests { \n public static Test suite() { \n TestSuite suite = new TestSuite(\"TestEverything\"); \n //$JUnit-BEGIN$ \n suite.addTestSuite(TestOne.class); \n suite.addTestSuite(TestTwo.class); \n suite.addTestSuite(TestThree.class); \n //$JUnit-END$ \n } \n\n public static void main(String[] args) \n { \n AllTests test = new AllTests(); \n Test testCase = test.suite(); \n TestResult result = new TestResult(); \n setUp(); \n testCase.run(result); \n tearDown(); \n } \n public void setUp() {} \n public void tearDown() {} \n} \n</code></pre>\n\n<p>I use something like this in eclipse, so I'm not sure how portable it is outside of that environment</p>\n" }, { "answer_id": 177069, "author": "Julie", "author_id": 8217, "author_profile": "https://Stackoverflow.com/users/8217", "pm_score": 7, "selected": false, "text": "<p>Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code:</p>\n\n<pre><code>package com.test;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Suite;\nimport org.junit.runners.Suite.SuiteClasses;\n\n@RunWith(Suite.class)\n@SuiteClasses({Test1.class, Test2.class})\npublic class TestSuite {\n\n @BeforeClass\n public static void setUp() {\n System.out.println(\"setting up\");\n }\n\n @AfterClass\n public static void tearDown() {\n System.out.println(\"tearing down\");\n }\n\n}\n</code></pre>\n\n<p>So your <code>Test1</code> class would look something like:</p>\n\n<pre><code>package com.test;\n\nimport org.junit.Test;\n\n\npublic class Test1 {\n @Test\n public void test1() {\n System.out.println(\"test1\");\n }\n\n}\n</code></pre>\n\n<p>...and you can imagine that <code>Test2</code> looks similar. If you ran <code>TestSuite</code>, you would get:</p>\n\n<pre><code>setting up\ntest1\ntest2\ntearing down\n</code></pre>\n\n<p>So you can see that the set up/tear down only run before and after all tests, respectively. </p>\n\n<p>The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you.</p>\n\n<p>As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the <a href=\"http://maven.apache.org/maven-1.x/plugins/test/properties.html\" rel=\"noreferrer\">maven surefire documentation</a>.</p>\n" }, { "answer_id": 706751, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here, we</p>\n\n<ul>\n<li>upgraded to JUnit 4.5,</li>\n<li>wrote annotations to tag each test class or method which needed a working service,</li>\n<li>wrote handlers for each annotation which contained static methods to implement the setup and teardown of the service,</li>\n<li>extended the usual Runner to locate the annotations on tests, adding the static handler methods into the test execution chain at the appropriate points.</li>\n</ul>\n" }, { "answer_id": 3104103, "author": "Anurag Sharma", "author_id": 374494, "author_profile": "https://Stackoverflow.com/users/374494", "pm_score": 0, "selected": false, "text": "<p>Since maven-surefire-plugin does not run Suite class first but treats suite and test classes same, so we can configure plugin as below to enable only suite classes and disable all the tests. Suite will run all the tests.</p>\n\n<pre><code> &lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;\n &lt;version&gt;2.5&lt;/version&gt;\n &lt;configuration&gt;\n &lt;includes&gt;\n &lt;include&gt;**/*Suite.java&lt;/include&gt;\n &lt;/includes&gt;\n &lt;excludes&gt;\n &lt;exclude&gt;**/*Test.java&lt;/exclude&gt;\n &lt;exclude&gt;**/*Tests.java&lt;/exclude&gt;\n &lt;/excludes&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n</code></pre>\n" }, { "answer_id": 4377991, "author": "Binod Pant", "author_id": 533829, "author_profile": "https://Stackoverflow.com/users/533829", "pm_score": 2, "selected": false, "text": "<p>As for \"Note: we're using maven 2 for our build. I've tried using maven's pre- &amp; post-integration-test phases, but, if a test fails, maven stops and doesn't run post-integration-test, which is no help.\"</p>\n\n<p>you can try the failsafe-plugin instead, I think it has the facility to ensure cleanup occurs regardless of setup or intermediate stage status</p>\n" }, { "answer_id": 7572021, "author": "christophe blin", "author_id": 808697, "author_profile": "https://Stackoverflow.com/users/808697", "pm_score": 2, "selected": false, "text": "<p>Provided that all your tests may extend a \"technical\" class and are in the same package, you can do a little trick :</p>\n\n<pre><code>public class AbstractTest {\n private static int nbTests = listClassesIn(&lt;package&gt;).size();\n private static int curTest = 0;\n\n @BeforeClass\n public static void incCurTest() { curTest++; }\n\n @AfterClass\n public static void closeTestSuite() {\n if (curTest == nbTests) { /*cleaning*/ } \n }\n}\n\npublic class Test1 extends AbstractTest {\n @Test\n public void check() {}\n}\npublic class Test2 extends AbstractTest {\n @Test\n public void check() {}\n}\n</code></pre>\n\n<p>Be aware that this solution has a lot of drawbacks :</p>\n\n<ul>\n<li>must execute all tests of the package</li>\n<li>must subclass a \"techincal\" class</li>\n<li>you can not use @BeforeClass and @AfterClass inside subclasses</li>\n<li>if you execute only one test in the package, cleaning is not done</li>\n<li>...</li>\n</ul>\n\n<p>For information: listClassesIn() => <a href=\"https://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java/495851#495851\">How do you find all subclasses of a given class in Java?</a></p>\n" }, { "answer_id": 7638967, "author": "Sled", "author_id": 254477, "author_profile": "https://Stackoverflow.com/users/254477", "pm_score": 4, "selected": false, "text": "<p>You can use the <a href=\"http://java.dzone.com/articles/junit-49-class-and-suite-level-rules\" rel=\"nofollow noreferrer\">@ClassRule annotation in JUnit 4.9+</a> as <a href=\"https://stackoverflow.com/questions/349842/junit-4-set-up-things-in-a-test-suite-before-tests-are-run-like-a-tests-befor/7638935#7638935\">I described in an answer another question</a>.</p>\n" }, { "answer_id": 14757266, "author": "Martin Vysny", "author_id": 377320, "author_profile": "https://Stackoverflow.com/users/377320", "pm_score": 5, "selected": false, "text": "<p>A colleague of mine suggested the following: you can use a custom RunListener and implement the testRunFinished() method: <a href=\"http://junit.sourceforge.net/javadoc/org/junit/runner/notification/RunListener.html#testRunFinished(org.junit.runner.Result)\">http://junit.sourceforge.net/javadoc/org/junit/runner/notification/RunListener.html#testRunFinished(org.junit.runner.Result)</a></p>\n\n<p>To register the RunListener just configure the surefire plugin as follows:\n<a href=\"http://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html\">http://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html</a> section \"Using custom listeners and reporters\"</p>\n\n<p>This configuration should also be picked by the failsafe plugin.\nThis solution is great because you don't have to specify Suites, lookup test classes or any of this stuff - it lets Maven to do its magic, waiting for all tests to finish.</p>\n" }, { "answer_id": 40250880, "author": "FredBoutin", "author_id": 5930242, "author_profile": "https://Stackoverflow.com/users/5930242", "pm_score": 0, "selected": false, "text": "<p>If you don't want to create a suite and have to list all your test classes you can use reflection to find the number of test classes dynamically and count down in a base class @AfterClass to do the tearDown only once:</p>\n\n<pre><code>public class BaseTestClass\n{\n private static int testClassToRun = 0;\n\n // Counting the classes to run so that we can do the tear down only once\n static {\n try {\n Field field = ClassLoader.class.getDeclaredField(\"classes\");\n field.setAccessible(true);\n\n @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n Vector&lt;Class&gt; classes = (Vector&lt;Class&gt;) field.get(BlockJUnit4ClassRunner.class.getClassLoader());\n for (Class&lt;?&gt; clazz : classes) {\n if (clazz.getName().endsWith(\"Test\")) {\n testClassToRun++;\n }\n }\n } catch (Exception ignore) {\n }\n }\n\n // Setup that needs to be done only once\n static {\n // one time set up\n }\n\n @AfterClass\n public static void baseTearDown() throws Exception\n {\n if (--testClassToRun == 0) {\n // one time clean up\n }\n }\n}\n</code></pre>\n\n<p>If you prefer to use @BeforeClass instead of the static blocks, you can also use a boolean flag to do the reflection count and test setup only once at the first call. Hope this helps someone, it took me an afternoon to figure out a better way than enumerating all classes in a suite.</p>\n\n<p>Now all you need to do is extend this class for all your test classes. We already had a base class to provide some common stuff for all our tests so this was the best solution for us.</p>\n\n<p>Inspiration comes from this SO answer <a href=\"https://stackoverflow.com/a/37488620/5930242\">https://stackoverflow.com/a/37488620/5930242</a></p>\n\n<p>If you don't want to extend this class everywhere, this last SO answer might do what you want.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
I'm trying to preform setup and teardown for a set of integration tests, using jUnit 4.4 to execute the tests. The teardown needs to be run reliably. I'm having other problems with TestNG, so I'm looking to port back to jUnit. What hooks are available for execution before any tests are run and after all tests have completed? Note: we're using maven 2 for our build. I've tried using maven's `pre-` & `post-integration-test` phases, but, if a test fails, maven stops and doesn't run `post-integration-test`, which is no help.
Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code: ``` package com.test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({Test1.class, Test2.class}) public class TestSuite { @BeforeClass public static void setUp() { System.out.println("setting up"); } @AfterClass public static void tearDown() { System.out.println("tearing down"); } } ``` So your `Test1` class would look something like: ``` package com.test; import org.junit.Test; public class Test1 { @Test public void test1() { System.out.println("test1"); } } ``` ...and you can imagine that `Test2` looks similar. If you ran `TestSuite`, you would get: ``` setting up test1 test2 tearing down ``` So you can see that the set up/tear down only run before and after all tests, respectively. The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you. As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the [maven surefire documentation](http://maven.apache.org/maven-1.x/plugins/test/properties.html).
82,993
<p>We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++.</p> <p>What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available.</p>
[ { "answer_id": 83211, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You should be able to use the shell's ICDBurn interface. Back in the XP day MFC didn't even have any classes for cd burning. I'll see if I can find some examples for you, but it's been a while since I looked at this.</p>\n" }, { "answer_id": 85166, "author": "selwyn", "author_id": 16314, "author_profile": "https://Stackoverflow.com/users/16314", "pm_score": 5, "selected": true, "text": "<p>We used the following: </p>\n\n<p>Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;imapi.h&gt;\n#include &lt;windows.h&gt;\n\nstruct MEDIAINFO {\n BYTE nSessions;\n BYTE nLastTrack;\n ULONG nStartAddress;\n ULONG nNextWritable;\n ULONG nFreeBlocks;\n};\n//==============================================================================\n// Description: CD burning on Windows XP\n//==============================================================================\n#define CSIDL_CDBURN_AREA 0x003b\nSHSTDAPI_(BOOL) SHGetSpecialFolderPathA(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate);\nSHSTDAPI_(BOOL) SHGetSpecialFolderPathW(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate);\n#ifdef UNICODE\n#define SHGetSpecialFolderPath SHGetSpecialFolderPathW\n#else\n#define SHGetSpecialFolderPath SHGetSpecialFolderPathA\n#endif\n//==============================================================================\n// Interface IDiscMaster\nconst IID IID_IDiscMaster = {0x520CCA62,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}};\nconst CLSID CLSID_MSDiscMasterObj = {0x520CCA63,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}};\n\ntypedef interface ICDBurn ICDBurn;\n// Interface ICDBurn\nconst IID IID_ICDBurn = {0x3d73a659,0xe5d0,0x4d42,{0xaf,0xc0,0x51,0x21,0xba,0x42,0x5c,0x8d}};\nconst CLSID CLSID_CDBurn = {0xfbeb8a05,0xbeee,0x4442,{0x80,0x4e,0x40,0x9d,0x6c,0x45,0x15,0xe9}};\n\nMIDL_INTERFACE(\"3d73a659-e5d0-4d42-afc0-5121ba425c8d\")\nICDBurn : public IUnknown\n{\npublic:\n virtual HRESULT STDMETHODCALLTYPE GetRecorderDriveLetter(\n /* [size_is][out] */ LPWSTR pszDrive,\n /* [in] */ UINT cch) = 0;\n\n virtual HRESULT STDMETHODCALLTYPE Burn(\n /* [in] */ HWND hwnd) = 0;\n\n virtual HRESULT STDMETHODCALLTYPE HasRecordableDrive(\n /* [out] */ BOOL *pfHasRecorder) = 0;\n};\n//==============================================================================\n// Description: Get burn pathname\n// Parameters: pathname - must be at least MAX_PATH in size\n// Returns: Non-zero for an error\n// Notes: CoInitialize(0) must be called once in application\n//==============================================================================\nint GetBurnPath(char *path)\n{\n ICDBurn* pICDBurn;\n int ret = 0;\n\n if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&amp;pICDBurn))) {\n BOOL flag;\n if (pICDBurn-&gt;HasRecordableDrive(&amp;flag) == S_OK) {\n if (SHGetSpecialFolderPath(0, path, CSIDL_CDBURN_AREA, 0)) {\n strcat(path, \"\\\\\");\n }\n else {\n ret = 1;\n }\n }\n else {\n ret = 2;\n }\n pICDBurn-&gt;Release();\n }\n else {\n ret = 3;\n }\n return ret;\n}\n//==============================================================================\n// Description: Get CD pathname\n// Parameters: pathname - must be at least 5 bytes in size\n// Returns: Non-zero for an error\n// Notes: CoInitialize(0) must be called once in application\n//==============================================================================\nint GetCDPath(char *path)\n{\n ICDBurn* pICDBurn;\n int ret = 0;\n\n if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&amp;pICDBurn))) {\n BOOL flag;\n WCHAR drive[5];\n if (pICDBurn-&gt;GetRecorderDriveLetter(drive, 4) == S_OK) {\n sprintf(path, \"%S\", drive);\n }\n else {\n ret = 1;\n }\n pICDBurn-&gt;Release();\n }\n else {\n ret = 3;\n }\n return ret;\n}\n//==============================================================================\n// Description: Burn CD\n// Parameters: None\n// Returns: Non-zero for an error\n// Notes: CoInitialize(0) must be called once in application\n//==============================================================================\nint Burn(void)\n{\n ICDBurn* pICDBurn;\n int ret = 0;\n\n if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&amp;pICDBurn))) {\n if (pICDBurn-&gt;Burn(NULL) != S_OK) {\n ret = 1;\n }\n pICDBurn-&gt;Release();\n }\n else {\n ret = 2;\n }\n return ret;\n}\n//==============================================================================\nbool GetCDRecordableInfo(long *FreeSpaceSize)\n{\n bool Result = false;\n IDiscMaster *idm = NULL;\n IDiscRecorder *idr = NULL;\n IEnumDiscRecorders *pEnumDiscRecorders = NULL;\n ULONG cnt;\n long type;\n long mtype;\n long mflags;\n MEDIAINFO mi;\n\n try {\n CoCreateInstance(CLSID_MSDiscMasterObj, 0, CLSCTX_ALL, IID_IDiscMaster, (void**)&amp;idm);\n idm-&gt;Open();\n idm-&gt;EnumDiscRecorders(&amp;pEnumDiscRecorders);\n pEnumDiscRecorders-&gt;Next(1, &amp;idr, &amp;cnt);\n pEnumDiscRecorders-&gt;Release();\n\n idr-&gt;OpenExclusive();\n idr-&gt;GetRecorderType(&amp;type);\n idr-&gt;QueryMediaType(&amp;mtype, &amp;mflags);\n idr-&gt;QueryMediaInfo(&amp;mi.nSessions, &amp;mi.nLastTrack, &amp;mi.nStartAddress, &amp;mi.nNextWritable, &amp;mi.nFreeBlocks);\n idr-&gt;Release();\n\n idm-&gt;Close();\n idm-&gt;Release();\n Result = true;\n }\n catch (...) {\n Result = false;\n }\n\n if (Result == true) {\n Result = false;\n if (mtype == 0) {\n // No Media inserted\n Result = false;\n }\n else {\n if ((mflags &amp; 0x04) == 0x04) {\n // Writable Media\n Result = true;\n }\n else {\n Result = false;\n }\n\n if (Result == true) {\n *FreeSpaceSize = (mi.nFreeBlocks * 2048);\n }\n else {\n *FreeSpaceSize = 0;\n }\n }\n }\n\n return Result;\n}\n</code></pre>\n" }, { "answer_id": 86627, "author": "eaguilar", "author_id": 16635, "author_profile": "https://Stackoverflow.com/users/16635", "pm_score": 0, "selected": false, "text": "<p>This is the information for IMAPI in MSDN site <a href=\"http://msdn.microsoft.com/en-us/library/aa939967.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa939967.aspx</a></p>\n" }, { "answer_id": 102170, "author": "QAZ", "author_id": 14260, "author_profile": "https://Stackoverflow.com/users/14260", "pm_score": 2, "selected": false, "text": "<p>To complement the accepted answer, we added this helper function to programatically change the burn directory on the fly as this was a requirement of ours.</p>\n\n<pre><code>typedef HMODULE (WINAPI * SHSETFOLDERPATHA)( int , HANDLE , DWORD , LPCTSTR );\n\nint SetBurnPath( char * cpPath )\n{\n SHSETFOLDERPATHA pSHSetFolderPath;\n HANDLE hShell = LoadLibraryA( \"shell32.dll\" );\n if( hShell == NULL )\n return -2;\n\n DWORD dwOrdinal = 0x00000000 + 231;\n\n pSHSetFolderPath = (SHSETFOLDERPATHA)GetProcAddress( hShell, (LPCSTR)dwOrdinal );\n if( pSHSetFolderPath == NULL )\n return -3;\n\n if( pSHSetFolderPath( CSIDL_CDBURN_AREA, NULL, 0, cpPath ) == S_OK )\n return 0;\n\n return -1;\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/82993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14260/" ]
We need to programatically burn files to CD in a C\C++ Windows XP/Vista application we are developing using Borlands Turbo C++. What is the simplest and best way to do this? We would prefer a native windows API (that doesnt rely on MFC) so as not to rely on any third party software/drivers if one is available.
We used the following: Store files in the directory returned by GetBurnPath, then write using Burn. GetCDRecordableInfo is used to check when the CD is ready. ``` #include <stdio.h> #include <imapi.h> #include <windows.h> struct MEDIAINFO { BYTE nSessions; BYTE nLastTrack; ULONG nStartAddress; ULONG nNextWritable; ULONG nFreeBlocks; }; //============================================================================== // Description: CD burning on Windows XP //============================================================================== #define CSIDL_CDBURN_AREA 0x003b SHSTDAPI_(BOOL) SHGetSpecialFolderPathA(HWND hwnd, LPSTR pszPath, int csidl, BOOL fCreate); SHSTDAPI_(BOOL) SHGetSpecialFolderPathW(HWND hwnd, LPWSTR pszPath, int csidl, BOOL fCreate); #ifdef UNICODE #define SHGetSpecialFolderPath SHGetSpecialFolderPathW #else #define SHGetSpecialFolderPath SHGetSpecialFolderPathA #endif //============================================================================== // Interface IDiscMaster const IID IID_IDiscMaster = {0x520CCA62,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}}; const CLSID CLSID_MSDiscMasterObj = {0x520CCA63,0x51A5,0x11D3,{0x91,0x44,0x00,0x10,0x4B,0xA1,0x1C,0x5E}}; typedef interface ICDBurn ICDBurn; // Interface ICDBurn const IID IID_ICDBurn = {0x3d73a659,0xe5d0,0x4d42,{0xaf,0xc0,0x51,0x21,0xba,0x42,0x5c,0x8d}}; const CLSID CLSID_CDBurn = {0xfbeb8a05,0xbeee,0x4442,{0x80,0x4e,0x40,0x9d,0x6c,0x45,0x15,0xe9}}; MIDL_INTERFACE("3d73a659-e5d0-4d42-afc0-5121ba425c8d") ICDBurn : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetRecorderDriveLetter( /* [size_is][out] */ LPWSTR pszDrive, /* [in] */ UINT cch) = 0; virtual HRESULT STDMETHODCALLTYPE Burn( /* [in] */ HWND hwnd) = 0; virtual HRESULT STDMETHODCALLTYPE HasRecordableDrive( /* [out] */ BOOL *pfHasRecorder) = 0; }; //============================================================================== // Description: Get burn pathname // Parameters: pathname - must be at least MAX_PATH in size // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int GetBurnPath(char *path) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { BOOL flag; if (pICDBurn->HasRecordableDrive(&flag) == S_OK) { if (SHGetSpecialFolderPath(0, path, CSIDL_CDBURN_AREA, 0)) { strcat(path, "\\"); } else { ret = 1; } } else { ret = 2; } pICDBurn->Release(); } else { ret = 3; } return ret; } //============================================================================== // Description: Get CD pathname // Parameters: pathname - must be at least 5 bytes in size // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int GetCDPath(char *path) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { BOOL flag; WCHAR drive[5]; if (pICDBurn->GetRecorderDriveLetter(drive, 4) == S_OK) { sprintf(path, "%S", drive); } else { ret = 1; } pICDBurn->Release(); } else { ret = 3; } return ret; } //============================================================================== // Description: Burn CD // Parameters: None // Returns: Non-zero for an error // Notes: CoInitialize(0) must be called once in application //============================================================================== int Burn(void) { ICDBurn* pICDBurn; int ret = 0; if (SUCCEEDED(CoCreateInstance(CLSID_CDBurn, NULL,CLSCTX_INPROC_SERVER,IID_ICDBurn,(LPVOID*)&pICDBurn))) { if (pICDBurn->Burn(NULL) != S_OK) { ret = 1; } pICDBurn->Release(); } else { ret = 2; } return ret; } //============================================================================== bool GetCDRecordableInfo(long *FreeSpaceSize) { bool Result = false; IDiscMaster *idm = NULL; IDiscRecorder *idr = NULL; IEnumDiscRecorders *pEnumDiscRecorders = NULL; ULONG cnt; long type; long mtype; long mflags; MEDIAINFO mi; try { CoCreateInstance(CLSID_MSDiscMasterObj, 0, CLSCTX_ALL, IID_IDiscMaster, (void**)&idm); idm->Open(); idm->EnumDiscRecorders(&pEnumDiscRecorders); pEnumDiscRecorders->Next(1, &idr, &cnt); pEnumDiscRecorders->Release(); idr->OpenExclusive(); idr->GetRecorderType(&type); idr->QueryMediaType(&mtype, &mflags); idr->QueryMediaInfo(&mi.nSessions, &mi.nLastTrack, &mi.nStartAddress, &mi.nNextWritable, &mi.nFreeBlocks); idr->Release(); idm->Close(); idm->Release(); Result = true; } catch (...) { Result = false; } if (Result == true) { Result = false; if (mtype == 0) { // No Media inserted Result = false; } else { if ((mflags & 0x04) == 0x04) { // Writable Media Result = true; } else { Result = false; } if (Result == true) { *FreeSpaceSize = (mi.nFreeBlocks * 2048); } else { *FreeSpaceSize = 0; } } } return Result; } ```
83,038
<p>When supplying dates to a stored procedure via a parameter I'm a little confused over which format to use for the dates. My original VBA syntax used the ADO Connection object to execute the stored procedure:</p> <pre><code>Set SentDetailRS = Me.ADOConnectionToIntegrity.Execute("dbo.s_SelectAggregatedSentDetailList '" &amp; fCSQLDate(EffectiveDate) &amp; "'", , adCmdText) </code></pre> <p>This works fine for me using the date syntax <code>yyyy-mm-dd</code> but when another user executes the code they recieve the error: 13 'Type Mismatch'. </p> <p>After some experimentation I found that supplying the date in the format <code>dd/mm/yyyy</code> fixes this error for the user but now gives me the error! </p> <p>Executing the stored procedure using a command object with parameters works regardless of the format of the date (I assume ADO is taking care of the formatting behind the scenes). I thought that using the format <code>yyyy-mm-dd</code> would work universally with SQL Server? </p> <p>I'm also perplexed as to why this problem appears to be user specific? I noticed that my default language on SQL Server is 'English' whereas the other user's default language is 'British English', could that cause the problem? </p> <p>I'm using ADO 2.8 with Access 2003 and SQL Server 2000, SQL Server login is via Windows integrated security.</p>
[ { "answer_id": 83164, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>I would guess that fCSQLDate function is culture-specific - i.e. it will parse the date based on the user's locale settings. That's why you see the problem.</p>\n\n<p>Anyway, using queries with concatenated strings is always a bad idea (injection attacks). You are better off if you use parameters.</p>\n" }, { "answer_id": 83174, "author": "GUI Junkie", "author_id": 11498, "author_profile": "https://Stackoverflow.com/users/11498", "pm_score": 0, "selected": false, "text": "<p>Access uses # as date field delimiter. The format should be #mm/dd/yyyy# probably the #mm-dd-yyyy# will also work fine.</p>\n" }, { "answer_id": 83489, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 2, "selected": true, "text": "<p>Be careful, and do not believe that ADO is taking care of the problem. Universal SQL date format is 'YYYYMMDD', while both SQL and ACCESS are influenced by the regional settings of the machine in the way they display dates and convert them in character strings.</p>\n\n<p>Do not forget that Date separator is # in Access, while it is ' in SQL</p>\n\n<p>My best advice will be to systematically convert your Access #MM-DD-YYYY# (or similar) into 'YYYYMMDD' before sending the instruction to your server. You could build a small function such as:</p>\n\n<pre><code>Public function SQLdateFormat(x_date) as string\n\nSQLDateFormat = _\n trim(str(datePart(\"yyyy\",x_date))) &amp; _\n right(str(datePart(\"m\",date)),2) &amp; _\n right(str(datePart(\"d\",date)),2)\n\n ''be carefull, you might get something like '2008 9 3'\nSQLDateFormat = replace(functionSQLDateFormat,\" \",\"0\")\n '' you will have the expected '20080903'\n\nEnd function\n</code></pre>\n\n<p>If you do not programmatically build your INSERT/UPDATE string before sending it to the server, I will then advise you to turn the regional settings of all the machines to the regional settings of the machine hosting SQL. You might also have to check if there is a specific date format on your SQL server (I am not sure). Personnaly, I solved this kind of localisation problems (it also happens when coma is used as a decimal separator in French) or SQL specific characters problems (when quotes or double quotes are in a string) by retreating the SQL instructions before sending them to the server. </p>\n" }, { "answer_id": 83578, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 0, "selected": false, "text": "<p>Sorry I don't know mysql, but with oracle I would always explicity state the format that I was expecting the format to be in, eg: 'DD-MM-YYYY', to avoid (regional) date format problems</p>\n" }, { "answer_id": 88598, "author": "Mark Plumpton", "author_id": 10422, "author_profile": "https://Stackoverflow.com/users/10422", "pm_score": 0, "selected": false, "text": "<p>Why not use the format</p>\n\n<pre><code>dd mmm yyyy\n</code></pre>\n\n<p>There is only one way it can be interpreted.</p>\n" }, { "answer_id": 987797, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can use the Date() function to return a universal date based on the machine date and time settings. The region settings on the machine will determine how it it formatted on the client end. If you leave the field as strictle a DateTime field then the cleint region settings can format the date.</p>\n\n<p>Going into the server, using the Date() function should aslo work (returning a universal date value).</p>\n\n<p>Also, use a command object and parameters in your query when you pass them to avoid SQL injection attacks on string fields.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When supplying dates to a stored procedure via a parameter I'm a little confused over which format to use for the dates. My original VBA syntax used the ADO Connection object to execute the stored procedure: ``` Set SentDetailRS = Me.ADOConnectionToIntegrity.Execute("dbo.s_SelectAggregatedSentDetailList '" & fCSQLDate(EffectiveDate) & "'", , adCmdText) ``` This works fine for me using the date syntax `yyyy-mm-dd` but when another user executes the code they recieve the error: 13 'Type Mismatch'. After some experimentation I found that supplying the date in the format `dd/mm/yyyy` fixes this error for the user but now gives me the error! Executing the stored procedure using a command object with parameters works regardless of the format of the date (I assume ADO is taking care of the formatting behind the scenes). I thought that using the format `yyyy-mm-dd` would work universally with SQL Server? I'm also perplexed as to why this problem appears to be user specific? I noticed that my default language on SQL Server is 'English' whereas the other user's default language is 'British English', could that cause the problem? I'm using ADO 2.8 with Access 2003 and SQL Server 2000, SQL Server login is via Windows integrated security.
Be careful, and do not believe that ADO is taking care of the problem. Universal SQL date format is 'YYYYMMDD', while both SQL and ACCESS are influenced by the regional settings of the machine in the way they display dates and convert them in character strings. Do not forget that Date separator is # in Access, while it is ' in SQL My best advice will be to systematically convert your Access #MM-DD-YYYY# (or similar) into 'YYYYMMDD' before sending the instruction to your server. You could build a small function such as: ``` Public function SQLdateFormat(x_date) as string SQLDateFormat = _ trim(str(datePart("yyyy",x_date))) & _ right(str(datePart("m",date)),2) & _ right(str(datePart("d",date)),2) ''be carefull, you might get something like '2008 9 3' SQLDateFormat = replace(functionSQLDateFormat," ","0") '' you will have the expected '20080903' End function ``` If you do not programmatically build your INSERT/UPDATE string before sending it to the server, I will then advise you to turn the regional settings of all the machines to the regional settings of the machine hosting SQL. You might also have to check if there is a specific date format on your SQL server (I am not sure). Personnaly, I solved this kind of localisation problems (it also happens when coma is used as a decimal separator in French) or SQL specific characters problems (when quotes or double quotes are in a string) by retreating the SQL instructions before sending them to the server.
83,045
<p>I have a costumer showing Notepad with a large set of data that looks totally misaligned if word wrap is on and I want to force it off. Is there a command switch to do this?</p>
[ { "answer_id": 83091, "author": "Neoaikon", "author_id": 15837, "author_profile": "https://Stackoverflow.com/users/15837", "pm_score": 1, "selected": false, "text": "<p>you could just turn it off by going to Format -> Word Wrap.</p>\n" }, { "answer_id": 83127, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 3, "selected": true, "text": "<p>I dont think there is a command switch to do this at all. If you want to force it off all the time then you may want to edit the registry:</p>\n\n<pre><code>Hive: HKEY_CURRENT_USER\nKey: SOFTWARE\\Microsoft\\Notepad\nName: fWrap\nType: REG_DWORD\nValue: 0\n</code></pre>\n\n<p>You could even create a .reg file and put it in a batch file to run it and reset it every time notepad runs.</p>\n\n<p>Usually though if you have word wrap turned off, when you open it up again, it will still be turned off.</p>\n" }, { "answer_id": 83176, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>I do not believe there is any command-line option to do that.</p>\n\n<p>You can however set the default behavior by setting the registry-value HKEY_CURRENT_USER\\Software\\Microsoft\\Notepad\\fWrap to 0.</p>\n\n<p>Depending on your exact requirements, you might be able to solve your problem by making a bat-file that modifies the registry before starting Notepad. That would be a rather large hack, though.</p>\n" }, { "answer_id": 83178, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 0, "selected": false, "text": "<p>You could just use Wordpad instead of Notepad, it has word wrap off by default.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9077/" ]
I have a costumer showing Notepad with a large set of data that looks totally misaligned if word wrap is on and I want to force it off. Is there a command switch to do this?
I dont think there is a command switch to do this at all. If you want to force it off all the time then you may want to edit the registry: ``` Hive: HKEY_CURRENT_USER Key: SOFTWARE\Microsoft\Notepad Name: fWrap Type: REG_DWORD Value: 0 ``` You could even create a .reg file and put it in a batch file to run it and reset it every time notepad runs. Usually though if you have word wrap turned off, when you open it up again, it will still be turned off.
83,050
<p>I had this question in mind and since I just discovered this site I decided to post it here.</p> <p>Let's say I have a table with a timestamp and a state for a given "object" (generic meaning, not OOP object); is there an optimal way to calculate the time between a state and the next occurrence of another (or same) state (what I call a "trip") with a single SQL statement (inner SELECTs and UNIONs aren't counted)?</p> <p>Ex: For the following, the trip time between Initial and Done would be 6 days, but between Initial and Review it would be 2 days. </p> <blockquote> <p>2008-08-01 13:30:00 - Initial<br> 2008-08-02 13:30:00 - Work<br> 2008-08-03 13:30:00 - Review<br> 2008-08-04 13:30:00 - Work<br> 2008-08-05 13:30:00 - Review<br> 2008-08-06 13:30:00 - Accepted<br> 2008-08-07 13:30:00 - Done</p> </blockquote> <p>No need to be generic, just say what <a href="https://stackoverflow.com/questions/980813/what-is-sgbd">SGBD</a> your solution is specific to if not generic.</p>
[ { "answer_id": 83129, "author": "GUI Junkie", "author_id": 11498, "author_profile": "https://Stackoverflow.com/users/11498", "pm_score": 0, "selected": false, "text": "<p>I don't think you can get that answer with one SQL statement as you are trying to obtain one result from many records. The only way to achieve that in SQL is to get the timestamp field for two different records and calculate the difference (datediff). Therefore, UNIONS or Inner Joins are needed.</p>\n" }, { "answer_id": 83234, "author": "Andy Irving", "author_id": 8553, "author_profile": "https://Stackoverflow.com/users/8553", "pm_score": 0, "selected": false, "text": "<p>I'm not sure I understand the question exactly, but you can do something like the following which reads the table in one pass then uses a derived table to calculate it. SQL Server code:</p>\n\n<pre><code>CREATE TABLE #testing\n(\n eventdatetime datetime NOT NULL,\n state varchar(10) NOT NULL\n)\n\nINSERT INTO #testing (\n eventdatetime,\n state\n) \nSELECT '20080801 13:30:00', 'Initial' UNION ALL\nSELECT '20080802 13:30:00', 'Work' UNION ALL\nSELECT '20080803 13:30:00', 'Review' UNION ALL\nSELECT '20080804 13:30:00', 'Work' UNION ALL\nSELECT '20080805 13:30:00', 'Review' UNION ALL\nSELECT '20080806 13:30:00', 'Accepted' UNION ALL\nSELECT '20080807 13:30:00', 'Done'\n\nSELECT DATEDIFF(dd, Initial, Review)\nFROM (\nSELECT MIN(CASE WHEN state='Initial' THEN eventdatetime END) AS Initial,\n MIN(CASE WHEN state='Review' THEN eventdatetime END) AS Review\nFROM #testing\n) AS A\n\nDROP TABLE #testing\n</code></pre>\n" }, { "answer_id": 83244, "author": "Damien_The_Unbeliever", "author_id": 15498, "author_profile": "https://Stackoverflow.com/users/15498", "pm_score": 0, "selected": false, "text": "<pre><code>create table A (\n At datetime not null,\n State varchar(20) not null\n)\ngo\ninsert into A(At,State)\nselect '2008-08-01T13:30:00','Initial' union all\nselect '2008-08-02T13:30:00','Work' union all\nselect '2008-08-03T13:30:00','Review' union all\nselect '2008-08-04T13:30:00','Work' union all\nselect '2008-08-05T13:30:00','Review' union all\nselect '2008-08-06T13:30:00','Accepted' union all\nselect '2008-08-07T13:30:00','Done'\ngo\n--Find trip time from Initial to Done\nselect DATEDIFF(day,t1.At,t2.At)\nfrom\n A t1\n inner join\n A t2\n on\n t1.State = 'Initial' and\n t2.State = 'Review' and\n t1.At &lt; t2.At\n left join\n A t3\n on\n t3.State = 'Initial' and\n t3.At &gt; t1.At and\n t4.At &lt; t2.At\n left join\n A t4\n on\n t4.State = 'Review' and\n t4.At &lt; t2.At and\n t4.At &gt; t1.At\nwhere\n t3.At is null and\n t4.At is null\n</code></pre>\n\n<p>Didn't say whether joins were allowed or not. Joins to t3 and t4 (and their comparisons) let you say whether you want the earliest or latest occurrence of the start and end states (in this case, I'm asking for latest \"Initial\" and earliest \"Review\")</p>\n\n<p>In real code, my start and end states would be parameters</p>\n\n<p>Edit: Oops, need to include \"t3.At &lt; t2.At\" and \"t4.At > t1.At\", to fix some odd sequences of States (e.g. If we removed the second \"Review\" and then queried from \"Work\" to \"Review\", the original query will fail)</p>\n" }, { "answer_id": 83377, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 0, "selected": false, "text": "<p>It is probably easier if you have a sequence number as well as the time-stamp: in most RDBMSs you can create an auto-increment column and not change any of the <code>INSERT</code> statements. Then you join the table with a copy of itself to get the deltas</p>\n\n<pre><code>select after.moment - before.moment, before.state, after.state\nfrom object_states before, object_states after\nwhere after.sequence + 1 = before.sequence\n</code></pre>\n\n<p>(where the details of SQL syntax will vary according to which database system).</p>\n" }, { "answer_id": 83521, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code> -- Oracle SQl\n\n CREATE TABLE ObjectState\n (\n startdate date NOT NULL,\n state varchar2(10) NOT NULL\n );\n\n\n\n insert into ObjectState \n select to_date('01-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Initial' union all\n select to_date('02-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Work' union all\n select to_date('03-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Review' union all\n select to_date('04-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Work' union all\n select to_date('05-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Review' union all\n select to_date('06-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Accepted' union all\n select to_date('07-Aug-2008 13:30:00','dd-Mon-rrrr hh24:mi:ss'),'Done';\n\n-- Days in between two states\n\n select o2.startdate - o1.startdate as days\n from ObjectState o1, ObjectState o2\n where o1.state = 'Initial'\n and o2.state = 'Review';\n</code></pre>\n" }, { "answer_id": 83831, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 0, "selected": false, "text": "<p>I think that your steps (each record of your trip can be seen as a step) can be somewhere grouped together as part of the same activity. It is then possible to group your data on it, as, for example:</p>\n\n<pre><code>SELECT Min(Tbl_Step.dateTimeStep) as tripBegin, _ \n Max(Tbl_Step.dateTimeStep) as tripEnd _\nFROM \n Tbl_Step \nWHERE \n id_Activity = 'AAAAAAA'\n</code></pre>\n\n<p>Using this principle, you can then calculate other aggregates like the number of steps in the activity and so on. But you will not find an SQL way to calculate values like gap between 2 steps, as such a data does not belong either to the first or to the second step. Some reporting tools use what they call \"running sums\" to calculate such intermediate data. Depending on your objectives, this might be a solution for you.</p>\n" }, { "answer_id": 84175, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 1, "selected": false, "text": "<p>Here's an Oracle methodology using an analytic function.</p>\n\n<pre><code>with data as (\nSELECT 1 trip_id, to_date('20080801 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Initial' step from dual UNION ALL\nSELECT 1 trip_id, to_date('20080802 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL\nSELECT 1 trip_id, to_date('20080803 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL\nSELECT 1 trip_id, to_date('20080804 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL\nSELECT 1 trip_id, to_date('20080805 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL\nSELECT 1 trip_id, to_date('20080806 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Accepted' step from dual UNION ALL\nSELECT 1 trip_id, to_date('20080807 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Done' step from dual )\nselect trip_id,\n step,\n dt - lag(dt) over (partition by trip_id order by dt) trip_time\nfrom data\n/\n\n\n1 Initial \n1 Work 1\n1 Review 1\n1 Work 1\n1 Review 1\n1 Accepted 1\n1 Done 1\n</code></pre>\n\n<p>These are very commonly used in situations where traditionally we might use a self-join.</p>\n" }, { "answer_id": 103133, "author": "user17957", "author_id": 17957, "author_profile": "https://Stackoverflow.com/users/17957", "pm_score": 1, "selected": false, "text": "<p>PostgreSQL syntax :</p>\n\n<pre><code>DROP TABLE ObjectState;\nCREATE TABLE ObjectState (\n object_id integer not null,--foreign key\n event_time timestamp NOT NULL,\n state varchar(10) NOT NULL,\n --Other fields \n CONSTRAINT pk_ObjectState PRIMARY KEY (object_id,event_time)\n);\n</code></pre>\n\n<p><strong>For given state find first folowing state of given type</strong></p>\n\n<pre><code>select parent.object_id,parent.event_time,parent.state,min(child.event_time) as ch_event_time,min(child.event_time)-parent.event_time as step_time\nfrom \n ObjectState parent\n join ObjectState child on (parent.object_id=child.object_id and parent.event_time&lt;child.event_time)\nwhere \n --Starting state \n parent.object_id=1 and parent.event_time=to_timestamp('01-Aug-2008 13:30:00','dd-Mon-yyyy hh24:mi:ss')\n --needed state\n and child.state='Review'\ngroup by parent.object_id,parent.event_time,parent.state;\n</code></pre>\n\n<p>This query is not the shortest posible but it should be easy to understand and used as part of other queries :</p>\n\n<p><strong>List events and their duration for given object</strong></p>\n\n<pre><code>select parent.object_id,parent.event_time,parent.state,min(child.event_time) as ch_event_time,\n CASE WHEN parent.state&lt;&gt;'Done' and min(child.event_time) is null THEN (select localtimestamp)-parent.event_time ELSE min(child.event_time)-parent.event_time END as step_time\nfrom \n ObjectState parent\n left outer join ObjectState child on (parent.object_id=child.object_id and parent.event_time&lt;child.event_time)\nwhere parent.object_id=4 \ngroup by parent.object_id,parent.event_time,parent.state\norder by parent.object_id,parent.event_time,parent.state;\n</code></pre>\n\n<p><strong>List current states for objects that are not \"done\"</strong></p>\n\n<pre><code>select states.object_id,states.event_time,states.state,(select localtimestamp)-states.event_time as step_time\nfrom\n (select parent.object_id,parent.event_time,parent.state,min(child.event_time) as ch_event_time,min(child.event_time)-parent.event_time as step_time\n from \n ObjectState parent\n left outer join ObjectState child on (parent.object_id=child.object_id and parent.event_time&lt;child.event_time) \n group by parent.object_id,parent.event_time,parent.state) states\nwhere \n states.object_id not in (select object_id from ObjectState where state='Done')\n and ch_event_time is null;\n</code></pre>\n\n<p>Test data</p>\n\n<pre><code>insert into ObjectState (object_id,event_time,state)\nselect 1,to_timestamp('01-Aug-2008 13:30:00','dd-Mon-yyyy hh24:mi:ss'),'Initial' union all\nselect 1,to_timestamp('02-Aug-2008 13:40:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 1,to_timestamp('03-Aug-2008 13:50:00','dd-Mon-yyyy hh24:mi:ss'),'Review' union all\nselect 1,to_timestamp('04-Aug-2008 14:30:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 1,to_timestamp('04-Aug-2008 16:20:00','dd-Mon-yyyy hh24:mi:ss'),'Review' union all\nselect 1,to_timestamp('06-Aug-2008 18:00:00','dd-Mon-yyyy hh24:mi:ss'),'Accepted' union all\nselect 1,to_timestamp('07-Aug-2008 21:30:00','dd-Mon-yyyy hh24:mi:ss'),'Done';\n\n\ninsert into ObjectState (object_id,event_time,state)\nselect 2,to_timestamp('01-Aug-2008 13:30:00','dd-Mon-yyyy hh24:mi:ss'),'Initial' union all\nselect 2,to_timestamp('02-Aug-2008 13:40:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 2,to_timestamp('07-Aug-2008 13:50:00','dd-Mon-yyyy hh24:mi:ss'),'Review' union all\nselect 2,to_timestamp('14-Aug-2008 14:30:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 2,to_timestamp('15-Aug-2008 16:20:00','dd-Mon-yyyy hh24:mi:ss'),'Review' union all\nselect 2,to_timestamp('16-Aug-2008 18:02:00','dd-Mon-yyyy hh24:mi:ss'),'Accepted' union all\nselect 2,to_timestamp('17-Aug-2008 22:10:00','dd-Mon-yyyy hh24:mi:ss'),'Done';\n\ninsert into ObjectState (object_id,event_time,state)\nselect 3,to_timestamp('12-Sep-2008 13:30:00','dd-Mon-yyyy hh24:mi:ss'),'Initial' union all\nselect 3,to_timestamp('13-Sep-2008 13:40:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 3,to_timestamp('14-Sep-2008 13:50:00','dd-Mon-yyyy hh24:mi:ss'),'Review' union all\nselect 3,to_timestamp('15-Sep-2008 14:30:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 3,to_timestamp('16-Sep-2008 16:20:00','dd-Mon-yyyy hh24:mi:ss'),'Review';\n\n\ninsert into ObjectState (object_id,event_time,state)\nselect 4,to_timestamp('21-Aug-2008 03:10:00','dd-Mon-yyyy hh24:mi:ss'),'Initial' union all\nselect 4,to_timestamp('22-Aug-2008 03:40:00','dd-Mon-yyyy hh24:mi:ss'),'Work' union all\nselect 4,to_timestamp('23-Aug-2008 03:20:00','dd-Mon-yyyy hh24:mi:ss'),'Review' union all\nselect 4,to_timestamp('24-Aug-2008 04:30:00','dd-Mon-yyyy hh24:mi:ss'),'Work';\n</code></pre>\n" }, { "answer_id": 109844, "author": "Jonathan", "author_id": 19272, "author_profile": "https://Stackoverflow.com/users/19272", "pm_score": 0, "selected": false, "text": "<p>I tried to do this in MySQL. You would need to use a variable since there is no rank function in MySQL, so it would go like this:</p>\n\n<pre><code>set @trip1 = 0; set @trip2 = 0;\nSELECT trip1.`date` as startdate, datediff(trip2.`date`, trip1.`date`) length_of_trip\nFROM\n(SELECT @trip1 := @trip1 + 1 as rank1, `date` from trip where state='Initial') as trip1\nINNER JOIN\n(SELECT @trip2 := @trip2 + 1 as rank2, `date` from trip where state='Done') as trip2\nON rank1 = rank2;\n</code></pre>\n\n<p>I am assuming that you want to calculate the time between 'Initial' and 'Done' states.</p>\n\n<pre><code>+---------------------+----------------+\n| startdate | length_of_trip |\n+---------------------+----------------+\n| 2008-08-01 13:30:00 | 6 |\n+---------------------+----------------+\n</code></pre>\n" }, { "answer_id": 153902, "author": "Grant Johnson", "author_id": 12518, "author_profile": "https://Stackoverflow.com/users/12518", "pm_score": 0, "selected": false, "text": "<p>Ok, this is a bit beyond geeky, but I built a web application to track my wife's contractions just before we had a baby so that I could see from work when it was getting close to time to go to the hospital. Anyway, I built this basic thing fairly easily as two views.</p>\n\n<pre><code>create table contractions time_date timestamp primary key;\n\ncreate view contraction_time as\nSELECT a.time_date, max(b.prev_time) AS prev_time\n FROM contractions a, ( SELECT contractions.time_date AS prev_time\n FROM contractions) b\n WHERE b.prev_time &lt; a.time_date\n GROUP BY a.time_date;\n\ncreate view time_between as \nSELECT contraction_time.time_date, contraction_time.prev_time, contraction_time.time_date - contraction_time.prev_time\n FROM contraction_time;\n</code></pre>\n\n<p>This could be done as a subselect obviously as well, but I used the intermediate views for other things as well, and so this worked out well.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15805/" ]
I had this question in mind and since I just discovered this site I decided to post it here. Let's say I have a table with a timestamp and a state for a given "object" (generic meaning, not OOP object); is there an optimal way to calculate the time between a state and the next occurrence of another (or same) state (what I call a "trip") with a single SQL statement (inner SELECTs and UNIONs aren't counted)? Ex: For the following, the trip time between Initial and Done would be 6 days, but between Initial and Review it would be 2 days. > > 2008-08-01 13:30:00 - Initial > > 2008-08-02 13:30:00 - Work > > 2008-08-03 13:30:00 - Review > > 2008-08-04 13:30:00 - Work > > 2008-08-05 13:30:00 - Review > > 2008-08-06 13:30:00 - Accepted > > 2008-08-07 13:30:00 - Done > > > No need to be generic, just say what [SGBD](https://stackoverflow.com/questions/980813/what-is-sgbd) your solution is specific to if not generic.
Here's an Oracle methodology using an analytic function. ``` with data as ( SELECT 1 trip_id, to_date('20080801 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Initial' step from dual UNION ALL SELECT 1 trip_id, to_date('20080802 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL SELECT 1 trip_id, to_date('20080803 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL SELECT 1 trip_id, to_date('20080804 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL SELECT 1 trip_id, to_date('20080805 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL SELECT 1 trip_id, to_date('20080806 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Accepted' step from dual UNION ALL SELECT 1 trip_id, to_date('20080807 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Done' step from dual ) select trip_id, step, dt - lag(dt) over (partition by trip_id order by dt) trip_time from data / 1 Initial 1 Work 1 1 Review 1 1 Work 1 1 Review 1 1 Accepted 1 1 Done 1 ``` These are very commonly used in situations where traditionally we might use a self-join.
83,093
<p>is there a solution for batch insert via hibernate in partitioned postgresql table? currently i'm getting an error like this...</p> <pre><code>ERROR org.hibernate.jdbc.AbstractBatcher - Exception executing batch: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61) at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46) at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68).... </code></pre> <p>i have found this link <a href="http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html" rel="nofollow noreferrer">http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html</a> but i can't find anywhere on the web is this problem solved or how it can be get around</p>
[ { "answer_id": 90031, "author": "alexguev", "author_id": 436199, "author_profile": "https://Stackoverflow.com/users/436199", "pm_score": 3, "selected": true, "text": "<p>You might want to try using a custom Batcher by setting the hibernate.jdbc.factory_class property. Making sure hibernate won't check the update count of batch operations might fix your problem, you can achieve that by making your custom Batcher extend the class BatchingBatcher, and then overriding the method doExecuteBatch(...) to look like:</p>\n\n<pre><code> @Override\n protected void doExecuteBatch(PreparedStatement ps) throws SQLException, HibernateException {\n if ( batchSize == 0 ) {\n log.debug( \"no batched statements to execute\" );\n }\n else {\n if ( log.isDebugEnabled() ) {\n log.debug( \"Executing batch size: \" + batchSize );\n }\n\n try {\n// checkRowCounts( ps.executeBatch(), ps );\n ps.executeBatch();\n }\n catch (RuntimeException re) {\n log.error( \"Exception executing batch: \", re );\n throw re;\n }\n finally {\n batchSize = 0;\n }\n\n }\n\n }\n</code></pre>\n\n<p>Note that the new method doesn't check the results of executing the prepared statements. Keep in mind that making this change might affect hibernate in some unexpected way (or maybe not).</p>\n" }, { "answer_id": 92020, "author": "tropikalista", "author_id": 15878, "author_profile": "https://Stackoverflow.com/users/15878", "pm_score": 2, "selected": false, "text": "<p>thnx! it did the trick, no problems poped up, so far :)....one thing thou...\ni had to implement <code>BatcherFactory</code> class and put it int the <code>persistence.xml</code> file,\nlike this:</p>\n\n<pre><code>property name=\"hibernate.jdbc.factory_class\" value=\"path.to.my.batcher.factory.implementation\"\n</code></pre>\n\n<p>from that factory i've called my batcher implementation with the code above</p>\n\n<p>ps\nhibernate core 3.2.6 GA</p>\n\n<p>thanks once again</p>\n" }, { "answer_id": 2905374, "author": "Piotr Gwiazda", "author_id": 221951, "author_profile": "https://Stackoverflow.com/users/221951", "pm_score": 2, "selected": false, "text": "<p>They say to use two triggers in a partitioned table or the @SQLInsert annotation here: <a href=\"http://www.redhat.com/f/pdf/jbw/jmlodgenski_940_scaling_hibernate.pdf\" rel=\"nofollow noreferrer\">http://www.redhat.com/f/pdf/jbw/jmlodgenski_940_scaling_hibernate.pdf</a> pages 21-26 (it also mentions an @SQLInsert specifying a String method).</p>\n\n<p>Here is an example with an after trigger to delete the extra row in the master: <a href=\"https://gist.github.com/copiousfreetime/59067\" rel=\"nofollow noreferrer\">https://gist.github.com/copiousfreetime/59067</a></p>\n" }, { "answer_id": 26123701, "author": "rogerdpack", "author_id": 32453, "author_profile": "https://Stackoverflow.com/users/32453", "pm_score": 2, "selected": false, "text": "<p>Appears if you can use RULES instead of triggers for the insert, then it can return the right number, but only with a single RULE without a WHERE statement. </p>\n\n<p><a href=\"http://www.technology-ebay.de/the-teams/mobile-de/blog/postgresql-table-partitioning-hibernate.html\" rel=\"nofollow\">ref1</a></p>\n\n<p><a href=\"http://www.postgresql.org/docs/8.3/interactive/ddl-partitioning.html#DDL-PARTITIONING-ALTERNATIVES\" rel=\"nofollow\">ref2</a></p>\n\n<p><a href=\"http://grokbase.com/t/postgresql/pgsql-general/0863bjzths/insert-into-master-table-0-rows-affected-hibernate-problems\" rel=\"nofollow\">ref3</a></p>\n\n<p>another option may be to create a view that 'wraps' the partitioned table, then you return the NEW row out to indicate a successful row update, without accidentally adding an extra unwanted row to the master table. </p>\n\n<pre><code>create view tablename_view as select * from tablename; -- create trivial wrapping view\n\nCREATE OR REPLACE FUNCTION partitioned_insert_trigger() -- partitioned insert trigger\nRETURNS TRIGGER AS $$\nBEGIN\n IF (NEW.partition_key&gt;= 5500000000 AND\n NEW.partition_key &lt; 6000000000) THEN\n INSERT INTO tablename_55_59 VALUES (NEW.*);\n ELSIF (NEW.partition_key &gt;= 5000000000 AND\n NEW.partition_key &lt; 5500000000) THEN\n INSERT INTO tablename_50_54 VALUES (NEW.*);\n ELSIF (NEW.partition_key &gt;= 500000000 AND\n NEW.partition_key &lt; 1000000000) THEN\n INSERT INTO tablename_5_9 VALUES (NEW.*);\n ELSIF (NEW.partition_key &gt;= 0 AND\n NEW.partition_key &lt; 500000000) THEN\n INSERT INTO tablename_0_4 VALUES (NEW.*);\n ELSE\n RAISE EXCEPTION 'partition key is out of range. Fix the trigger function';\n END IF;\n RETURN NEW; -- RETURN NEW in this case, typically you'd return NULL from this trigger, but for views we return NEW\nEND;\n$$\nLANGUAGE plpgsql;\n\nCREATE TRIGGER insert_view_trigger\n INSTEAD OF INSERT ON tablename_view\n FOR EACH ROW EXECUTE PROCEDURE partitioned_insert_trigger(); -- create \"INSTEAD OF\" trigger\n</code></pre>\n\n<p>ref: <a href=\"http://www.postgresql.org/docs/9.2/static/trigger-definition.html\" rel=\"nofollow\">http://www.postgresql.org/docs/9.2/static/trigger-definition.html</a></p>\n\n<p>If you went the view wrapper route one option is to also define trivial \"instead of\" triggers for delete and update, as well, then you can just use the name of the view table in place of your normal table in all transactions.</p>\n\n<p>Another option that uses the view is to create an insert rule so that any inserts on the main table go to the view [which uses its trigger], ex (assuming you already have <code>partitioned_insert_trigger</code> and tablename_view and insert_view_trigger created as listed above)</p>\n\n<pre><code>create RULE use_right_inserter_tablename AS\n ON INSERT TO tablename\n DO INSTEAD insert into tablename_view VALUES (NEW.*);\n</code></pre>\n\n<p>Then it will use your new working view wrapper insert.</p>\n" }, { "answer_id": 43731288, "author": "Arun Kumar V", "author_id": 7950406, "author_profile": "https://Stackoverflow.com/users/7950406", "pm_score": 0, "selected": false, "text": "<p>I faced the same problem while inserting documents through hibernate after lot of search found that it is expecting that updated rows should be returned so instead of null change it to new in trigger procedure which will resolve the problem as shown below</p>\n\n<p>RETURN NEW</p>\n" }, { "answer_id": 52627573, "author": "blov80", "author_id": 4556112, "author_profile": "https://Stackoverflow.com/users/4556112", "pm_score": 0, "selected": false, "text": "<p>I found another solution for the same problem <a href=\"https://blog.akquinet.de/2015/08/04/postgresql-partitioned-tables-and-hibernate/\" rel=\"nofollow noreferrer\">on this webpage</a>:</p>\n\n<p>This suggests the same solution that @rogerdpack said, changing the <strong>Return Null</strong> to <strong>Return NEW</strong>, and adding a new trigger that deletes the duplicated tuple in the master with the query:</p>\n\n<pre><code>DELETE FROM ONLY master_table;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15878/" ]
is there a solution for batch insert via hibernate in partitioned postgresql table? currently i'm getting an error like this... ``` ERROR org.hibernate.jdbc.AbstractBatcher - Exception executing batch: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61) at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46) at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68).... ``` i have found this link <http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html> but i can't find anywhere on the web is this problem solved or how it can be get around
You might want to try using a custom Batcher by setting the hibernate.jdbc.factory\_class property. Making sure hibernate won't check the update count of batch operations might fix your problem, you can achieve that by making your custom Batcher extend the class BatchingBatcher, and then overriding the method doExecuteBatch(...) to look like: ``` @Override protected void doExecuteBatch(PreparedStatement ps) throws SQLException, HibernateException { if ( batchSize == 0 ) { log.debug( "no batched statements to execute" ); } else { if ( log.isDebugEnabled() ) { log.debug( "Executing batch size: " + batchSize ); } try { // checkRowCounts( ps.executeBatch(), ps ); ps.executeBatch(); } catch (RuntimeException re) { log.error( "Exception executing batch: ", re ); throw re; } finally { batchSize = 0; } } } ``` Note that the new method doesn't check the results of executing the prepared statements. Keep in mind that making this change might affect hibernate in some unexpected way (or maybe not).
83,132
<p>I thought I'd found the solution a while ago (see my <a href="https://tjrobinson.net/programming/technology/2006/09/03/cant-execute-code-from-a-freed-script.html" rel="noreferrer">blog</a>):</p> <blockquote> <p>If you ever get the JavaScript (or should that be JScript) error "Can't execute code from a freed script" - try moving any meta tags in the head so that they're before your script tags. </p> </blockquote> <p>...but based on one of the most recent blog comments, the fix I suggested may not work for everyone. I thought this would be a good one to open up to the StackOverflow community....</p> <p>What causes the error "Can't execute code from a freed script" and what are the solutions/workarounds?</p>
[ { "answer_id": 83570, "author": "pcorcoran", "author_id": 15992, "author_profile": "https://Stackoverflow.com/users/15992", "pm_score": 3, "selected": false, "text": "<p>This error can occur in MSIE when a child window tries to communicate with a parent window which is no longer open.</p>\n\n<p>(Not exactly the most helpful error message text in the world.)</p>\n" }, { "answer_id": 84300, "author": "Sjoerd Visscher", "author_id": 5852, "author_profile": "https://Stackoverflow.com/users/5852", "pm_score": 5, "selected": false, "text": "<p>You get this error when you call a function that was created in a window or frame that no longer exists. </p>\n\n<p>If you don't know in advance if the window still exists, you can do a try/catch to detect it:</p>\n\n<pre><code>try\n{\n f();\n}\ncatch(e)\n{\n if (e.number == -2146823277)\n // f is no longer available\n ...\n}\n</code></pre>\n" }, { "answer_id": 1360689, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p><strong>The error is caused when the 'parent' window of script is disposed (ie: closed) but a reference to the script which is still held (such as in another window) is invoked.</strong> Even though the 'object' is still alive, the context in which it wants to execute is not.</p>\n\n<p>It's somewhat dirty, but it works for my Windows Sidebar Gadget:</p>\n\n<p>Here is the general idea:\nThe 'main' window sets up a function which will eval'uate some code, yup, it's that ugly.\nThen a 'child' can call this \"builder function\" (which is /bound to the scope of the main window/) and get back a function which is also bound to the 'main' window. An obvious disadvantage is, of course, that the function being 'rebound' can't closure over the scope it is seemingly defined in... anyway, enough of the gibbering:</p>\n\n<p>This is partially pseudo-code, but I use a variant of it on a Windows Sidebar Gadget (I keep saying this because Sidebar Gadgets run in \"unrestricted zone 0\", which may -- or may not -- change the scenario greatly.)</p>\n\n<pre><code>\n// This has to be setup from the main window, not a child/etc!\nmainWindow.functionBuilder = function (func, args) {\n // trim the name, if any\n var funcStr = (\"\" + func).replace(/^function\\s+[^\\s(]+\\s*\\(/, \"function (\")\n try {\n var rebuilt\n eval(\"rebuilt = (\" + funcStr + \")\")\n return rebuilt(args)\n } catch (e) {\n alert(\"oops! \" + e.message)\n }\n}\n\n// then in the child, as an example\n// as stated above, even though function (args) looks like it's \n// a closure in the child scope, IT IS NOT. There you go :)\nvar x = {blerg: 2}\nfunctionInMainWindowContenxt = mainWindow.functionBuilder(function (args) {\n // in here args is in the bound scope -- have at the child objects! :-/\n function fn (blah) {\n return blah * args.blerg\n }\n return fn\n}, x)\n\nx.blerg = 7\nfunctionInMainWindowContext(6) // -> 42 if I did my math right\n</code></pre>\n\n<p>As a variant, the main window should be able to pass the functionBuilder function to the child window -- as long as the functionBuilder function is defined in the main window context!</p>\n\n<p>I feel like I used too many words. YMMV.</p>\n" }, { "answer_id": 2806980, "author": "aaron", "author_id": 330176, "author_profile": "https://Stackoverflow.com/users/330176", "pm_score": 3, "selected": false, "text": "<p>Here's a very specific case in which I've seen this behavior. It is reproducible for me in IE6 and IE7.</p>\n\n<p>From within an iframe:</p>\n\n<pre><code>window.parent.mySpecialHandler = function() { ...work... }\n</code></pre>\n\n<p>Then, after reloading the iframe with new content, in the window containing the iframe:</p>\n\n<pre><code>window.mySpecialHandler();\n</code></pre>\n\n<p>This call fails with \"Can't execute code from a freed script\" because mySpecialHandler was defined in a context (the iframe's original DOM) that no longer exits. (Reloading the iframe destroyed this context.)</p>\n\n<p>You can however safely set \"serializeable\" values (primitives, object graphs that don't reference functions directly) in the parent window. If you really need a separate window (in my case, an iframe) to specify some work to a remote window, you can pass the work as a String and \"eval\" it in the receiver. Be careful with this, it generally doesn't make for a clean or secure implementation.</p>\n" }, { "answer_id": 6668743, "author": "Tom", "author_id": 841284, "author_profile": "https://Stackoverflow.com/users/841284", "pm_score": 3, "selected": false, "text": "<p>Beginning in IE9 we began receiving this error when calling .getTime() on a Date object stored in an Array within another Object. The solution was to make sure it was a Date before calling Date methods:</p>\n\n<p>Fail: <code>rowTime = wl.rowData[a][12].getTime()</code></p>\n\n<p>Pass: <code>rowTime = new Date(wl.rowData[a][12]).getTime()</code></p>\n" }, { "answer_id": 10369456, "author": "Nathan Crause", "author_id": 251930, "author_profile": "https://Stackoverflow.com/users/251930", "pm_score": 1, "selected": false, "text": "<p>This isn't really an answer, but more an example of where this precisely happens.</p>\n\n<p>We have frame A and frame B (this wasn't my idea, but I have to live with it). Frame A never changes, Frame B changes constantly. We cannot apply code changes directly into frame A, so (per the vendor's instructions) we can only run JavaScript in frame B - the exact frame that keeps changing.</p>\n\n<p>We have a piece of JavaScript that needs to run every 5 seconds, so the JavaScript in frame B create a new script tag and inserts into into the head section of frame B. The setInterval exists in this new scripts (the one injected), as well as the function to invoke. Even though the injected JavaScript is technically loaded by frame A (since it now contains the script tag), once frame B changes, the function is no longer accessible by the setInterval.</p>\n" }, { "answer_id": 15973195, "author": "Melanie", "author_id": 282152, "author_profile": "https://Stackoverflow.com/users/282152", "pm_score": 0, "selected": false, "text": "<p>I got this error in IE9 within a page that eventually opens an iFrame. As long as the iFrame wasn't open, I could use localStorage. Once the iFrame was opened and closed, I wasn't able to use the localStorage anymore because of this error. To fix it, I had to add this code to in the Javascript that was inside the iFrame and also using the localStorage.</p>\n\n<pre><code>if (window.parent) {\n localStorage = window.parent.localStorage;\n}\n</code></pre>\n" }, { "answer_id": 16844211, "author": "wycleffsean", "author_id": 394184, "author_profile": "https://Stackoverflow.com/users/394184", "pm_score": 2, "selected": false, "text": "<p>I ran into this problem when inside of a child frame I added a reference type to the top level window and attempted to access it after the child window reloaded</p>\n\n<p>i.e.</p>\n\n<pre><code>// set the value on first load\nwindow.top.timestamp = new Date();\n\n// after frame reloads, try to access the value\nif(window.top.timestamp) // &lt;--- Raises exception\n...\n</code></pre>\n\n<p>I was able to resolve the issue by using only primitive types</p>\n\n<pre><code>// set the value on first load\nwindow.top.timestamp = Number(new Date());\n</code></pre>\n" }, { "answer_id": 22020346, "author": "Grzegorz Ciwoniuk", "author_id": 1452958, "author_profile": "https://Stackoverflow.com/users/1452958", "pm_score": 3, "selected": false, "text": "<p>If you are trying to access the JS object, the easiest way is to create a copy:</p>\n\n<pre><code>var objectCopy = JSON.parse(JSON.stringify(object));\n</code></pre>\n\n<p>Hope it'll help.</p>\n" }, { "answer_id": 30230015, "author": "panky sharma", "author_id": 1020477, "author_profile": "https://Stackoverflow.com/users/1020477", "pm_score": 0, "selected": false, "text": "<p>got this error in DHTMLX while opening a dialogue &amp; parent id or current window id not found </p>\n\n<pre><code> $(document).ready(function () {\n\n if (parent.dxWindowMngr == undefined) return;\n DhtmlxJS.GetCurrentWindow('wnManageConDlg').show();\n\n});\n</code></pre>\n\n<p>Just make sure you are sending correct curr/parent window id while opening a dialogue</p>\n" }, { "answer_id": 44517989, "author": "Chan", "author_id": 3247575, "author_profile": "https://Stackoverflow.com/users/3247575", "pm_score": 0, "selected": false, "text": "<p>On update of iframe's src i am getting that error.</p>\n\n<p>Got that error by accessing an event(click in my case) of an element in the main window like this (calling the main/outmost window directly): </p>\n\n<pre><code>top.$(\"#settings\").on(\"click\",function(){\n $(\"#settings_modal\").modal(\"show\");\n}); \n</code></pre>\n\n<p>I just changed it like this and it works fine (calling the parent of the parent of the iframe window):</p>\n\n<pre><code>$('#settings', window.parent.parent.document).on(\"click\",function(){ \n $(\"#settings_modal\").modal(\"show\"); \n});\n</code></pre>\n\n<p>My iframe containing the modal is also inside another iframe.</p>\n" }, { "answer_id": 52804201, "author": "pavan kumar", "author_id": 9556120, "author_profile": "https://Stackoverflow.com/users/9556120", "pm_score": 0, "selected": false, "text": "<p>The explanations are very relevant in the previous answers. Just trying to provide my scenario. Hope this can help others.</p>\n\n<p>we were using:</p>\n\n<pre><code>&lt;script&gt; window.document.writeln(table) &lt;/script&gt;\n</code></pre>\n\n<p>, and calling other functions in the script on <code>onchange</code> events but writeln completely overrides the HTML in IE where as it is having different behavior in chrome.</p>\n\n<p>we changed it to:</p>\n\n<pre><code>&lt;script&gt; window.document.body.innerHTML = table;&lt;/script&gt; \n</code></pre>\n\n<p>Thus retained the script which fixed the issue.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12124/" ]
I thought I'd found the solution a while ago (see my [blog](https://tjrobinson.net/programming/technology/2006/09/03/cant-execute-code-from-a-freed-script.html)): > > If you ever get the JavaScript (or should that be JScript) error "Can't execute code from a freed script" - try moving any meta tags in the head so that they're before your script tags. > > > ...but based on one of the most recent blog comments, the fix I suggested may not work for everyone. I thought this would be a good one to open up to the StackOverflow community.... What causes the error "Can't execute code from a freed script" and what are the solutions/workarounds?
You get this error when you call a function that was created in a window or frame that no longer exists. If you don't know in advance if the window still exists, you can do a try/catch to detect it: ``` try { f(); } catch(e) { if (e.number == -2146823277) // f is no longer available ... } ```
83,152
<p>Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#?</p>
[ { "answer_id": 83166, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 1, "selected": false, "text": "<p>You could look into this:\n<a href=\"http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx</a>\nIt's not completely free, but it looks very nice.</p>\n\n<p>Alex</p>\n" }, { "answer_id": 83186, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://sourceforge.net/projects/clown/\" rel=\"nofollow noreferrer\">PDFClown</a> might help, but I would not recommend it for a big or heavy use application.</p>\n" }, { "answer_id": 83208, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 0, "selected": false, "text": "<p>There is also LibHaru</p>\n\n<p><a href=\"http://libharu.org/wiki/Main_Page\" rel=\"nofollow noreferrer\">http://libharu.org/wiki/Main_Page</a></p>\n" }, { "answer_id": 83238, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>iText is the best library I know. Originally written in Java, there is a .NET port as well.</p>\n\n<p>See <a href=\"http://www.ujihara.jp/iTextdotNET/en/\" rel=\"nofollow noreferrer\">http://www.ujihara.jp/iTextdotNET/en/</a></p>\n" }, { "answer_id": 83372, "author": "Ben McEvoy", "author_id": 15234, "author_profile": "https://Stackoverflow.com/users/15234", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.c-sharpcorner.com/UploadFile/psingh/PDFFileGenerator12062005235236PM/PDFFileGenerator.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/psingh/PDFFileGenerator12062005235236PM/PDFFileGenerator.aspx</a> is open source and may be a good starting point for you.</p>\n" }, { "answer_id": 84410, "author": "ceetheman", "author_id": 16154, "author_profile": "https://Stackoverflow.com/users/16154", "pm_score": 6, "selected": false, "text": "<p><strong><a href=\"https://github.com/itext/itextsharp\" rel=\"noreferrer\">iTextSharp</a></strong> is the best bet. Used it to make a spider for lucene.Net so that it could crawl PDF.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing iTextSharp.text.pdf;\nusing System.Text.RegularExpressions;\n\nnamespace Spider.Utils\n{\n /// &lt;summary&gt;\n /// Parses a PDF file and extracts the text from it.\n /// &lt;/summary&gt;\n public class PDFParser\n {\n /// BT = Beginning of a text object operator \n /// ET = End of a text object operator\n /// Td move to the start of next line\n /// 5 Ts = superscript\n /// -5 Ts = subscript\n\n #region Fields\n\n #region _numberOfCharsToKeep\n /// &lt;summary&gt;\n /// The number of characters to keep, when extracting text.\n /// &lt;/summary&gt;\n private static int _numberOfCharsToKeep = 15;\n #endregion\n\n #endregion\n\n #region ExtractText\n /// &lt;summary&gt;\n /// Extracts a text from a PDF file.\n /// &lt;/summary&gt;\n /// &lt;param name=\"inFileName\"&gt;the full path to the pdf file.&lt;/param&gt;\n /// &lt;param name=\"outFileName\"&gt;the output file name.&lt;/param&gt;\n /// &lt;returns&gt;the extracted text&lt;/returns&gt;\n public bool ExtractText(string inFileName, string outFileName)\n {\n StreamWriter outFile = null;\n try\n {\n // Create a reader for the given PDF file\n PdfReader reader = new PdfReader(inFileName);\n //outFile = File.CreateText(outFileName);\n outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);\n\n Console.Write(\"Processing: \");\n\n int totalLen = 68;\n float charUnit = ((float)totalLen) / (float)reader.NumberOfPages;\n int totalWritten = 0;\n float curUnit = 0;\n\n for (int page = 1; page &lt;= reader.NumberOfPages; page++)\n {\n outFile.Write(ExtractTextFromPDFBytes(reader.GetPageContent(page)) + \" \");\n\n // Write the progress.\n if (charUnit &gt;= 1.0f)\n {\n for (int i = 0; i &lt; (int)charUnit; i++)\n {\n Console.Write(\"#\");\n totalWritten++;\n }\n }\n else\n {\n curUnit += charUnit;\n if (curUnit &gt;= 1.0f)\n {\n for (int i = 0; i &lt; (int)curUnit; i++)\n {\n Console.Write(\"#\");\n totalWritten++;\n }\n curUnit = 0;\n }\n\n }\n }\n\n if (totalWritten &lt; totalLen)\n {\n for (int i = 0; i &lt; (totalLen - totalWritten); i++)\n {\n Console.Write(\"#\");\n }\n }\n return true;\n }\n catch\n {\n return false;\n }\n finally\n {\n if (outFile != null) outFile.Close();\n }\n }\n #endregion\n\n #region ExtractTextFromPDFBytes\n /// &lt;summary&gt;\n /// This method processes an uncompressed Adobe (text) object \n /// and extracts text.\n /// &lt;/summary&gt;\n /// &lt;param name=\"input\"&gt;uncompressed&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public string ExtractTextFromPDFBytes(byte[] input)\n {\n if (input == null || input.Length == 0) return \"\";\n\n try\n {\n string resultString = \"\";\n\n // Flag showing if we are we currently inside a text object\n bool inTextObject = false;\n\n // Flag showing if the next character is literal \n // e.g. '\\\\' to get a '\\' character or '\\(' to get '('\n bool nextLiteral = false;\n\n // () Bracket nesting level. Text appears inside ()\n int bracketDepth = 0;\n\n // Keep previous chars to get extract numbers etc.:\n char[] previousCharacters = new char[_numberOfCharsToKeep];\n for (int j = 0; j &lt; _numberOfCharsToKeep; j++) previousCharacters[j] = ' ';\n\n\n for (int i = 0; i &lt; input.Length; i++)\n {\n char c = (char)input[i];\n if (input[i] == 213)\n c = \"'\".ToCharArray()[0];\n\n if (inTextObject)\n {\n // Position the text\n if (bracketDepth == 0)\n {\n if (CheckToken(new string[] { \"TD\", \"Td\" }, previousCharacters))\n {\n resultString += \"\\n\\r\";\n }\n else\n {\n if (CheckToken(new string[] { \"'\", \"T*\", \"\\\"\" }, previousCharacters))\n {\n resultString += \"\\n\";\n }\n else\n {\n if (CheckToken(new string[] { \"Tj\" }, previousCharacters))\n {\n resultString += \" \";\n }\n }\n }\n }\n\n // End of a text object, also go to a new line.\n if (bracketDepth == 0 &amp;&amp;\n CheckToken(new string[] { \"ET\" }, previousCharacters))\n {\n\n inTextObject = false;\n resultString += \" \";\n }\n else\n {\n // Start outputting text\n if ((c == '(') &amp;&amp; (bracketDepth == 0) &amp;&amp; (!nextLiteral))\n {\n bracketDepth = 1;\n }\n else\n {\n // Stop outputting text\n if ((c == ')') &amp;&amp; (bracketDepth == 1) &amp;&amp; (!nextLiteral))\n {\n bracketDepth = 0;\n }\n else\n {\n // Just a normal text character:\n if (bracketDepth == 1)\n {\n // Only print out next character no matter what. \n // Do not interpret.\n if (c == '\\\\' &amp;&amp; !nextLiteral)\n {\n resultString += c.ToString();\n nextLiteral = true;\n }\n else\n {\n if (((c &gt;= ' ') &amp;&amp; (c &lt;= '~')) ||\n ((c &gt;= 128) &amp;&amp; (c &lt; 255)))\n {\n resultString += c.ToString();\n }\n\n nextLiteral = false;\n }\n }\n }\n }\n }\n }\n\n // Store the recent characters for \n // when we have to go back for a checking\n for (int j = 0; j &lt; _numberOfCharsToKeep - 1; j++)\n {\n previousCharacters[j] = previousCharacters[j + 1];\n }\n previousCharacters[_numberOfCharsToKeep - 1] = c;\n\n // Start of a text object\n if (!inTextObject &amp;&amp; CheckToken(new string[] { \"BT\" }, previousCharacters))\n {\n inTextObject = true;\n }\n }\n\n return CleanupContent(resultString);\n }\n catch\n {\n return \"\";\n }\n }\n\n private string CleanupContent(string text)\n {\n string[] patterns = { @\"\\\\\\(\", @\"\\\\\\)\", @\"\\\\226\", @\"\\\\222\", @\"\\\\223\", @\"\\\\224\", @\"\\\\340\", @\"\\\\342\", @\"\\\\344\", @\"\\\\300\", @\"\\\\302\", @\"\\\\304\", @\"\\\\351\", @\"\\\\350\", @\"\\\\352\", @\"\\\\353\", @\"\\\\311\", @\"\\\\310\", @\"\\\\312\", @\"\\\\313\", @\"\\\\362\", @\"\\\\364\", @\"\\\\366\", @\"\\\\322\", @\"\\\\324\", @\"\\\\326\", @\"\\\\354\", @\"\\\\356\", @\"\\\\357\", @\"\\\\314\", @\"\\\\316\", @\"\\\\317\", @\"\\\\347\", @\"\\\\307\", @\"\\\\371\", @\"\\\\373\", @\"\\\\374\", @\"\\\\331\", @\"\\\\333\", @\"\\\\334\", @\"\\\\256\", @\"\\\\231\", @\"\\\\253\", @\"\\\\273\", @\"\\\\251\", @\"\\\\221\"};\n string[] replace = { \"(\", \")\", \"-\", \"'\", \"\\\"\", \"\\\"\", \"à\", \"â\", \"ä\", \"À\", \"Â\", \"Ä\", \"é\", \"è\", \"ê\", \"ë\", \"É\", \"È\", \"Ê\", \"Ë\", \"ò\", \"ô\", \"ö\", \"Ò\", \"Ô\", \"Ö\", \"ì\", \"î\", \"ï\", \"Ì\", \"Î\", \"Ï\", \"ç\", \"Ç\", \"ù\", \"û\", \"ü\", \"Ù\", \"Û\", \"Ü\", \"®\", \"™\", \"«\", \"»\", \"©\", \"'\" };\n\n for (int i = 0; i &lt; patterns.Length; i++)\n {\n string regExPattern = patterns[i];\n Regex regex = new Regex(regExPattern, RegexOptions.IgnoreCase);\n text = regex.Replace(text, replace[i]);\n }\n\n return text;\n }\n\n #endregion\n\n #region CheckToken\n /// &lt;summary&gt;\n /// Check if a certain 2 character token just came along (e.g. BT)\n /// &lt;/summary&gt;\n /// &lt;param name=\"tokens\"&gt;the searched token&lt;/param&gt;\n /// &lt;param name=\"recent\"&gt;the recent character array&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private bool CheckToken(string[] tokens, char[] recent)\n {\n foreach (string token in tokens)\n {\n if ((recent[_numberOfCharsToKeep - 3] == token[0]) &amp;&amp;\n (recent[_numberOfCharsToKeep - 2] == token[1]) &amp;&amp;\n ((recent[_numberOfCharsToKeep - 1] == ' ') ||\n (recent[_numberOfCharsToKeep - 1] == 0x0d) ||\n (recent[_numberOfCharsToKeep - 1] == 0x0a)) &amp;&amp;\n ((recent[_numberOfCharsToKeep - 4] == ' ') ||\n (recent[_numberOfCharsToKeep - 4] == 0x0d) ||\n (recent[_numberOfCharsToKeep - 4] == 0x0a))\n )\n {\n return true;\n }\n }\n return false;\n }\n #endregion\n }\n}\n</code></pre>\n" }, { "answer_id": 84479, "author": "Kuvo", "author_id": 12623, "author_profile": "https://Stackoverflow.com/users/12623", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.aspose.com/\" rel=\"nofollow noreferrer\">aspose pdf</a> works pretty well. then again, you have to pay for it</p>\n" }, { "answer_id": 5002998, "author": "ShravankumarKumar ", "author_id": 617652, "author_profile": "https://Stackoverflow.com/users/617652", "pm_score": 3, "selected": false, "text": "<pre><code>public string ReadPdfFile(object Filename, DataTable ReadLibray)\n{\n PdfReader reader2 = new PdfReader((string)Filename);\n string strText = string.Empty;\n\n for (int page = 1; page &lt;= reader2.NumberOfPages; page++)\n {\n ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();\n PdfReader reader = new PdfReader((string)Filename);\n String s = PdfTextExtractor.GetTextFromPage(reader, page, its);\n\n s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));\n strText = strText + s;\n reader.Close();\n }\n return strText;\n}\n</code></pre>\n" }, { "answer_id": 7985501, "author": "Brock Nusser", "author_id": 1026269, "author_profile": "https://Stackoverflow.com/users/1026269", "pm_score": 8, "selected": true, "text": "<p>Since this question was last answered in 2008, iTextSharp has improved their api dramatically. If you download the latest version of their api from <a href=\"http://sourceforge.net/projects/itextsharp/\" rel=\"noreferrer\">http://sourceforge.net/projects/itextsharp/</a>, you can use the following snippet of code to extract all text from a pdf into a string.</p>\n\n<pre><code>using iTextSharp.text.pdf;\nusing iTextSharp.text.pdf.parser;\n\nnamespace PdfParser\n{\n public static class PdfTextExtractor\n {\n public static string pdfText(string path)\n {\n PdfReader reader = new PdfReader(path);\n string text = string.Empty;\n for(int page = 1; page &lt;= reader.NumberOfPages; page++)\n {\n text += PdfTextExtractor.GetTextFromPage(reader,page);\n }\n reader.Close();\n return text;\n } \n }\n}\n</code></pre>\n" }, { "answer_id": 8508478, "author": "Bobrovsky", "author_id": 249690, "author_profile": "https://Stackoverflow.com/users/249690", "pm_score": 0, "selected": false, "text": "<p>Have a look at <a href=\"https://bitmiracle.com/pdf-library/\" rel=\"nofollow noreferrer\">Docotic.Pdf library</a>. It does not require you to make source code of your application open (like iTextSharp with viral AGPL 3 license, for example).</p>\n<p>Docotic.Pdf can be used to read PDF files and extract text with or without formatting. Please have a look at the article that shows <a href=\"https://bitmiracle.com/blog/extract-text-from-pdf-in-net\" rel=\"nofollow noreferrer\">how to extract text from PDFs</a>.</p>\n<p>Disclaimer: I work for Bit Miracle, vendor of the library.</p>\n" }, { "answer_id": 12188974, "author": "Dobermaxx99", "author_id": 1631890, "author_profile": "https://Stackoverflow.com/users/1631890", "pm_score": 2, "selected": false, "text": "<p>itext?</p>\n\n<p><a href=\"http://www.itextpdf.com/terms-of-use/index.php\" rel=\"nofollow\">http://www.itextpdf.com/terms-of-use/index.php</a></p>\n\n<p>Guide</p>\n\n<p><a href=\"http://www.vogella.com/articles/JavaPDF/article.html\" rel=\"nofollow\">http://www.vogella.com/articles/JavaPDF/article.html</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6777/" ]
Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#?
Since this question was last answered in 2008, iTextSharp has improved their api dramatically. If you download the latest version of their api from <http://sourceforge.net/projects/itextsharp/>, you can use the following snippet of code to extract all text from a pdf into a string. ``` using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace PdfParser { public static class PdfTextExtractor { public static string pdfText(string path) { PdfReader reader = new PdfReader(path); string text = string.Empty; for(int page = 1; page <= reader.NumberOfPages; page++) { text += PdfTextExtractor.GetTextFromPage(reader,page); } reader.Close(); return text; } } } ```
83,156
<p>Ok, I have been working with Solaris for a 10+ years, and have never seen this...</p> <p>I have a directory listing which includes both a file and subdirectory with the same name:</p> <pre><code>-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehan drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan </code></pre> <p>I use file to discover contents of the file, and I get:</p> <pre><code>bash-2.03# file msheehan msheehan: directory bash-2.03# file msh* msheehan: ascii text msheehan: directory </code></pre> <p>I am not worried about the file, but I want to keep the directory, so I try rm:</p> <pre><code>bash-2.03# rm msheehan rm: msheehan is a directory </code></pre> <p>So here is my two part question:</p> <ol> <li>What's up with this?</li> <li>How do I carefully delete the file?</li> </ol> <p>Jonathan</p> <p>Edit: Thanks for the answers guys, both (so far) were helpful, but piping the listing to an editor did the trick, ala:</p> <pre><code>bash-2.03# ls -l &gt; jb.txt bash-2.03# vi jb.txt </code></pre> <p>Which contained:</p> <pre><code>-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehab^?n drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan </code></pre> <p>Always be careful with the backspace key!</p>
[ { "answer_id": 83168, "author": "Jonathan Bourke", "author_id": 8361, "author_profile": "https://Stackoverflow.com/users/8361", "pm_score": 0, "selected": false, "text": "<p>And a quick answer to part 2 of my own question...</p>\n\n<p>I would imagine I could rename the directory, delete the file, and rename the directory back to it's original again. </p>\n\n<p>... I would still be interested to see what other people come up with.</p>\n\n<p>JB</p>\n" }, { "answer_id": 83224, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": 0, "selected": false, "text": "<p>I suspect that one of them has a strange character in the name. You could try using the shell wildcard expansion to see that: type </p>\n\n<pre><code>cat msh*\n</code></pre>\n\n<p>and press the wildcard expansion key (in my shell it's Ctrl-X *). You should get two names listed, perhaps one of which has an escape character in it.</p>\n" }, { "answer_id": 83281, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 4, "selected": true, "text": "<p>I would guess that these are in fact two different filenames that \"look\" the same, as the command file was able to distinguish them when the shell passed the expanded versions of the name in. Try piping ls into od or another hex/octal dump utility to see if they really have the same name, or if there are non-printing characters involved.</p>\n" }, { "answer_id": 83644, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "<p>I'm wondering what could cause this. Aside from filesystem bugs, it could be caused by a non-ascii chararacter that got through somehow. In that case, use another language with easier string semantics to do the operation.</p>\n\n<p>It would be interesting to see what would be the output of this ruby snippet:</p>\n\n<pre><code>ruby -e 'puts Dir[\"msheehan*\"].inspect'\n</code></pre>\n" }, { "answer_id": 90053, "author": "Alan H", "author_id": 3807, "author_profile": "https://Stackoverflow.com/users/3807", "pm_score": 0, "selected": false, "text": "<p>To see if there are special characters in your file, Try the -b or -q options to ls,\nassuming solaris 8 has those options.</p>\n\n<p>As another solution to deleting the file you can bring up the graphical file browser\n(gasp!) and drag and drop the unwanted file to the trash.</p>\n\n<p>Another solution might be to move the one file to a different name (the one without the unknown special character), then delete the special character directory name with wildcards.</p>\n\n<pre><code>mv msheehan temp\nrm mshee*\nmv temp msheehan\n</code></pre>\n\n<p>Of course, you want to be sure that only the file you want to delete matches the wildcard.\nAnd, for your particular case, since one was a directory and the other a file, this command might have solved it all:</p>\n\n<pre><code>rmdir msheeha*\n</code></pre>\n" }, { "answer_id": 107279, "author": "TLS", "author_id": 19417, "author_profile": "https://Stackoverflow.com/users/19417", "pm_score": 0, "selected": false, "text": "<p>One quick-and-easy way to see non-printing characters and whitespace is to pipe the output through <em>cat -vet</em>, e.g.:</p>\n\n<pre>\n# ls -l | cat -vet\n</pre>\n\n<p>Nice and easy to remember!</p>\n" }, { "answer_id": 196263, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>For part 2, since one name contains two extra characters, you can use:</p>\n\n<pre><code>mv sheehan abc\nmv sheeha??n xyz\n</code></pre>\n\n<p>Once you've done that, you've got sane file names again, that you can fix up as you need.</p>\n" }, { "answer_id": 4207909, "author": "itilys", "author_id": 510706, "author_profile": "https://Stackoverflow.com/users/510706", "pm_score": 1, "selected": false, "text": "<p>You can delete using the iNode</p>\n\n<p>If you use the \"-i\" option in \"ls\"</p>\n\n<pre><code>$ ls -li\ntotal 1\n20801 -rw-r--r-- 1 root root 0 2010-11-08 01:55 a?\n20802 -rw-r--r-- 1 root root 0 2010-11-08 01:55 a\\?\n$ find . -inum 20802 -exec rm {} \\;\n$ ls -li\ntotal 1\n20801 -rw-r--r-- 1 root root 0 2010-11-08 01:55 a?\n</code></pre>\n\n<p>I've an example (in Spanish) how you can delete a file using then iNode on Solaris\n<a href=\"http://sparcki.blogspot.com/2010/03/como-eliminar-archivos-utilizando-su.html\" rel=\"nofollow\">http://sparcki.blogspot.com/2010/03/como-eliminar-archivos-utilizando-su.html</a></p>\n\n<p>Urko,</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8361/" ]
Ok, I have been working with Solaris for a 10+ years, and have never seen this... I have a directory listing which includes both a file and subdirectory with the same name: ``` -rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehan drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan ``` I use file to discover contents of the file, and I get: ``` bash-2.03# file msheehan msheehan: directory bash-2.03# file msh* msheehan: ascii text msheehan: directory ``` I am not worried about the file, but I want to keep the directory, so I try rm: ``` bash-2.03# rm msheehan rm: msheehan is a directory ``` So here is my two part question: 1. What's up with this? 2. How do I carefully delete the file? Jonathan Edit: Thanks for the answers guys, both (so far) were helpful, but piping the listing to an editor did the trick, ala: ``` bash-2.03# ls -l > jb.txt bash-2.03# vi jb.txt ``` Which contained: ``` -rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehab^?n drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan ``` Always be careful with the backspace key!
I would guess that these are in fact two different filenames that "look" the same, as the command file was able to distinguish them when the shell passed the expanded versions of the name in. Try piping ls into od or another hex/octal dump utility to see if they really have the same name, or if there are non-printing characters involved.
83,159
<p>Some API returns me XmlCursor pointing on root of XML Document. I need to insert all of this into another org.w3c.DOM represented document.</p> <p>At start: XmlCursor poiting on <code></p> <p>&lt;a&gt; &lt;b&gt; some text &lt;/b&gt; &lt;/a&gt; </code></p> <p>DOM Document: <code></p> <p>&lt;foo&gt;</p> <p>&lt;/foo&gt; </code></p> <p>At the end I want to have original DOM document changed like this: <code></p> <p>&lt;foo&gt;</p> <p>&nbsp;&nbsp;&lt;someOtherInsertedElement&gt;</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&lt;a&gt; &lt;b&gt; some text &lt;/b&gt; &lt;/a&gt;</p> <p>&nbsp;&nbsp;&lt;/someOtherInsertedElement&gt;</p> <p>&lt;/foo&gt; </code></p> <p>NOTE: <code>document.importNode(cursor.getDomNode())</code> doesn't work - Exception is thrown: <em>NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation.</em></p>
[ { "answer_id": 83256, "author": "Sietse", "author_id": 6400, "author_profile": "https://Stackoverflow.com/users/6400", "pm_score": 4, "selected": true, "text": "<p>Try something like this:</p>\n\n<pre><code>Node originalNode = cursor.getDomNode();\nNode importNode = document.importNode(originalNode.getFirstChild());\nNode otherNode = document.createElement(\"someOtherInsertedElement\");\notherNode.appendChild(importNode);\ndocument.appendChild(otherNode);\n</code></pre>\n\n<p>So in other words:</p>\n\n<ol>\n<li>Get the DOM Node from the cursor. In this case, it's a DOMDocument, so do getFirstChild() to get the root node.</li>\n<li>Import it into the DOMDocument. </li>\n<li>Do other stuff with the DOMDocument.</li>\n<li>Append the imported node to the right Node.</li>\n</ol>\n\n<p>The reason to import is that a node always \"belongs\" to a given DOMDocument. Just adding the original node would cause exceptions.</p>\n" }, { "answer_id": 13199479, "author": "Techky", "author_id": 1106225, "author_profile": "https://Stackoverflow.com/users/1106225", "pm_score": 1, "selected": false, "text": "<p>I was having the same issue.</p>\n\n<p>This was failing:</p>\n\n<p><code>Node importNode = document.importNode(originalNode);</code></p>\n\n<p>This fixed the problem:</p>\n\n<p><code>Node importNode = document.importNode(originalNode.getFirstChild());</code></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1128722/" ]
Some API returns me XmlCursor pointing on root of XML Document. I need to insert all of this into another org.w3c.DOM represented document. At start: XmlCursor poiting on <a> <b> some text </b> </a> DOM Document: <foo> </foo> At the end I want to have original DOM document changed like this: <foo>   <someOtherInsertedElement>     <a> <b> some text </b> </a>   </someOtherInsertedElement> </foo> NOTE: `document.importNode(cursor.getDomNode())` doesn't work - Exception is thrown: *NOT\_SUPPORTED\_ERR: The implementation does not support the requested type of object or operation.*
Try something like this: ``` Node originalNode = cursor.getDomNode(); Node importNode = document.importNode(originalNode.getFirstChild()); Node otherNode = document.createElement("someOtherInsertedElement"); otherNode.appendChild(importNode); document.appendChild(otherNode); ``` So in other words: 1. Get the DOM Node from the cursor. In this case, it's a DOMDocument, so do getFirstChild() to get the root node. 2. Import it into the DOMDocument. 3. Do other stuff with the DOMDocument. 4. Append the imported node to the right Node. The reason to import is that a node always "belongs" to a given DOMDocument. Just adding the original node would cause exceptions.
83,232
<p>I'm looking for a key/value pair object that I can include in a web service.</p> <p>I tried using .NET's <a href="http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx" rel="noreferrer"><code>System.Collections.Generic.KeyValuePair&lt;&gt;</code></a> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.</p> <p>Is there any other generic class that can be used for this situation?</p> <p>I'd use .NET's <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx" rel="noreferrer"><code>System.Web.UI.Pair</code></a> class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.</p>
[ { "answer_id": 83265, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 8, "selected": true, "text": "<p>Just define a struct/class.</p>\n\n<pre><code>[Serializable]\npublic struct KeyValuePair&lt;K,V&gt;\n{\n public K Key {get;set;}\n public V Value {get;set;}\n}\n</code></pre>\n" }, { "answer_id": 83336, "author": "Compile This", "author_id": 4048, "author_profile": "https://Stackoverflow.com/users/4048", "pm_score": 5, "selected": false, "text": "<p>I don't think there is as <code>Dictionary&lt;&gt;</code> itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the <code>Dictionary&lt;&gt;</code> object myself and adding support for <code>IXMLSerializable</code>.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Represents an XML serializable collection of keys and values.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"TKey\"&gt;The type of the keys in the dictionary.&lt;/typeparam&gt;\n/// &lt;typeparam name=\"TValue\"&gt;The type of the values in the dictionary.&lt;/typeparam&gt;\n[XmlRoot(\"dictionary\")]\npublic class SerializableDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;, IXmlSerializable\n{\n #region Constants\n\n /// &lt;summary&gt;\n /// The default XML tag name for an item.\n /// &lt;/summary&gt;\n private const string DEFAULT_ITEM_TAG = \"Item\";\n\n /// &lt;summary&gt;\n /// The default XML tag name for a key.\n /// &lt;/summary&gt;\n private const string DEFAULT_KEY_TAG = \"Key\";\n\n /// &lt;summary&gt;\n /// The default XML tag name for a value.\n /// &lt;/summary&gt;\n private const string DEFAULT_VALUE_TAG = \"Value\";\n\n #endregion\n\n #region Protected Properties\n\n /// &lt;summary&gt;\n /// Gets the XML tag name for an item.\n /// &lt;/summary&gt;\n protected virtual string ItemTagName\n {\n get\n {\n return DEFAULT_ITEM_TAG;\n }\n }\n\n /// &lt;summary&gt;\n /// Gets the XML tag name for a key.\n /// &lt;/summary&gt;\n protected virtual string KeyTagName\n {\n get\n {\n return DEFAULT_KEY_TAG;\n }\n }\n\n /// &lt;summary&gt;\n /// Gets the XML tag name for a value.\n /// &lt;/summary&gt;\n protected virtual string ValueTagName\n {\n get\n {\n return DEFAULT_VALUE_TAG;\n }\n }\n\n #endregion\n\n #region Public Methods\n\n /// &lt;summary&gt;\n /// Gets the XML schema for the XML serialization.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;An XML schema for the serialized object.&lt;/returns&gt;\n public XmlSchema GetSchema()\n {\n return null;\n }\n\n /// &lt;summary&gt;\n /// Deserializes the object from XML.\n /// &lt;/summary&gt;\n /// &lt;param name=\"reader\"&gt;The XML representation of the object.&lt;/param&gt;\n public void ReadXml(XmlReader reader)\n {\n XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));\n XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));\n\n bool wasEmpty = reader.IsEmptyElement;\n\n reader.Read();\n\n if (wasEmpty)\n {\n return;\n }\n\n while (reader.NodeType != XmlNodeType.EndElement)\n {\n reader.ReadStartElement(ItemTagName);\n\n reader.ReadStartElement(KeyTagName);\n TKey key = (TKey)keySerializer.Deserialize(reader);\n reader.ReadEndElement();\n\n reader.ReadStartElement(ValueTagName);\n TValue value = (TValue)valueSerializer.Deserialize(reader);\n reader.ReadEndElement();\n\n this.Add(key, value);\n\n reader.ReadEndElement();\n reader.MoveToContent();\n }\n\n reader.ReadEndElement();\n }\n\n /// &lt;summary&gt;\n /// Serializes this instance to XML.\n /// &lt;/summary&gt;\n /// &lt;param name=\"writer\"&gt;The writer to serialize to.&lt;/param&gt;\n public void WriteXml(XmlWriter writer)\n {\n XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));\n XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));\n\n foreach (TKey key in this.Keys)\n {\n writer.WriteStartElement(ItemTagName);\n\n writer.WriteStartElement(KeyTagName);\n keySerializer.Serialize(writer, key);\n writer.WriteEndElement();\n\n writer.WriteStartElement(ValueTagName);\n TValue value = this[key];\n valueSerializer.Serialize(writer, value);\n writer.WriteEndElement();\n\n writer.WriteEndElement();\n }\n }\n\n #endregion\n}\n</code></pre>\n" }, { "answer_id": 83501, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>A KeyedCollection is a type of dictionary that can be directly serialized to xml without any nonsense. The only issue is that you have to access values by: coll[\"key\"].Value;</p>\n" }, { "answer_id": 459992, "author": "user56931", "author_id": 56931, "author_profile": "https://Stackoverflow.com/users/56931", "pm_score": 4, "selected": false, "text": "<p>You will find the reason why KeyValuePairs cannot be serialised at this <a href=\"http://blogs.msdn.com/seshadripv/archive/2005/11/02/488273.aspx\" rel=\"nofollow noreferrer\">MSDN Blog Post</a></p>\n\n<p>The Struct answer is the simplest solution, however not the only solution. A \"better\" solution is to write a Custom KeyValurPair class which is Serializable.</p>\n" }, { "answer_id": 4598558, "author": "Peter Oehlert", "author_id": 44656, "author_profile": "https://Stackoverflow.com/users/44656", "pm_score": 2, "selected": false, "text": "<p>In the 4.0 Framework, there is also the addition of the Tuple family of classes that are serializable and equatable. You can use <code>Tuple.Create(a, b)</code> or <code>new Tuple&lt;T1, T2&gt;(a, b)</code>.</p>\n" }, { "answer_id": 8008789, "author": "Saraf Talukder", "author_id": 690310, "author_profile": "https://Stackoverflow.com/users/690310", "pm_score": -1, "selected": false, "text": "<p>You can use <code>Tuple&lt;string,object&gt;</code></p>\n\n<p>see this for more details on <code>Tuple</code> usage : <a href=\"http://www.abhisheksur.com/2010/11/working-with-tuple-in-c-40.html\" rel=\"nofollow\">Working with Tuple in C# 4.0</a></p>\n" }, { "answer_id": 21933365, "author": "GregoryBrad", "author_id": 1017874, "author_profile": "https://Stackoverflow.com/users/1017874", "pm_score": 3, "selected": false, "text": "<pre><code> [Serializable]\n public class SerializableKeyValuePair&lt;TKey, TValue&gt;\n {\n\n public SerializableKeyValuePair()\n {\n }\n\n public SerializableKeyValuePair(TKey key, TValue value)\n {\n Key = key;\n Value = value;\n }\n\n public TKey Key { get; set; }\n public TValue Value { get; set; }\n\n }\n</code></pre>\n" }, { "answer_id": 37876965, "author": "Akodo_Shado", "author_id": 2961273, "author_profile": "https://Stackoverflow.com/users/2961273", "pm_score": 0, "selected": false, "text": "<p><strong>XmlSerializer doesn't work with Dictionaries. Oh, and it has problems with KeyValuePairs too</strong></p>\n\n<p><a href=\"http://www.codeproject.com/Tips/314447/XmlSerializer-doesnt-work-with-Dictionaries-Oh-and\" rel=\"nofollow\">http://www.codeproject.com/Tips/314447/XmlSerializer-doesnt-work-with-Dictionaries-Oh-and</a></p>\n" }, { "answer_id": 49979671, "author": "Hasse", "author_id": 4350601, "author_profile": "https://Stackoverflow.com/users/4350601", "pm_score": 0, "selected": false, "text": "<p>Use the DataContractSerializer since it can handle the Key Value Pair.</p>\n\n<pre><code> public static string GetXMLStringFromDataContract(object contractEntity)\n {\n using (System.IO.MemoryStream writer = new System.IO.MemoryStream())\n {\n var dataContractSerializer = new DataContractSerializer(contractEntity.GetType());\n dataContractSerializer.WriteObject(writer, contractEntity);\n writer.Position = 0;\n var streamReader = new System.IO.StreamReader(writer);\n return streamReader.ReadToEnd();\n }\n }\n</code></pre>\n" }, { "answer_id": 56067993, "author": "Teodor Tite", "author_id": 4469405, "author_profile": "https://Stackoverflow.com/users/4469405", "pm_score": 0, "selected": false, "text": "<p><code>DataTable</code> is my favorite collection for (solely) wrapping data to be serialized to JSON, since it's easy to expand without the need for an extra <code>struct</code> &amp; acts like a serializable replacement for <code>Tuple&lt;&gt;[]</code></p>\n\n<p>Maybe not the cleanest way, but I prefer to include &amp; use it directly in the classes (which shall be serialized), instead of declaring a new <code>struct</code></p>\n\n<pre><code>class AnyClassToBeSerialized\n{\n public DataTable KeyValuePairs { get; }\n\n public AnyClassToBeSerialized\n {\n KeyValuePairs = new DataTable();\n KeyValuePairs.Columns.Add(\"Key\", typeof(string));\n KeyValuePairs.Columns.Add(\"Value\", typeof(string));\n }\n\n public void AddEntry(string key, string value)\n {\n DataRow row = KeyValuePairs.NewRow();\n row[\"Key\"] = key; // \"Key\" &amp; \"Value\" used only for example\n row[\"Value\"] = value;\n KeyValuePairs.Rows.Add(row);\n }\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I'm looking for a key/value pair object that I can include in a web service. I tried using .NET's [`System.Collections.Generic.KeyValuePair<>`](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this. Is there any other generic class that can be used for this situation? I'd use .NET's [`System.Web.UI.Pair`](http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.
Just define a struct/class. ``` [Serializable] public struct KeyValuePair<K,V> { public K Key {get;set;} public V Value {get;set;} } ```
83,242
<p>I have a RHEL 5 system with a fresh new hard drive I just dedicated to the MySQL server. To get things started, I used "mysqldump --host otherhost -A | mysql", even though I noticed the manpage never explicitly recommends trying this (mysqldump into a file is a no-go. We're talking 500G of database). </p> <p>This process fails at random intervals, complaining that too many files are open (at which point mysqld gets the relevant signal, and dies and respawns). </p> <p>I tried upping it at sysctl and ulimit, but the problem persists. What do I do about it? </p>
[ { "answer_id": 83381, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 4, "selected": true, "text": "<p>mysqldump by default performs a per-table lock of all involved tables. If you have many tables that can exceed the amount of file descriptors of the mysql server process.\nTry --skip-lock-tables or if locking is imperative --lock-all-tables.<br />\n<a href=\"http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html</a><blockquote><pre>--lock-all-tables, -x</p>\n\n<p>Lock all tables across all databases. This is achieved by acquiring a global read lock for the duration of the whole dump. This option automatically turns off --single-transaction and --lock-tables.</pre></blockquote></p>\n" }, { "answer_id": 83385, "author": "lbz", "author_id": 11530, "author_profile": "https://Stackoverflow.com/users/11530", "pm_score": 2, "selected": false, "text": "<p>mysqldump has been reported to yeld that error for larger databases (<a href=\"http://bugs.mysql.com/bug.php?id=26026\" rel=\"nofollow noreferrer\">1</a>, <a href=\"http://bugs.mysql.com/bug.php?id=26114\" rel=\"nofollow noreferrer\">2</a>, <a href=\"http://bugs.mysql.com/bug.php?id=27763\" rel=\"nofollow noreferrer\">3</a>). Explanation and workaround from <a href=\"http://bugs.mysql.com/bug.php?id=26026\" rel=\"nofollow noreferrer\">MySQL Bugs</a>:</p>\n<blockquote>\n<p>[3 Feb 2007 22:00] Sergei Golubchik\nThis is not really a bug.</p>\n<p>mysqldump by default has --lock-tables enabled, which means it tries to lock all tables to\nbe dumped before starting the dump. And doing LOCK TABLES t1, t2, ... for really big\nnumber of tables will inevitably exhaust all available file descriptors, as LOCK needs all\ntables to be opened.</p>\n<p>Workarounds: --skip-lock-tables will disable such a locking completely. Alternatively,\n--lock-all-tables will make mysqldump to use FLUSH TABLES WITH READ LOCK which locks all\ntables in all databases (without opening them). In this case mysqldump will automatically\ndisable --lock-tables because it makes no sense when --lock-all-tables is used.</p>\n</blockquote>\n<p><em>Edit</em>: Please check Dave's workaround for InnoDB in the comment below.</p>\n" }, { "answer_id": 87661, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If your database is that large you've got a few issues. </p>\n\n<ol>\n<li><p>You have to lock the tables to dump the data.</p></li>\n<li><p>mysqldump will take a very very long time and your tables will need to locked during this time.</p></li>\n<li><p>importing the data on the new server will also take a long time. </p></li>\n</ol>\n\n<p>Since your database is going to be essentially unusable while #1 and #2 are happening I would actually recommend stopping the database and using rsync to copy the files to the other server. It's faster than using mysqldump and much faster than importing because you don't have the added IO and CPU of generating indexes. </p>\n\n<p>In production environments on Linux many people put Mysql data on an LVM partition. Then they stop the database, do an LVM snapshot, start the database, and copy off the state of the stopped database at their leisure.</p>\n" }, { "answer_id": 57127322, "author": "Mohd Abdul Mujib", "author_id": 807104, "author_profile": "https://Stackoverflow.com/users/807104", "pm_score": 0, "selected": false, "text": "<p>I just restarted the \"MySql\" Server and then I could use the <code>mysqldump</code> command flawlessly.</p>\n\n<p>Thought this might be helpful tip here.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15910/" ]
I have a RHEL 5 system with a fresh new hard drive I just dedicated to the MySQL server. To get things started, I used "mysqldump --host otherhost -A | mysql", even though I noticed the manpage never explicitly recommends trying this (mysqldump into a file is a no-go. We're talking 500G of database). This process fails at random intervals, complaining that too many files are open (at which point mysqld gets the relevant signal, and dies and respawns). I tried upping it at sysctl and ulimit, but the problem persists. What do I do about it?
mysqldump by default performs a per-table lock of all involved tables. If you have many tables that can exceed the amount of file descriptors of the mysql server process. Try --skip-lock-tables or if locking is imperative --lock-all-tables. <http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html> > > ``` > --lock-all-tables, -x > ``` > Lock all tables across all databases. This is achieved by acquiring a global read lock for the duration of the whole dump. This option automatically turns off --single-transaction and --lock-tables.
83,260
<p>Say I've got this array: MyArray(0)="aaa" MyArray(1)="bbb" MyArray(2)="aaa"</p> <p>Is there a .net function which can give me the unique values? I would like something like this as an output of the function: OutputArray(0)="aaa" OutputArray(1)="bbb"</p>
[ { "answer_id": 83280, "author": "Stormenet", "author_id": 2090, "author_profile": "https://Stackoverflow.com/users/2090", "pm_score": 2, "selected": false, "text": "<p>You could use a dictionary to add them with a key, and when you add them check if the key already exists.</p>\n\n<pre><code>string[] myarray = new string[] { \"aaa\", \"bbb\", \"aaa\" };\n Dictionary mydict = new Dictionary();\n foreach (string s in myarray) {\n if (!mydict.ContainsKey(s)) mydict.Add(s, s);\n }</code></pre>\n" }, { "answer_id": 83285, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>Use the HashSet class included in .NET 3.5.</p>\n" }, { "answer_id": 83315, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p>A solution could be to use LINQ as in the following example:</p>\n\n<pre><code>int[] test = { 1, 2, 1, 3, 3, 4, 5 };\nvar res = (from t in test select t).Distinct&lt;int&gt;();\nforeach (var i in res)\n{\n Console.WriteLine(i);\n}\n</code></pre>\n\n<p>That would print the expected:</p>\n\n<pre><code>1\n2\n3\n4\n5\n</code></pre>\n" }, { "answer_id": 83371, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<p>Assuming you have .Net 3.5/LINQ:</p>\n\n<pre><code>string[] OutputArray = MyArray.Distinct().ToArray();\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15928/" ]
Say I've got this array: MyArray(0)="aaa" MyArray(1)="bbb" MyArray(2)="aaa" Is there a .net function which can give me the unique values? I would like something like this as an output of the function: OutputArray(0)="aaa" OutputArray(1)="bbb"
Assuming you have .Net 3.5/LINQ: ``` string[] OutputArray = MyArray.Distinct().ToArray(); ```
83,279
<p>I'm developing a 3-column website using a layout like this:</p> <pre><code> &lt;div id='left' style='left: 0; width: 150px; '&gt; ... &lt;/div&gt; &lt;div id='middle' style='left: 150px; right: 200px' &gt; ... &lt;/div&gt; &lt;div id='right' style='right: 0; width: 200px; '&gt; ... &lt;/div&gt; </code></pre> <p>But, considering the default CSS 'position' property of <code>&lt;DIV&gt;'s</code> is 'static', my <code>&lt;DIV&gt;'s</code> were shown one below the other, as expected.</p> <p>So I set the CSS property 'position' to 'relative', and changed the 'top' property of the 'middle' and 'right' <code>&lt;DIV&gt;'s</code> to -(minus) the height of the preceding <code>&lt;DIV&gt;</code>. It worked fine, but this approach brought me two problems:</p> <p>1) Even though Internet Explorer 7 shows three columns properly, it still keeps the vertical scrollbar as if the <code>&lt;DIV&gt;'s</code> were positioned one below the other, and there is a lot of white space after the content is over. I would'n like to have that.</p> <p>2) The height of these elements is variable, so I don't really know which value to set for each <code>&lt;DIV&gt;</code>'s 'top' property; and I wouldn't like to hardcode it.</p> <p>So my question is, what would be the best (simple + elegant) way to implement this layout? I would like to avoid absolute positioning , and I also to keep my design tableless.</p>
[ { "answer_id": 83294, "author": "Joshua", "author_id": 11981, "author_profile": "https://Stackoverflow.com/users/11981", "pm_score": 0, "selected": false, "text": "<p>Try floating the div's to the left, that will keep them all on the same line - assuming there is enough spacing.</p>\n" }, { "answer_id": 83305, "author": "Anthony Williams", "author_id": 5597, "author_profile": "https://Stackoverflow.com/users/5597", "pm_score": -1, "selected": false, "text": "<p>Firstly, relative positioning does what you've described: it reserves space in the original location but displays the DIV offset by some amount.</p>\n\n<p>If you float the DIVs then they will stack left-to-right, but this can cause problems.</p>\n\n<p>A three-column layout using CSS is quite hard. Have a look at [<a href=\"http://www.glish.com/css/7.asp]\" rel=\"nofollow noreferrer\">http://www.glish.com/css/7.asp]</a></p>\n" }, { "answer_id": 83322, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 6, "selected": true, "text": "<p>If you haven't already checked out <a href=\"http://www.alistapart.com/\" rel=\"noreferrer\">A List Apart</a> you should, as it contains some excellent tutorials and guidelines for website design.</p>\n\n<p><a href=\"http://alistapart.com/articles/holygrail\" rel=\"noreferrer\">This article</a> in particular should help you out.</p>\n" }, { "answer_id": 90790, "author": "Peter Kelley", "author_id": 14893, "author_profile": "https://Stackoverflow.com/users/14893", "pm_score": 1, "selected": false, "text": "<p>By far the easiest way that I have found to do 3 columns (or any other number of columns split over the available space in weird ways) is <a href=\"http://developer.yahoo.com/yui/grids/\" rel=\"nofollow noreferrer\">YUI Grids</a>. There is a <a href=\"http://developer.yahoo.com/yui/grids/builder/\" rel=\"nofollow noreferrer\">YUI Grids Builder</a> to give you the basic layout. The following will give you a 750px wide basic 3 column layout (split 1/3 1/3 1/3) with a 160px left sidebar. Changing it to to other widths, sidebar configs and column splits is really easy.</p>\n\n<pre><code>1 &lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \n2 \"http://www.w3.org/TR/html4/strict.dtd\"&gt; \n3 &lt;html&gt; \n4 &lt;head&gt; \n5 &lt;title&gt;YUI Base Page&lt;/title&gt; \n6 &lt;link rel=\"stylesheet\" href=\"http://yui.yahooapis.com/2.5.1/build/reset-fonts-grids/reset-fonts-grids.css\" type=\"text/css\"&gt; \n7 &lt;/head&gt; \n8 &lt;body&gt; \n9 &lt;div id=\"doc\" class=\"yui-t1\"&gt; \n10 &lt;div id=\"hd\"&gt;&lt;h1&gt;YUI: CSS Grid Builder&lt;/h1&gt;&lt;/div&gt; \n11 &lt;div id=\"bd\"&gt; \n12 &lt;div id=\"yui-main\"&gt; \n13 &lt;div class=\"yui-b\"&gt; &lt;div class=\"yui-gb\"&gt; \n14 &lt;div class=\"yui-u first\"&gt; \n15 &lt;!-- YOUR DATA GOES HERE --&gt; \n16 &lt;/div&gt; \n17 &lt;div class=\"yui-u\"&gt; \n18 &lt;!-- YOUR DATA GOES HERE --&gt; \n19 &lt;/div&gt; \n20 &lt;div class=\"yui-u\"&gt; \n21 &lt;!-- YOUR DATA GOES HERE --&gt; \n22 &lt;/div&gt; \n23 &lt;/div&gt; \n24 &lt;/div&gt; \n25 &lt;/div&gt; \n26 &lt;div class=\"yui-b\"&gt;&lt;!-- YOUR NAVIGATION GOES HERE --&gt;&lt;/div&gt; \n27 \n28 &lt;/div&gt; \n29 &lt;div id=\"ft\"&gt;Footer is here.&lt;/div&gt; \n30 &lt;/div&gt; \n31 &lt;/body&gt; \n32 &lt;/html&gt; \n</code></pre>\n" }, { "answer_id": 92266, "author": "Baer", "author_id": 6957, "author_profile": "https://Stackoverflow.com/users/6957", "pm_score": 1, "selected": false, "text": "<p>There are a number of examples and libraries out there you can search on - a couple already listed (A List Apart is a must read).</p>\n\n<p>I've used the <a href=\"http://developer.yahoo.com/yui/\" rel=\"nofollow noreferrer\">Yahoo User Interface Library (YUI)</a> on my last couple of sites and really like it. Yahoo completely supports it and it's quick to understand and use. Here is there <a href=\"http://developer.yahoo.com/yui/grids/\" rel=\"nofollow noreferrer\">CSS for Grids</a>, which allows you to format your page into as many columns and sections as you want.</p>\n\n<p>YUI is nice because you don't have to reinvent the wheel for the foundation of your site, and they do all the work of making sure their foundations work across all browsers. And best of all, it's free.</p>\n" }, { "answer_id": 100878, "author": "Mats Wiklander", "author_id": 5140, "author_profile": "https://Stackoverflow.com/users/5140", "pm_score": 2, "selected": false, "text": "<p>Give <a href=\"http://blueprintcss.org/\" rel=\"nofollow noreferrer\">BluePrint CSS</a> a try. It is really simple to get started with, yet powerful enough for most applications.</p>\n\n<p>Easy to understand tutorials and examples. Has a typography library that produces decent results straight out of the box.</p>\n" }, { "answer_id": 100939, "author": "sdfx", "author_id": 3445, "author_profile": "https://Stackoverflow.com/users/3445", "pm_score": 1, "selected": false, "text": "<p>I like <a href=\"http://960.gs/\" rel=\"nofollow noreferrer\">960 Grid System</a>. It's a lightweight, easy to use css which devides the screen into 12 (or 16) columns. You can use it for a 3 column design and align the rest of your content accordingly.</p>\n" }, { "answer_id": 584916, "author": "unigogo", "author_id": 61145, "author_profile": "https://Stackoverflow.com/users/61145", "pm_score": 0, "selected": false, "text": "<p>For fixed coloumn, just set height:xxxpx will make them equal. </p>\n\n<p>Use this <a href=\"http://www.pagecolumn.com/3_column_div_generator.htm\" rel=\"nofollow noreferrer\">3 column layout generator</a> to try.</p>\n" }, { "answer_id": 4986784, "author": "Nqko", "author_id": 615432, "author_profile": "https://Stackoverflow.com/users/615432", "pm_score": 0, "selected": false, "text": "<p>This code work on my computer with IE 8, Chrome, Firefox. </p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC\"-//W3C//DTD HTML 4.01//EN\"&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt; Test &lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div id=\"grad2\" style=\"width:15%; height:100%; position:fixed; top:0px; left:0px; background-color:rgb(147,81,73);\"&gt;\n &lt;a href=\"http://abv.bg\"&gt; Column1 &lt;/a&gt; &lt;/div&gt;\n &lt;div id=\"grad4\" style=\"width:70%; height:100%; position:fixed; top:0px; left:15%; background-color:rgb(0,0,0);\"&gt;\n &lt;font color=\"#FFFFFF\"&gt;Column 2 &lt;/font&gt; &lt;/div&gt;\n &lt;div id=\"grad3\" style=\"width:100%; height:100%; position:fixed; top:0px; left:85%; background-color:rgb(60,255,4);\"&gt;\n &lt;a href=\"http://abv.bg\"&gt; Column 3 &lt;/a&gt; &lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15931/" ]
I'm developing a 3-column website using a layout like this: ``` <div id='left' style='left: 0; width: 150px; '> ... </div> <div id='middle' style='left: 150px; right: 200px' > ... </div> <div id='right' style='right: 0; width: 200px; '> ... </div> ``` But, considering the default CSS 'position' property of `<DIV>'s` is 'static', my `<DIV>'s` were shown one below the other, as expected. So I set the CSS property 'position' to 'relative', and changed the 'top' property of the 'middle' and 'right' `<DIV>'s` to -(minus) the height of the preceding `<DIV>`. It worked fine, but this approach brought me two problems: 1) Even though Internet Explorer 7 shows three columns properly, it still keeps the vertical scrollbar as if the `<DIV>'s` were positioned one below the other, and there is a lot of white space after the content is over. I would'n like to have that. 2) The height of these elements is variable, so I don't really know which value to set for each `<DIV>`'s 'top' property; and I wouldn't like to hardcode it. So my question is, what would be the best (simple + elegant) way to implement this layout? I would like to avoid absolute positioning , and I also to keep my design tableless.
If you haven't already checked out [A List Apart](http://www.alistapart.com/) you should, as it contains some excellent tutorials and guidelines for website design. [This article](http://alistapart.com/articles/holygrail) in particular should help you out.
83,319
<p>I'm trying to figure out why the control does not honor ZIndex.</p> <p>Example 1 - which works fine</p> <pre><code> &lt;Canvas&gt; &lt;Rectangle Canvas.ZIndex="1" Height="400" Width="600" Fill="Yellow"/&gt; &lt;Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/&gt; &lt;/Canvas&gt; </code></pre> <p>Example 2 - which does not work</p> <pre><code> &lt;Canvas&gt; &lt;WebBrowser Canvas.ZIndex="1" Height="400" Width="600" Source="http://www.stackoverflow.com"/&gt; &lt;Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/&gt; &lt;/Canvas&gt; </code></pre> <p>Thanks, -- Ed</p>
[ { "answer_id": 83338, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 5, "selected": true, "text": "<p>Unfortunately this is because the WebBrowser control is a wrapper around the Internet Explorer COM control. This means that it gets its own HWND and does not allow WPF to draw anything over it. It has the same restrictions as hosting any other Win32 or WinForms control in WPF.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms742522.aspx\" rel=\"noreferrer\">MSDN</a> has more information about WPF/Win32 interop.</p>\n" }, { "answer_id": 87141, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 1, "selected": false, "text": "<p>I solved a similar issue where I was hosting a 3rd party WinForms control in my WPF application. I created a WPF control that renders the WinForms control in memory and then paints it to a bitmap. Then I use DrawImage in the OnRender method to draw the rendered content. Finally I routed mouse events from my control to the hosted control. In the case of a web browser you would also have to route keyboard events.</p>\n\n<p>My case was fairly easy - a chart with some simple mouse interaction. A web browser control may have other issues that I didn't take into consideration. Anyway I hope that helps.</p>\n" }, { "answer_id": 835949, "author": "zproxy", "author_id": 94411, "author_profile": "https://Stackoverflow.com/users/94411", "pm_score": 2, "selected": false, "text": "<p>You could SetWindowRgn to fake the overlapping area by hiding it as shown here:</p>\n\n<ul>\n<li><a href=\"http://www.flounder.com/setwindowrgn.htm\" rel=\"nofollow noreferrer\">flounder.com</a> </li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/aa930600.aspx\" rel=\"nofollow noreferrer\">msdn</a></li>\n</ul>\n" }, { "answer_id": 2572321, "author": "turtlewax", "author_id": 308417, "author_profile": "https://Stackoverflow.com/users/308417", "pm_score": 1, "selected": false, "text": "<p>I hit this issue as well. In my case I was dragging images from one panel into the WebBrowser, but of course as soon as my image moved into the browser it was hidden.</p>\n\n<p>Currently working on the following solution:</p>\n\n<ol>\n<li>When the Image drag starts, create a Bitmap of the WebBrowser using \"RenderTargetBitmap\"</li>\n<li>Add your Bitmap to the canvas, using the same width/location as the webbrowser</li>\n<li>webControl.Visibility = Visibility.Hidden.</li>\n<li>When the drag is released, remove your bitmap and set webControl.Visibility = Visible.</li>\n</ol>\n\n<p>This solution is very specific to my situation, but maybe it will give you some ideas.</p>\n" }, { "answer_id": 4205293, "author": "Armentage", "author_id": 78576, "author_profile": "https://Stackoverflow.com/users/78576", "pm_score": 3, "selected": false, "text": "<p>You are running into a common WPF pitfall, most commonly called the \"The Airspace Problem\". A possible solution is to NOT use the WebBrowser control, and instead go for something a little crazier - namely an embedded WebKit browser rendering directly to WPF. There are two packages that do this; Awesomonium (commercial) and Berkelium (open-source). There's a .NET wrapper for both of these.</p>\n" }, { "answer_id": 19936409, "author": "Hannish", "author_id": 1514608, "author_profile": "https://Stackoverflow.com/users/1514608", "pm_score": 1, "selected": false, "text": "<p>I managed to solve this by using this structure, check out the properties configuration in each element:</p>\n\n<pre><code>&lt;Canvas ClipToBounds=\"False\"&gt;\n &lt;Popup AllowsTransparency=\"True\" ClipToBounds=\"False\" IsOpen=\"True\"&gt;\n &lt;Expander&gt;\n &lt;Grid x:Name=\"YourContent\"/&gt;\n &lt;/Expander&gt;\n &lt;Popup&gt;\n&lt;/Canvas&gt;\n</code></pre>\n\n<p>You just have to manage the Expander to show or hide your content, I'm using it for a menu bar, I think that the expander is optional depending on the case.</p>\n\n<p>Check out this picture with the result, you can even show your controls on top of the WebBrowser and even outside the main window:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZO53h.png\" alt=\"enter image description here\"></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15921/" ]
I'm trying to figure out why the control does not honor ZIndex. Example 1 - which works fine ``` <Canvas> <Rectangle Canvas.ZIndex="1" Height="400" Width="600" Fill="Yellow"/> <Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/> </Canvas> ``` Example 2 - which does not work ``` <Canvas> <WebBrowser Canvas.ZIndex="1" Height="400" Width="600" Source="http://www.stackoverflow.com"/> <Rectangle Canvas.ZIndex="2" Height="100" Width="100" Fill="Red"/> </Canvas> ``` Thanks, -- Ed
Unfortunately this is because the WebBrowser control is a wrapper around the Internet Explorer COM control. This means that it gets its own HWND and does not allow WPF to draw anything over it. It has the same restrictions as hosting any other Win32 or WinForms control in WPF. [MSDN](http://msdn.microsoft.com/en-us/library/ms742522.aspx) has more information about WPF/Win32 interop.
83,329
<p>I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.</p> <p>Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?</p>
[ { "answer_id": 83344, "author": "Mark Janssen", "author_id": 15828, "author_profile": "https://Stackoverflow.com/users/15828", "pm_score": 5, "selected": false, "text": "<p>You could use 'vi' and then the following command:</p>\n\n<pre><code>:16224,16482w!/tmp/some-file\n</code></pre>\n\n<p>Alternatively: </p>\n\n<pre><code>cat file | head -n 16482 | tail -n 258\n</code></pre>\n\n<p>EDIT:- Just to add explanation, you use <strong>head -n 16482</strong> to display first 16482 lines then use <strong>tail -n 258</strong> to get last 258 lines out of the first output. </p>\n" }, { "answer_id": 83347, "author": "boxxar", "author_id": 15732, "author_profile": "https://Stackoverflow.com/users/15732", "pm_score": 11, "selected": true, "text": "<pre><code>sed -n '16224,16482p;16483q' filename &gt; newfile\n</code></pre>\n\n<p>From the <a href=\"https://www.gnu.org/software/sed/manual/sed.html#Common-Commands\" rel=\"noreferrer\">sed manual</a>:</p>\n\n<blockquote>\n <p><strong>p</strong> - \n Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.</p>\n \n <p><strong>n</strong> -\n If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If\n there is no more input then sed exits without processing any more\n commands.</p>\n \n <p><strong>q</strong> -\n Exit <code>sed</code> without processing any more commands or input.\n Note that the current pattern space is printed if auto-print is not disabled with the -n option.</p>\n</blockquote>\n\n<p><a href=\"https://www.gnu.org/software/sed/manual/sed.html#Addresses\" rel=\"noreferrer\">and</a></p>\n\n<blockquote>\n <p>Addresses in a sed script can be in any of the following forms:</p>\n \n <p><strong>number</strong>\n Specifying a line number will match only that line in the input.</p>\n \n <p>An address range can be specified by specifying two addresses\n separated by a comma (,). An address range matches lines starting from\n where the first address matches, and continues until the second\n address matches (inclusively).</p>\n</blockquote>\n" }, { "answer_id": 83348, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 3, "selected": false, "text": "<pre><code> # print section of file based on line numbers\n sed -n '16224 ,16482p' # method 1\n sed '16224,16482!d' # method 2\n</code></pre>\n" }, { "answer_id": 83359, "author": "mmaibaum", "author_id": 12213, "author_profile": "https://Stackoverflow.com/users/12213", "pm_score": 4, "selected": false, "text": "<pre><code>perl -ne 'print if 16224..16482' file.txt &gt; new_file.txt\n</code></pre>\n" }, { "answer_id": 83367, "author": "jan.vdbergh", "author_id": 9540, "author_profile": "https://Stackoverflow.com/users/9540", "pm_score": 2, "selected": false, "text": "<p>Quick and dirty:</p>\n\n<pre><code>head -16428 &lt; file.in | tail -259 &gt; file.out\n</code></pre>\n\n<p>Probably not the best way to do it but it should work.</p>\n\n<p>BTW: 259 = 16482-16224+1.</p>\n" }, { "answer_id": 83374, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 3, "selected": false, "text": "<p><code>sed -n '16224,16482p' &lt; dump.sql</code></p>\n" }, { "answer_id": 83383, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 7, "selected": false, "text": "<p>Quite simple using head/tail:</p>\n<pre><code>head -16482 in.sql | tail -258 &gt; out.sql\n</code></pre>\n<p>using sed:</p>\n<pre><code>sed -n '16224,16482p' in.sql &gt; out.sql\n</code></pre>\n<p>using awk:</p>\n<pre><code>awk 'NR&gt;=16224&amp;&amp;NR&lt;=16482' in.sql &gt; out.sql\n</code></pre>\n" }, { "answer_id": 83392, "author": "JXG", "author_id": 15456, "author_profile": "https://Stackoverflow.com/users/15456", "pm_score": 8, "selected": false, "text": "<pre><code>sed -n '16224,16482 p' orig-data-file &gt; new-file\n</code></pre>\n\n<p>Where 16224,16482 are the start line number and end line number, inclusive. This is 1-indexed. <code>-n</code> suppresses echoing the input as output, which you clearly don't want; the numbers indicate the range of lines to make the following command operate on; the command <code>p</code> prints out the relevant lines.</p>\n" }, { "answer_id": 83420, "author": "JP Lodine", "author_id": 8998, "author_profile": "https://Stackoverflow.com/users/8998", "pm_score": 3, "selected": false, "text": "<pre><code>cat dump.txt | head -16224 | tail -258\n</code></pre>\n\n<p>should do the trick. The downside of this approach is that you need to do the arithmetic to determine the argument for tail and to account for whether you want the 'between' to include the ending line or not.</p>\n" }, { "answer_id": 83423, "author": "sammyo", "author_id": 10826, "author_profile": "https://Stackoverflow.com/users/10826", "pm_score": 2, "selected": false, "text": "<p>I was about to post the head/tail trick, but actually I'd probably just fire up emacs. ;-)</p>\n\n<ol>\n<li><kbd>esc</kbd>-<kbd>x</kbd> goto-line <kbd>ret</kbd> 16224</li>\n<li>mark (<kbd>ctrl</kbd>-<kbd>space</kbd>)</li>\n<li><kbd>esc</kbd>-<kbd>x</kbd> goto-line <kbd>ret</kbd> 16482</li>\n<li><kbd>esc</kbd>-<kbd>w</kbd></li>\n</ol>\n\n<p>open the new output file, ctl-y\nsave</p>\n\n<p>Let's me see what's happening. </p>\n" }, { "answer_id": 14113237, "author": "Paddy3118", "author_id": 10562, "author_profile": "https://Stackoverflow.com/users/10562", "pm_score": 2, "selected": false, "text": "<p>I would use:</p>\n\n<pre><code>awk 'FNR &gt;= 16224 &amp;&amp; FNR &lt;= 16482' my_file &gt; extracted.txt\n</code></pre>\n\n<p>FNR contains the record (line) number of the line being read from the file.</p>\n" }, { "answer_id": 17870039, "author": "Robert Massaioli", "author_id": 83446, "author_profile": "https://Stackoverflow.com/users/83446", "pm_score": 2, "selected": false, "text": "<p>I wrote a Haskell program called <a href=\"http://hackage.haskell.org/package/splitter\" rel=\"nofollow\">splitter</a> that does exactly this: have a <a href=\"http://robertmassaioli.wordpress.com/2013/07/25/a-line-based-file-splitter-for-the-command-line/\" rel=\"nofollow\">read through my release blog post</a>.</p>\n\n<p>You can use the program as follows:</p>\n\n<pre><code>$ cat somefile | splitter 16224-16482\n</code></pre>\n\n<p>And that is all that there is to it. You will need Haskell to install it. Just:</p>\n\n<pre><code>$ cabal install splitter\n</code></pre>\n\n<p>And you are done. I hope that you find this program useful.</p>\n" }, { "answer_id": 21118665, "author": "fedorqui", "author_id": 1983854, "author_profile": "https://Stackoverflow.com/users/1983854", "pm_score": 5, "selected": false, "text": "<p>There is another approach with <code>awk</code>:</p>\n\n<pre><code>awk 'NR==16224, NR==16482' file\n</code></pre>\n\n<p>If the file is huge, it can be good to <code>exit</code> after reading the last desired line. This way, it won't read the following lines unnecessarily:</p>\n\n<pre><code>awk 'NR==16224, NR==16482-1; NR==16482 {print; exit}' file\n\nawk 'NR==16224, NR==16482; NR==16482 {exit}' file\n</code></pre>\n" }, { "answer_id": 21570310, "author": "Chinmoy Padhi", "author_id": 3273979, "author_profile": "https://Stackoverflow.com/users/3273979", "pm_score": 2, "selected": false, "text": "<p>Even we can do this to check at command line:</p>\n\n<pre><code>cat filename|sed 'n1,n2!d' &gt; abc.txt\n</code></pre>\n\n<p>For Example:</p>\n\n<pre><code>cat foo.pl|sed '100,200!d' &gt; abc.txt\n</code></pre>\n" }, { "answer_id": 27406810, "author": "DrNerdfighter", "author_id": 2167295, "author_profile": "https://Stackoverflow.com/users/2167295", "pm_score": 1, "selected": false, "text": "<p>I wrote a small bash script that you can run from your command line, so long as you update your PATH to include its directory (or you can place it in a directory that is already contained in the PATH).</p>\n\n<p>Usage: $ pinch filename start-line end-line</p>\n\n<pre><code>#!/bin/bash\n# Display line number ranges of a file to the terminal.\n# Usage: $ pinch filename start-line end-line\n# By Evan J. Coon\n\nFILENAME=$1\nSTART=$2\nEND=$3\n\nERROR=\"[PINCH ERROR]\"\n\n# Check that the number of arguments is 3\nif [ $# -lt 3 ]; then\n echo \"$ERROR Need three arguments: Filename Start-line End-line\"\n exit 1\nfi\n\n# Check that the file exists.\nif [ ! -f \"$FILENAME\" ]; then\n echo -e \"$ERROR File does not exist. \\n\\t$FILENAME\"\n exit 1\nfi\n\n# Check that start-line is not greater than end-line\nif [ \"$START\" -gt \"$END\" ]; then\n echo -e \"$ERROR Start line is greater than End line.\"\n exit 1\nfi\n\n# Check that start-line is positive.\nif [ \"$START\" -lt 0 ]; then\n echo -e \"$ERROR Start line is less than 0.\"\n exit 1\nfi\n\n# Check that end-line is positive.\nif [ \"$END\" -lt 0 ]; then\n echo -e \"$ERROR End line is less than 0.\"\n exit 1\nfi\n\nNUMOFLINES=$(wc -l &lt; \"$FILENAME\")\n\n# Check that end-line is not greater than the number of lines in the file.\nif [ \"$END\" -gt \"$NUMOFLINES\" ]; then\n echo -e \"$ERROR End line is greater than number of lines in file.\"\n exit 1\nfi\n\n# The distance from the end of the file to end-line\nENDDIFF=$(( NUMOFLINES - END ))\n\n# For larger files, this will run more quickly. If the distance from the\n# end of the file to the end-line is less than the distance from the\n# start of the file to the start-line, then start pinching from the\n# bottom as opposed to the top.\nif [ \"$START\" -lt \"$ENDDIFF\" ]; then\n &lt; \"$FILENAME\" head -n $END | tail -n +$START\nelse\n &lt; \"$FILENAME\" tail -n +$START | head -n $(( END-START+1 ))\nfi\n\n# Success\nexit 0\n</code></pre>\n" }, { "answer_id": 30373675, "author": "Carl Blakeley", "author_id": 4743018, "author_profile": "https://Stackoverflow.com/users/4743018", "pm_score": 2, "selected": false, "text": "<p>Using ruby:</p>\n\n<pre><code>ruby -ne 'puts \"#{$.}: #{$_}\" if $. &gt;= 32613500 &amp;&amp; $. &lt;= 32614500' &lt; GND.rdf &gt; GND.extract.rdf\n</code></pre>\n" }, { "answer_id": 31920272, "author": "potong", "author_id": 967492, "author_profile": "https://Stackoverflow.com/users/967492", "pm_score": 1, "selected": false, "text": "<p>This might work for you (GNU sed):</p>\n\n<pre><code>sed -ne '16224,16482w newfile' -e '16482q' file\n</code></pre>\n\n<p>or taking advantage of bash:</p>\n\n<pre><code>sed -n $'16224,16482w newfile\\n16482q' file\n</code></pre>\n" }, { "answer_id": 34204380, "author": "ThinkBonobo", "author_id": 2668545, "author_profile": "https://Stackoverflow.com/users/2668545", "pm_score": 0, "selected": false, "text": "<p>The -n in the accept answers work. Here's another way in case you're inclined.</p>\n\n<pre><code>cat $filename | sed \"${linenum}p;d\";\n</code></pre>\n\n<p>This does the following:</p>\n\n<ol>\n<li>pipe in the contents of a file (or feed in the text however you want).</li>\n<li>sed selects the given line, prints it</li>\n<li>d is required to delete lines, otherwise sed will assume all lines will eventually be printed. i.e., without the d, you will get all lines printed by the selected line printed twice because you have the ${linenum}p part asking for it to be printed. I'm pretty sure the -n is basically doing the same thing as the d here.</li>\n</ol>\n" }, { "answer_id": 46988259, "author": "KevinY", "author_id": 2403657, "author_profile": "https://Stackoverflow.com/users/2403657", "pm_score": 2, "selected": false, "text": "<p>I wanted to do the same thing from a script using a variable and achieved it by putting quotes around the $variable to separate the variable name from the p:</p>\n\n<pre><code>sed -n \"$first\",\"$count\"p imagelist.txt &gt;\"$imageblock\"\n</code></pre>\n\n<p>I wanted to split a list into separate folders and found the initial question and answer a useful step. (split command not an option on the old os I have to port code to).</p>\n" }, { "answer_id": 48797557, "author": "Kemin Zhou", "author_id": 2407363, "author_profile": "https://Stackoverflow.com/users/2407363", "pm_score": 1, "selected": false, "text": "<p>Since we are talking about extracting lines of text from a text file, I will give an special case where you want to extract all lines that match a certain pattern. </p>\n\n<pre><code>myfile content:\n=====================\nline1 not needed\nline2 also discarded\n[Data]\nfirst data line\nsecond data line\n=====================\nsed -n '/Data/,$p' myfile\n</code></pre>\n\n<p>Will print the [Data] line and the remaining. If you want the text from line1 to the pattern, you type: sed -n '1,/Data/p' myfile. Furthermore, if you know two pattern (better be unique in your text), both the beginning and end line of the range can be specified with matches.</p>\n\n<pre><code>sed -n '/BEGIN_MARK/,/END_MARK/p' myfile\n</code></pre>\n" }, { "answer_id": 54692028, "author": "Tilman Vogel", "author_id": 119725, "author_profile": "https://Stackoverflow.com/users/119725", "pm_score": 4, "selected": false, "text": "<p>Standing on the shoulders of boxxar, I like this:</p>\n\n<pre><code>sed -n '&lt;first line&gt;,$p;&lt;last line&gt;q' input\n</code></pre>\n\n<p>e.g.</p>\n\n<pre><code>sed -n '16224,$p;16482q' input\n</code></pre>\n\n<p>The <code>$</code> means \"last line\", so the first command makes <code>sed</code> print all lines starting with line <code>16224</code> and the second command makes <code>sed</code> quit <em>after</em> printing line <code>16428</code>. (Adding <code>1</code> for the <code>q</code>-range in boxxar's solution does not seem to be necessary.)</p>\n\n<p>I like this variant because I don't need to specify the ending line number twice. And I measured that using <code>$</code> does not have detrimental effects on performance.</p>\n" }, { "answer_id": 57914915, "author": "Benjamin W.", "author_id": 3266847, "author_profile": "https://Stackoverflow.com/users/3266847", "pm_score": 2, "selected": false, "text": "<p>Using ed:</p>\n\n<pre><code>ed -s infile &lt;&lt;&lt;'16224,16482p'\n</code></pre>\n\n<p><code>-s</code> suppresses diagnostic output; the actual commands are in a here-string. Specifically, <code>16224,16482p</code> runs the <code>p</code> (print) command on the desired line address range.</p>\n" }, { "answer_id": 63818110, "author": "Anselmo Blanco Dominguez", "author_id": 6131786, "author_profile": "https://Stackoverflow.com/users/6131786", "pm_score": 2, "selected": false, "text": "<p>Just benchmarking 3 solutions given above, that works to me:</p>\n<ul>\n<li>awk</li>\n<li>sed</li>\n<li>&quot;head+tail&quot;</li>\n</ul>\n<p>Credits on the 3 solutions goes to:</p>\n<ul>\n<li>@boxxar</li>\n<li>@avandeursen</li>\n<li>@wds</li>\n<li>@manveru</li>\n<li>@sibaz</li>\n<li>@SOFe</li>\n<li>@fedorqui 'SO stop harming'</li>\n<li>@Robin A. Meade</li>\n</ul>\n<hr />\n<p>I'm using a huge file I find in my server:</p>\n<pre><code># wc fo2debug.1.log\n 10421186 19448208 38795491134 fo2debug.1.log\n</code></pre>\n<p>38 Gb in 10.4 million lines.</p>\n<p>And yes, I have a logrotate problem. : ))</p>\n<hr />\n<h2>Make your bets!</h2>\n<hr />\n<p>Getting 256 lines from the beginning of the file.</p>\n<pre><code># time sed -n '1001,1256p;1256q' fo2debug.1.log | wc -l\n256\n\nreal 0m0,003s\nuser 0m0,000s\nsys 0m0,004s\n\n# time head -1256 fo2debug.1.log | tail -n +1001 | wc -l\n256\n\nreal 0m0,003s\nuser 0m0,006s\nsys 0m0,000s\n\n# time awk 'NR==1001, NR==1256; NR==1256 {exit}' fo2debug.1.log | wc -l\n256\n\nreal 0m0,002s\nuser 0m0,004s\nsys 0m0,000s\n</code></pre>\n<p><strong>Awk</strong> won. Technical tie in second place between sed and &quot;head+tail&quot;.</p>\n<hr />\n<p>Getting 256 lines at the end of the first third of the file.</p>\n<pre><code># time sed -n '3473001,3473256p;3473256q' fo2debug.1.log | wc -l\n256\n\nreal 0m0,265s\nuser 0m0,242s\nsys 0m0,024s\n\n# time head -3473256 fo2debug.1.log | tail -n +3473001 | wc -l\n256\n\nreal 0m0,308s\nuser 0m0,313s\nsys 0m0,145s\n\n# time awk 'NR==3473001, NR==3473256; NR==3473256 {exit}' fo2debug.1.log | wc -l\n256\n\nreal 0m0,393s\nuser 0m0,326s\nsys 0m0,068s\n</code></pre>\n<p><strong>Sed</strong> won. Followed by &quot;head+tail&quot; and, finally, awk.</p>\n<hr />\n<p>Getting 256 lines at the end of the second third of the file.</p>\n<pre><code># time sed -n '6947001,6947256p;6947256q' fo2debug.1.log | wc -l\nA256\n\nreal 0m0,525s\nuser 0m0,462s\nsys 0m0,064s\n\n# time head -6947256 fo2debug.1.log | tail -n +6947001 | wc -l\n256\n\nreal 0m0,615s\nuser 0m0,488s\nsys 0m0,423s\n\n# time awk 'NR==6947001, NR==6947256; NR==6947256 {exit}' fo2debug.1.log | wc -l\n256\n\nreal 0m0,779s\nuser 0m0,650s\nsys 0m0,130s\n</code></pre>\n<p>Same results.</p>\n<p><strong>Sed</strong> won. Followed by &quot;head+tail&quot; and, finally, awk.</p>\n<hr />\n<p>Getting 256 lines near the end of the file.</p>\n<pre><code># time sed -n '10420001,10420256p;10420256q' fo2debug.1.log | wc -l\n256\n\nreal 1m50,017s\nuser 0m12,735s\nsys 0m22,926s\n\n# time head -10420256 fo2debug.1.log | tail -n +10420001 | wc -l\n256\n\nreal 1m48,269s\nuser 0m42,404s\nsys 0m51,015s\n\n# time awk 'NR==10420001, NR==10420256; NR==10420256 {exit}' fo2debug.1.log | wc -l\n256\n\nreal 1m49,106s\nuser 0m12,322s\nsys 0m18,576s\n</code></pre>\n<p>And suddenly, a twist!</p>\n<p><strong>&quot;Head+tail&quot;</strong> won. Followed by awk and, finally, sed.</p>\n<hr />\n<p>(some hours later...)</p>\n<h2>Sorry guys!</h2>\n<p>My analysis above ends up being an example of a basic flaw in doing an analysis.</p>\n<p>The flaw is not knowing in depth the resources used for the analysis.</p>\n<p>In this case, I used a log file to analyze the performance of a search for a certain number of lines within it.</p>\n<p>Using 3 different techniques, searches were made at different points in the file, comparing the performance of the techniques at each point and checking whether the results varied depending on the point in the file where the search was made.</p>\n<p>My mistake was to assume that there was a certain homogeneity of content in the log file.</p>\n<p>The reality is that long lines appear more frequently at the end of the file.</p>\n<p>Thus, the apparent conclusion that longer searches (closer to the end of the file) are better with a given technique, may be biased. In fact, this technique may be better when dealing with longer lines. What remains to be confirmed.</p>\n" }, { "answer_id": 66395284, "author": "Kahiga", "author_id": 4463830, "author_profile": "https://Stackoverflow.com/users/4463830", "pm_score": 0, "selected": false, "text": "<p>I was looking for an answer to this but I had to end up writing my own code which worked. None of the answers above were satisfactory.\nConsider you have very large file and have certain line numbers that you want to print out but the numbers are not in order. You can do the following:</p>\n<p>My relatively large file\n<code>for letter in {a..k} ; do echo $letter; done | cat -n &gt; myfile.txt</code></p>\n<pre><code> 1 a\n 2 b\n 3 c\n 4 d\n 5 e\n 6 f\n 7 g\n 8 h\n 9 i\n10 j\n11 k\n</code></pre>\n<p>Specific line numbers I want:\n<code>shuf -i 1-11 -n 4 &gt; line_numbers_I_want.txt</code></p>\n<pre><code> 10\n 11\n 4\n 9\n</code></pre>\n<p>To print these line numbers, do the following.\n<code>awk '{system(&quot;head myfile.txt -n &quot; $0 &quot; | tail -n 1&quot;)}' line_numbers_I_want.txt</code></p>\n<p>What the above does is to head the n line then take the last line using tail</p>\n<p>If you want your line numbers in order, sort ( is -n numeric sort) first then get the lines.</p>\n<p><code>cat line_numbers_I_want.txt | sort -n | awk '{system(&quot;head myfile.txt -n &quot; $0 &quot; | tail -n 1&quot;)}'</code></p>\n<pre><code> 4 d\n 9 i\n10 j\n11 k\n</code></pre>\n" }, { "answer_id": 67063978, "author": "Tasos Papastylianou", "author_id": 4183191, "author_profile": "https://Stackoverflow.com/users/4183191", "pm_score": 4, "selected": false, "text": "<p>People trying to wrap their heads around computing an interval for the <code>head | tail</code> combo are overthinking it.</p>\n<p>Here's how you get the &quot;16224 -- 16482&quot; range without computing anything:</p>\n<pre><code>cat file | head -n +16482 | tail -n +16224\n</code></pre>\n<hr>\n<p>Explanation:</p>\n<ul>\n<li><p>The <code>+</code> instructs the <code>head</code>/<code>tail</code> command to &quot;<em>go up to</em> / <em>start from</em>&quot; (respectively) the specified line number <strong>as counted from the beginning of the file</strong>.</p>\n</li>\n<li><p>Similarly, a <code>-</code> instructs them to &quot;<em>go up to</em> / <em>start from</em>&quot; (respectively) the specified line number <strong>as counted from the end of the file</strong></p>\n</li>\n<li><p>The solution shown above simply uses <code>head</code> first, to '<strong>keep everything up to the top number</strong>', and then <code>tail</code> second, to '<strong>keep everything from the bottom number upwards</strong>', thus defining our range of interest (with no need to compute an interval).</p>\n</li>\n</ul>\n" }, { "answer_id": 71969197, "author": "user2928048", "author_id": 2928048, "author_profile": "https://Stackoverflow.com/users/2928048", "pm_score": 0, "selected": false, "text": "<p>Maybe, you would be so kind to give this humble script a chance ;-)</p>\n<pre><code>#!/usr/bin/bash\n\n# Usage:\n# body n m|-m\n\nfrom=$1\nto=$2\n\nif [ $to -gt 0 ]; then\n# count $from the begin of the file $to selected line\n awk &quot;NR &gt;= $from &amp;&amp; NR &lt;= $to {print}&quot;\nelse\n# count $from the begin of the file skipping tailing $to lines\n awk '\n BEGIN {lines=0; from='$from'; to='$to'}\n {++lines}\n NR &gt;= $from {line[lines]=$0}\n END {for (i = from; i &lt; lines + to + 1; i++) {\n print line[i]\n }\n }'\nfi\n</code></pre>\n<p>Outputs:</p>\n<pre><code>$ seq 20 | ./body.sh 5 15\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n\n$ seq 20 | ./body.sh 5 -5\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n</code></pre>\n" }, { "answer_id": 71970867, "author": "RARE Kpop Manifesto", "author_id": 14672114, "author_profile": "https://Stackoverflow.com/users/14672114", "pm_score": 1, "selected": false, "text": "<p>I've compiled some of the highest rated solutions for <code>sed</code>, <code>perl</code>, <code>head+tail</code>, plus my own code for <code>awk</code>, and focusing on performance via the pipe, while using <code>LC_ALL=C</code> to ensure all candidates at their fastest possible, allocating 2-second sleep gap in between.</p>\n<p>The gaps are somewhat noticeable :</p>\n<pre><code> abs time awk/app speed ratio\n ----------------------------------\n 0.0672 sec : 1.00x mawk-2\n 0.0839 sec : 1.25x gnu-sed\n 0.1289 sec : 1.92x perl\n 0.2151 sec : 3.20x gnu-head+tail\n</code></pre>\n<p>Haven't had chance to test <code>python</code> or <code>BSD</code> variants of those utilities.</p>\n<pre><code> (fg &amp;&amp; fg &amp;&amp; fg &amp;&amp; fg) 2&gt;/dev/null; \n echo;\n ( time ( pvE0 &lt; &quot;${m3t}&quot; \n | LC_ALL=C mawk2 '\n\n BEGIN { \n _=10420001-(\\\n __=10420256)^(FS=&quot;^$&quot;) \n } _&lt;NR { \n print\n\n if(__==NR) { exit } \n \n }' ) | pvE9) | tee &gt;(xxh128sum &gt;&amp;2) | LC_ALL=C gwc -lcm | lgp3 ; \n sleep 2;\n (fg &amp;&amp; fg &amp;&amp; fg &amp;&amp; fg) 2&gt;/dev/null\n echo; \n ( time ( pvE0 &lt; &quot;${m3t}&quot; \n | LC_ALL=C gsed -n '10420001,10420256p;10420256q' \n \n ) | pvE9 ) | tee &gt;(xxh128sum &gt;&amp;2) | LC_ALL=C gwc -lcm | lgp3 ;\n sleep 2; (fg &amp;&amp; fg &amp;&amp; fg &amp;&amp; fg) 2&gt;/dev/null\n echo\n ( time ( pvE0 &lt; &quot;${m3t}&quot; \n | LC_ALL=C perl -ne 'print if 10420001..10420256'\n \n ) | pvE9 ) | tee &gt;(xxh128sum &gt;&amp;2) | LC_ALL=C gwc -lcm | lgp3 ;\n sleep 2; (fg &amp;&amp; fg &amp;&amp; fg &amp;&amp; fg) 2&gt;/dev/null\n echo\n ( time ( pvE0 &lt; &quot;${m3t}&quot; \n | LC_ALL=C ghead -n +10420256 \n | LC_ALL=C gtail -n +10420001 \n ) | pvE9 ) | tee &gt;(xxh128sum &gt;&amp;2) | LC_ALL=C gwc -lcm | lgp3 ; \n\n\n in0: 1.51GiB 0:00:00 [2.31GiB/s] [2.31GiB/s] [============&gt; ] 81% \n out9: 42.5KiB 0:00:00 [64.9KiB/s] [64.9KiB/s] [ &lt;=&gt; ]\n( pvE 0.1 in0 &lt; &quot;${m3t}&quot; | LC_ALL=C mawk2 ; )\n \n 0.43s user 0.36s system 117% cpu 0.672 total\n 256 43487 43487\n\n54313365c2e66a48dc1dc33595716cc8 stdin\n\n out9: 42.5KiB 0:00:00 [51.7KiB/s] [51.7KiB/s] [ &lt;=&gt; ]\n in0: 1.51GiB 0:00:00 [1.84GiB/s] [1.84GiB/s] [==========&gt; ] 81% \n\n ( pvE 0.1 in0 &lt; &quot;${m3t}&quot; |LC_ALL=C gsed -n '10420001,10420256p;10420256q'; ) \n \n 0.68s user 0.34s system 121% cpu 0.839 total\n 256 43487 43487\n\n54313365c2e66a48dc1dc33595716cc8 stdin\n\n\n in0: 1.85GiB 0:00:01 [1.46GiB/s] [1.46GiB/s] [=============&gt;] 100% \n out9: 42.5KiB 0:00:01 [33.5KiB/s] [33.5KiB/s] [ &lt;=&gt; ]\n\n( pvE 0.1 in0 &lt; &quot;${m3t}&quot; | LC_ALL=C perl -ne 'print if 10420001..10420256'; )\n \n 1.10s user 0.44s system 119% cpu 1.289 total\n 256 43487 43487\n\n54313365c2e66a48dc1dc33595716cc8 stdin\n\n in0: 1.51GiB 0:00:02 [ 728MiB/s] [ 728MiB/s] [=============&gt; ] 81% \n out9: 42.5KiB 0:00:02 [19.9KiB/s] [19.9KiB/s] [ &lt;=&gt; ]\n\n ( pvE 0.1 in0 &lt; &quot;${m3t}&quot; \n | LC_ALL=C ghead -n +10420256 \n | LC_ALL=C gtail -n ; ) \n \n 1.98s user 1.40s system 157% cpu 2.151 total\n 256 43487 43487\n\n54313365c2e66a48dc1dc33595716cc8 stdin\n</code></pre>\n" }, { "answer_id": 74076800, "author": "Du-Lacoste", "author_id": 3600553, "author_profile": "https://Stackoverflow.com/users/3600553", "pm_score": 0, "selected": false, "text": "<p>You could use <code>sed</code> command in your case and is pretty fast.</p>\n<p>As mentioned lets assume the range is: between 16224 and 16482 lines</p>\n<pre><code>#get the lines from 16224 to 16482 and prints the values into filename.txt file\n sed -n '16224 ,16482p' file.txt &gt; filename.txt \n \n#Additional Info to showcase other possible scenarios:\n \n#get the 16224 th line and writes the value to filename.txt\n\n sed -n '16224p' file.txt &gt; filename.txt \n\n#get the 16224 and 16300 line values only and write to filename.txt. \n\n sed -n '16224p;16300p;' file.txt &gt; filename.txt\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15676/" ]
I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want. Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?
``` sed -n '16224,16482p;16483q' filename > newfile ``` From the [sed manual](https://www.gnu.org/software/sed/manual/sed.html#Common-Commands): > > **p** - > Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. > > > **n** - > If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If > there is no more input then sed exits without processing any more > commands. > > > **q** - > Exit `sed` without processing any more commands or input. > Note that the current pattern space is printed if auto-print is not disabled with the -n option. > > > [and](https://www.gnu.org/software/sed/manual/sed.html#Addresses) > > Addresses in a sed script can be in any of the following forms: > > > **number** > Specifying a line number will match only that line in the input. > > > An address range can be specified by specifying two addresses > separated by a comma (,). An address range matches lines starting from > where the first address matches, and continues until the second > address matches (inclusively). > > >
83,397
<p>In php I have open a .php file and want to evaluate certain lines. Specifically when the $table_id and $line variables are assigned a value.</p> <p>Within the text file I have:</p> <pre><code>... $table_id = 'crs_class'; // table name $screen = 'crs_class.detail.screen.inc'; // file identifying screen structure ... </code></pre> <p>amongst other lines. The if statement below never detects the occurance of <code>$table_id</code> or <code>$screen</code> (even without the $ prepended). I can't understand why it won't work as the strpos statement below looking for 'require' works fine.</p> <p>So, why isn't this if statement getting a hit?</p> <pre><code>while ($line=fgets($fh)) { //echo "Evaluating... $line &lt;br&gt;"; **if ((($pos = stripos($line, '$table_id')) === true) || (($pos = stripos($line, '$screen'))===true))** { // TODO: Not evaluating tableid and screen lines correctly fix. // Set $table_id and $screen variables from task scripts eval($line); } if (($pos=stripos($line, 'require')) === true) { $controller = $line; } } </code></pre>
[ { "answer_id": 83424, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 4, "selected": true, "text": "<p>use !==false instead of ===true<br />\nstripos returns the position as an integer if the needle is found. And that's never ===bool.\n<br />\nYou might also be interested in PHP's <a href=\"http://de2.php.net/tokenizer\" rel=\"noreferrer\">tokenizer module</a> or the <a href=\"http://pear.php.net/package/PHP_LexerGenerator\" rel=\"noreferrer\">lexer package</a> in the pear repository.</p>\n" }, { "answer_id": 83430, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": -1, "selected": false, "text": "<p>Why are you using the === Argument?</p>\n\n<p>If it is anywhere in the line, it will be an integer. You're comparing the type also by using ====</p>\n\n<p>From my understand you're asking it \"If the position is equal and of the same type as true\" which will never work.</p>\n" }, { "answer_id": 83435, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "<p>Variable interpolation is only performed on \"strings\", not 'strings' (note the quotes). i.e.</p>\n\n<pre><code>&lt;?php\n $foo = \"bar\";\n\n print '$foo';\n print \"$foo\";\n?&gt;\n</code></pre>\n\n<p>prints $foobar. Change your quotes, and all should be well.</p>\n" }, { "answer_id": 83472, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 2, "selected": false, "text": "<p>I think VolkerK already has the answer - stripos() does not return a boolean, it returns the position within the string, or false if it's not found - so you want to be checking that the return is not false using !== (not != as you want to check the type as well).</p>\n\n<p>Also, be very careful with that eval(), unless you know you can trust the source of the data you're reading from $fh.</p>\n\n<p>Otherwise, there could be anything else on that line that you unwittingly eval() - the line could be something like:</p>\n\n<pre>\n$table_id = 'foo'; exec('/bin/rm -rf /');\n</pre>\n" }, { "answer_id": 83648, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 2, "selected": false, "text": "<p>According to the <a href=\"http://ca.php.net/manual/en/function.strpos.php\" rel=\"nofollow noreferrer\">PHP docs</a>, strpos() and stripos() will return an integer for the position, <strong>OR</strong> a boolean FALSE.</p>\n\n<p>Since 0 (zero) is a valid, and very expect-able index, this function should be used with extreme caution.</p>\n\n<p>Most libs wrap this function in a better one (or a class) that returns -1 if the value isn't found.</p>\n\n<p>e.g. like Javascript's</p>\n\n<pre><code>String.indexOf(str)\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10583/" ]
In php I have open a .php file and want to evaluate certain lines. Specifically when the $table\_id and $line variables are assigned a value. Within the text file I have: ``` ... $table_id = 'crs_class'; // table name $screen = 'crs_class.detail.screen.inc'; // file identifying screen structure ... ``` amongst other lines. The if statement below never detects the occurance of `$table_id` or `$screen` (even without the $ prepended). I can't understand why it won't work as the strpos statement below looking for 'require' works fine. So, why isn't this if statement getting a hit? ``` while ($line=fgets($fh)) { //echo "Evaluating... $line <br>"; **if ((($pos = stripos($line, '$table_id')) === true) || (($pos = stripos($line, '$screen'))===true))** { // TODO: Not evaluating tableid and screen lines correctly fix. // Set $table_id and $screen variables from task scripts eval($line); } if (($pos=stripos($line, 'require')) === true) { $controller = $line; } } ```
use !==false instead of ===true stripos returns the position as an integer if the needle is found. And that's never ===bool. You might also be interested in PHP's [tokenizer module](http://de2.php.net/tokenizer) or the [lexer package](http://pear.php.net/package/PHP_LexerGenerator) in the pear repository.
83,410
<p>I have a large CSV file and I want to execute a stored procedure for each line.</p> <p>What is the best way to execute a stored procedure from PowerShell?</p>
[ { "answer_id": 83425, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<p>Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.</p>\n\n<p>SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.</p>\n\n<p><a href=\"http://www.databasejournal.com/features/mssql/article.php/3696731\" rel=\"nofollow noreferrer\">http://www.databasejournal.com/features/mssql/article.php/3696731</a></p>\n\n<p>There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:</p>\n\n<p><a href=\"http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx\" rel=\"nofollow noreferrer\">http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx</a></p>\n" }, { "answer_id": 83448, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "<p>Use sqlcmd instead of osql if it's a 2005 database</p>\n" }, { "answer_id": 83791, "author": "Mark Schill", "author_id": 9482, "author_profile": "https://Stackoverflow.com/users/9482", "pm_score": 7, "selected": true, "text": "<p>This answer was pulled from <a href=\"http://www.databasejournal.com/features/mssql/article.php/3683181\" rel=\"noreferrer\">http://www.databasejournal.com/features/mssql/article.php/3683181</a></p>\n\n<p>This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.</p>\n\n<pre><code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection\n$SqlConnection.ConnectionString = \"Server=HOME\\SQLEXPRESS;Database=master;Integrated Security=True\"\n$SqlCmd = New-Object System.Data.SqlClient.SqlCommand\n$SqlCmd.CommandText = \"sp_helpdb\"\n$SqlCmd.Connection = $SqlConnection\n$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter\n$SqlAdapter.SelectCommand = $SqlCmd\n$DataSet = New-Object System.Data.DataSet\n$SqlAdapter.Fill($DataSet)\n$SqlConnection.Close()\n$DataSet.Tables[0]\n</code></pre>\n" }, { "answer_id": 83834, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 3, "selected": false, "text": "<p>Here is a function I use to execute sql commands. You just have to change $sqlCommand.CommandText to the name of your sproc and $SqlCommand.CommandType to CommandType.StoredProcedure.</p>\n\n<pre><code>function execute-Sql{\n param($server, $db, $sql )\n $sqlConnection = new-object System.Data.SqlClient.SqlConnection\n $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db \n $sqlConnection.Open()\n $sqlCommand = new-object System.Data.SqlClient.SqlCommand\n $sqlCommand.CommandTimeout = 120\n $sqlCommand.Connection = $sqlConnection\n $sqlCommand.CommandText= $sql\n $text = $sql.Substring(0, 50)\n Write-Progress -Activity \"Executing SQL\" -Status \"Executing SQL =&gt; $text...\"\n Write-Host \"Executing SQL =&gt; $text...\"\n $result = $sqlCommand.ExecuteNonQuery()\n $sqlConnection.Close()\n}\n</code></pre>\n" }, { "answer_id": 280023, "author": "Mike Shepard", "author_id": 36429, "author_profile": "https://Stackoverflow.com/users/36429", "pm_score": 4, "selected": false, "text": "<p>Here is a function that I use (slightly redacted). It allows input and output parameters. I only have uniqueidentifier and varchar types implemented, but any other types are easy to add. If you use parameterized stored procedures (or just parameterized sql...this code is easily adapted to that), this will make your life a lot easier.</p>\n\n<p>To call the function, you need a connection to the SQL server (say $conn), </p>\n\n<blockquote>\n <p>$res=exec-storedprocedure -storedProcName 'stp_myProc' -parameters @{Param1=\"Hello\";Param2=50} -outparams @{ID=\"uniqueidentifier\"} $conn</p>\n \n <p><em>retrieve proc output from returned object</em></p>\n \n <p>$res.data #dataset containing the datatables returned by selects</p>\n \n <p>$res.outputparams.ID #output parameter ID (uniqueidentifier)</p>\n</blockquote>\n\n<p>The function:</p>\n\n<pre><code>function exec-storedprocedure($storedProcName, \n [hashtable] $parameters=@{},\n [hashtable] $outparams=@{},\n $conn,[switch]$help){ \n\n function put-outputparameters($cmd, $outparams){\n foreach($outp in $outparams.Keys){\n $cmd.Parameters.Add(\"@$outp\", (get-paramtype $outparams[$outp])).Direction=[System.Data.ParameterDirection]::Output\n }\n }\n function get-outputparameters($cmd,$outparams){\n foreach($p in $cmd.Parameters){\n if ($p.Direction -eq [System.Data.ParameterDirection]::Output){\n $outparams[$p.ParameterName.Replace(\"@\",\"\")]=$p.Value\n }\n }\n }\n\n function get-paramtype($typename,[switch]$help){\n switch ($typename){\n 'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}\n 'int' {[System.Data.SqlDbType]::Int}\n 'xml' {[System.Data.SqlDbType]::Xml}\n 'nvarchar' {[System.Data.SqlDbType]::NVarchar}\n default {[System.Data.SqlDbType]::Varchar}\n }\n }\n if ($help){\n $msg = @\"\n Execute a sql statement. Parameters are allowed. \n Input parameters should be a dictionary of parameter names and values.\n Output parameters should be a dictionary of parameter names and types.\n Return value will usually be a list of datarows. \n\n Usage: exec-query sql [inputparameters] [outputparameters] [conn] [-help]\n \"@\n Write-Host $msg\n return\n }\n $close=($conn.State -eq [System.Data.ConnectionState]'Closed')\n if ($close) {\n $conn.Open()\n }\n\n $cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)\n $cmd.CommandType=[System.Data.CommandType]'StoredProcedure'\n $cmd.CommandText=$storedProcName\n foreach($p in $parameters.Keys){\n $cmd.Parameters.AddWithValue(\"@$p\",[string]$parameters[$p]).Direction=\n [System.Data.ParameterDirection]::Input\n }\n\n put-outputparameters $cmd $outparams\n $ds=New-Object system.Data.DataSet\n $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)\n [Void]$da.fill($ds)\n if ($close) {\n $conn.Close()\n }\n get-outputparameters $cmd $outparams\n\n return @{data=$ds;outputparams=$outparams}\n }\n</code></pre>\n" }, { "answer_id": 32723977, "author": "Ken", "author_id": 3047366, "author_profile": "https://Stackoverflow.com/users/3047366", "pm_score": 0, "selected": false, "text": "<p>I include <code>invoke-sqlcmd2.ps1</code> and <code>write-datatable.ps1</code> from <a href=\"http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx\" rel=\"nofollow\">http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx</a>. Calls to run SQL commands take the form: <br><code>Invoke-sqlcmd2 -ServerInstance \"&lt;sql-server&gt;\" -Database &lt;DB&gt; -Query \"truncate table &lt;table&gt;\"</code> <br>An example of writing the contents of DataTable variables to a SQL table looks like: <br><code>$logs = (get-item SQLSERVER:\\sql\\&lt;server_path&gt;).ReadErrorLog()\nWrite-DataTable -ServerInstance \"&lt;sql-server&gt;\" -Database \"&lt;DB&gt;\" -TableName \"&lt;table&gt;\" -Data $logs</code><br> I find these useful when doing SQL Server database-related PowerShell scripts as the resulting scripts are clean and readable.</p>\n" }, { "answer_id": 71036679, "author": "Ash K", "author_id": 8644294, "author_profile": "https://Stackoverflow.com/users/8644294", "pm_score": 0, "selected": false, "text": "<p>Adds <code>CommandType</code> and <code>Parameters</code> to @Santiago Cepas' answer:</p>\n<pre><code>function Execute-Stored-Procedure\n{\n param($server, $db, $spname)\n $sqlConnection = new-object System.Data.SqlClient.SqlConnection\n $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db \n $sqlConnection.Open()\n $sqlCommand = new-object System.Data.SqlClient.SqlCommand\n $sqlCommand.CommandTimeout = 120\n $sqlCommand.Connection = $sqlConnection\n $sqlCommand.CommandType= [System.Data.CommandType]::StoredProcedure\n # If you have paramters, add them like this:\n # $sqlCommand.Parameters.AddWithValue(&quot;@paramName&quot;, &quot;$param&quot;) | Out-Null\n $sqlCommand.CommandText= $spname\n $text = $spname.Substring(0, 50)\n Write-Progress -Activity &quot;Executing Stored Procedure&quot; -Status &quot;Executing SQL =&gt; $text...&quot;\n Write-Host &quot;Executing Stored Procedure =&gt; $text...&quot;\n $result = $sqlCommand.ExecuteNonQuery()\n $sqlConnection.Close()\n}\n\n\n# Call like this:\nExecute-Stored-Procedure -server &quot;enter-server-name-here&quot; -db &quot;enter-db-name-here&quot; -spname &quot;enter-sp-name-here&quot;\n</code></pre>\n" }, { "answer_id": 72887312, "author": "Golden Lion", "author_id": 4001177, "author_profile": "https://Stackoverflow.com/users/4001177", "pm_score": 0, "selected": false, "text": "<p>I added timeout and show how to reader a scalar or get results using a reader</p>\n<pre><code>function exec-query( $storedProcName,$parameters=@{},$conn,$timeout=60){\n \n $cmd=new-object system.Data.SqlClient.SqlCommand\n\n $cmd.CommandType=[System.Data.CommandType]'StoredProcedure'\n $cmd.Connection=$conn\n $cmd.CommandText=$storedProcName\n $cmd.CommandTimeout=$timeout\n foreach($p in $parameters.Keys){\n [Void] $cmd.Parameters.AddWithValue(&quot;@$p&quot;,$parameters[$p])\n }\n \n #$id=$cmd.ExecuteScalar()\n $adapter=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)\n $dataset=New-Object system.Data.DataSet\n\n $adapter.fill($dataset) | Out-Null\n\n #$reader = $cmd.ExecuteReader()\n\n #$results = @()\n #while ($reader.Read())\n #{\n # write-host &quot;reached&quot; -ForegroundColor Green\n #}\n\n return $dataSet.Tables[0]\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12767/" ]
I have a large CSV file and I want to execute a stored procedure for each line. What is the best way to execute a stored procedure from PowerShell?
This answer was pulled from <http://www.databasejournal.com/features/mssql/article.php/3683181> This same example can be used for any adhoc queries. Let us execute the stored procedure “sp\_helpdb” as shown below. ``` $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = "sp_helpdb" $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) $SqlConnection.Close() $DataSet.Tables[0] ```
83,439
<p>What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?</p>
[ { "answer_id": 83468, "author": "rupello", "author_id": 635, "author_profile": "https://Stackoverflow.com/users/635", "pm_score": 5, "selected": false, "text": "<p>From <a href=\"http://www.gamedev.net/community/forums/topic.asp?topic_id=359650\" rel=\"noreferrer\">gamedev</a></p>\n\n<pre><code>string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());\n</code></pre>\n" }, { "answer_id": 83481, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 7, "selected": false, "text": "<pre><code>std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');\nstr.erase(end_pos, str.end());\n</code></pre>\n" }, { "answer_id": 83500, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": -1, "selected": false, "text": "<p>I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.</p>\n\n<p>EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.</p>\n\n<p>You should try different approaches and see what is best for you: you might not have any performance issues at all.</p>\n" }, { "answer_id": 83538, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 9, "selected": true, "text": "<p>The best thing to do is to use the algorithm <a href=\"http://en.cppreference.com/w/cpp/algorithm/remove\" rel=\"noreferrer\"><code>remove_if</code></a> and isspace:</p>\n\n<pre><code>remove_if(str.begin(), str.end(), isspace);\n</code></pre>\n\n<p>Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:</p>\n\n<pre><code>str.erase(remove_if(str.begin(), str.end(), isspace), str.end());\n</code></pre>\n\n<p>We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:</p>\n\n<pre><code>template&lt;typename T, typename P&gt;\nT remove_if(T beg, T end, P pred)\n{\n T dest = beg;\n for (T itr = beg;itr != end; ++itr)\n if (!pred(*itr))\n *(dest++) = *itr;\n return dest;\n}\n</code></pre>\n" }, { "answer_id": 83744, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 5, "selected": false, "text": "<p>Can you use Boost String Algo? <a href=\"http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573</a></p>\n\n<pre><code>erase_all(str, \" \"); \n</code></pre>\n" }, { "answer_id": 1754664, "author": "Roman", "author_id": 213596, "author_profile": "https://Stackoverflow.com/users/213596", "pm_score": 4, "selected": false, "text": "<p>For trimming, use <a href=\"http://www.boost.org/doc/html/string_algo.html\" rel=\"noreferrer\">boost string algorithms</a>:</p>\n\n<pre><code>#include &lt;boost/algorithm/string.hpp&gt;\n\nusing namespace std;\nusing namespace boost;\n\n// ...\n\nstring str1(\" hello world! \");\ntrim(str1); // str1 == \"hello world!\"\n</code></pre>\n" }, { "answer_id": 8868204, "author": "ddacot", "author_id": 1036018, "author_profile": "https://Stackoverflow.com/users/1036018", "pm_score": 4, "selected": false, "text": "<p>Hi, you can do something like that. This function deletes all spaces.</p>\n\n<pre><code>string delSpaces(string &amp;str) \n{\n str.erase(std::remove(str.begin(), str.end(), ' '), str.end());\n return str;\n}\n</code></pre>\n\n<hr>\n\n<p>I made another function, that deletes all unnecessary spaces.</p>\n\n<pre><code>string delUnnecessary(string &amp;str)\n{\n int size = str.length();\n for(int j = 0; j&lt;=size; j++)\n {\n for(int i = 0; i &lt;=j; i++)\n {\n if(str[i] == ' ' &amp;&amp; str[i+1] == ' ')\n {\n str.erase(str.begin() + i);\n }\n else if(str[0]== ' ')\n {\n str.erase(str.begin());\n }\n else if(str[i] == '\\0' &amp;&amp; str[i-1]== ' ')\n {\n str.erase(str.end() - 1);\n }\n }\n }\n return str;\n}\n</code></pre>\n" }, { "answer_id": 10355229, "author": "SudoBash", "author_id": 1361698, "author_profile": "https://Stackoverflow.com/users/1361698", "pm_score": 3, "selected": false, "text": "<pre><code>string replaceinString(std::string str, std::string tofind, std::string toreplace)\n{\n size_t position = 0;\n for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )\n {\n str.replace(position ,1, toreplace);\n }\n return(str);\n}\n</code></pre>\n\n<p>use it:</p>\n\n<pre><code>string replace = replaceinString(thisstring, \" \", \"%20\");\nstring replace2 = replaceinString(thisstring, \" \", \"-\");\nstring replace3 = replaceinString(thisstring, \" \", \"+\");\n</code></pre>\n" }, { "answer_id": 16011109, "author": "user2281802", "author_id": 2281802, "author_profile": "https://Stackoverflow.com/users/2281802", "pm_score": 4, "selected": false, "text": "<p>You can use this solution for removing a char:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nstr.erase(remove(str.begin(), str.end(), char_to_remove), str.end());\n</code></pre>\n" }, { "answer_id": 30037563, "author": "test c", "author_id": 4863555, "author_profile": "https://Stackoverflow.com/users/4863555", "pm_score": -1, "selected": false, "text": "<pre><code>string removespace(string str)\n{ \n int m = str.length();\n int i=0;\n while(i&lt;m)\n {\n while(str[i] == 32)\n str.erase(i,1);\n i++;\n } \n}\n</code></pre>\n" }, { "answer_id": 35107174, "author": "Volomike", "author_id": 105539, "author_profile": "https://Stackoverflow.com/users/105539", "pm_score": 3, "selected": false, "text": "<p>If you want to do this with an easy macro, here's one:</p>\n<pre><code>#define REMOVE_SPACES(x) x.erase(std::remove(x.begin(), x.end(), ' '), x.end())\n</code></pre>\n<p>This assumes you have done <code>#include &lt;string&gt;</code> of course.</p>\n<p>Call it like so:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string sName = &quot; Example Name &quot;;\nREMOVE_SPACES(sName);\nprintf(&quot;%s&quot;,sName.c_str()); // requires #include &lt;stdio.h&gt;\n</code></pre>\n" }, { "answer_id": 36694415, "author": "RaGa__M", "author_id": 5198101, "author_profile": "https://Stackoverflow.com/users/5198101", "pm_score": 2, "selected": false, "text": "<p>I used the below work around for long - not sure about its complexity.</p>\n\n<p><code>s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return (f==' '||s==' ');}),s.end());</code></p>\n\n<p>when you wanna remove character <code>' '</code> and some for example <code>-</code> use</p>\n\n<p><code>s.erase(std::unique(s.begin(),s.end(),[](char s,char f){return ((f==' '||s==' ')||(f=='-'||s=='-'));}),s.end());</code></p>\n\n<p>likewise just increase the <code>||</code> if number of characters you wanna remove is not 1</p>\n\n<p>but as mentioned by others the erase remove idiom also seems fine.</p>\n" }, { "answer_id": 55642878, "author": "Crisp Apples", "author_id": 9959106, "author_profile": "https://Stackoverflow.com/users/9959106", "pm_score": 2, "selected": false, "text": "<pre><code>string removeSpaces(string word) {\n string newWord;\n for (int i = 0; i &lt; word.length(); i++) {\n if (word[i] != ' ') {\n newWord += word[i];\n }\n }\n\n return newWord;\n}\n</code></pre>\n\n<p>This code basically takes a string and iterates through every character in it. It then checks whether that string is a white space, if it isn't then the character is added to a new string.</p>\n" }, { "answer_id": 59053051, "author": "Deepanshu", "author_id": 10186641, "author_profile": "https://Stackoverflow.com/users/10186641", "pm_score": 2, "selected": false, "text": "<blockquote>\n <pre class=\"lang-cpp prettyprint-override\"><code> #include &lt;algorithm&gt;\n using namespace std;\n\n int main() {\n .\n .\n s.erase( remove( s.begin(), s.end(), ' ' ), s.end() );\n .\n .\n }\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h2>Source:</h2>\n\n<p>Reference taken from <a href=\"http://www.cplusplus.com/forum/beginner/9557/\" rel=\"nofollow noreferrer\">this</a> forum.</p>\n" }, { "answer_id": 61989008, "author": "NoSenseEtAl", "author_id": 700825, "author_profile": "https://Stackoverflow.com/users/700825", "pm_score": 3, "selected": false, "text": "<p>In C++20 you can use free function std::erase</p>\n\n<pre><code>std::string str = \" Hello World !\";\nstd::erase(str, ' ');\n</code></pre>\n\n<p>Full example:</p>\n\n<pre><code>#include&lt;string&gt;\n#include&lt;iostream&gt;\n\nint main() {\n std::string str = \" Hello World !\";\n std::erase(str, ' ');\n std::cout &lt;&lt; \"|\" &lt;&lt; str &lt;&lt;\"|\";\n}\n</code></pre>\n\n<p>I print | so that it is obvious that space at the begining is also removed.</p>\n\n<p>note: this removes only the space, not every other possible character that may be considered whitespace, see <a href=\"https://en.cppreference.com/w/cpp/string/byte/isspace\" rel=\"noreferrer\">https://en.cppreference.com/w/cpp/string/byte/isspace</a></p>\n" }, { "answer_id": 62207804, "author": "AnselmRu", "author_id": 6359258, "author_profile": "https://Stackoverflow.com/users/6359258", "pm_score": 2, "selected": false, "text": "<p>Removes all <a href=\"https://en.wikipedia.org/wiki/Category:Whitespace\" rel=\"nofollow noreferrer\">whitespace characters</a> such as tabs and line breaks (C++11):</p>\n\n<pre><code>string str = \" \\n AB cd \\t efg\\v\\n\";\nstr = regex_replace(str,regex(\"\\\\s\"),\"\");\n</code></pre>\n" }, { "answer_id": 62321910, "author": "Kerim FIRAT", "author_id": 2499808, "author_profile": "https://Stackoverflow.com/users/2499808", "pm_score": -1, "selected": false, "text": "<pre><code> string str = \"2C F4 32 3C B9 DE\";\n str.erase(remove(str.begin(),str.end(),' '),str.end());\n cout &lt;&lt; str &lt;&lt; endl;\n</code></pre>\n\n<p>output: 2CF4323CB9DE</p>\n" }, { "answer_id": 64953861, "author": "Enlico", "author_id": 5825294, "author_profile": "https://Stackoverflow.com/users/5825294", "pm_score": 0, "selected": false, "text": "<p>Just for fun, as other answers are much better than this.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;boost/hana/functional/partial.hpp&gt;\n#include &lt;iostream&gt;\n#include &lt;range/v3/range/conversion.hpp&gt;\n#include &lt;range/v3/view/filter.hpp&gt;\nint main() {\n using ranges::to;\n using ranges::views::filter;\n using boost::hana::partial;\n auto const&amp; not_space = partial(std::not_equal_to&lt;&gt;{}, ' ');\n auto const&amp; to_string = to&lt;std::string&gt;;\n\n std::string input = &quot;2C F4 32 3C B9 DE&quot;;\n std::string output = input | filter(not_space) | to_string;\n assert(output == &quot;2CF4323CB9DE&quot;);\n}\n</code></pre>\n" }, { "answer_id": 65626953, "author": "D...", "author_id": 7452451, "author_profile": "https://Stackoverflow.com/users/7452451", "pm_score": 0, "selected": false, "text": "<p>I created a function, that removes the white spaces from the either ends of string. Such as\n<code>&quot; Hello World &quot;</code>, will be converted into <code>&quot;Hello world&quot;</code>.</p>\n<p>This works similar to <code>strip</code>, <code>lstrip</code> and <code>rstrip</code> functions, which are frequently used in python.</p>\n<pre><code>string strip(string str) {\n while (str[str.length() - 1] == ' ') {\n str = str.substr(0, str.length() - 1);\n }\n while (str[0] == ' ') {\n str = str.substr(1, str.length() - 1);\n }\n return str;\n}\n\nstring lstrip(string str) {\n while (str[0] == ' ') {\n str = str.substr(1, str.length() - 1);\n }\n return str;\n}\n\nstring rstrip(string str) {\n while (str[str.length() - 1] == ' ') {\n str = str.substr(0, str.length() - 1);\n }\n return str;\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15947/" ]
What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?
The best thing to do is to use the algorithm [`remove_if`](http://en.cppreference.com/w/cpp/algorithm/remove) and isspace: ``` remove_if(str.begin(), str.end(), isspace); ``` Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container: ``` str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); ``` We should also note that remove\_if will make at most one copy of the data. Here is a sample implementation: ``` template<typename T, typename P> T remove_if(T beg, T end, P pred) { T dest = beg; for (T itr = beg;itr != end; ++itr) if (!pred(*itr)) *(dest++) = *itr; return dest; } ```
83,471
<p>Working with a SqlCommand in C# I've created a query that contains a IN (list...) part in the where clause. Instead of looping through my string list generating the list I need for the query (dangerous if you think in sqlInjection). I thought that I could create a parameter like:</p> <pre><code>SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS </code></pre> <p>Then in the code I try to add a parameter like this: </p> <pre><code>DataTable dt = new DataTable(); dt.Columns.Add("word", typeof(string)); foreach (String word in listOfWords) { dt.Rows.Add(word); } comm.Parameters.Add("LISTOFWORDS", System.Data.SqlDbType.Structured).Value = dt; </code></pre> <p>But this doesn't work. </p> <p>Questions:</p> <ul> <li>Am I trying something impossible?</li> <li>Did I took the wrong approach?</li> <li>Do I have mistakes in this approach?</li> </ul> <p>Thanks for your time :)</p>
[ { "answer_id": 83525, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You want to think about where that list comes from. Generally that information is in the database somewhere. For example, instead of this:</p>\n\n<pre><code>SELECT * FROM [Table] WHERE ID IN (1,2,3)\n</code></pre>\n\n<p>You could use a subquery like this:</p>\n\n<pre><code>SELECT * FROM [Table] WHERE ID IN ( SELECT TableID FROM [OtherTable] WHERE OtherTableID= @OtherTableID )\n</code></pre>\n" }, { "answer_id": 83549, "author": "Vyrotek", "author_id": 10941, "author_profile": "https://Stackoverflow.com/users/10941", "pm_score": 0, "selected": false, "text": "<p>I would recommend setting the parameter as a comma delimited string of values and use a Split function in SQL to turn that into a single column table of values and then you can use the IN feature.</p>\n\n<p><a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648</a> - Split Functions</p>\n" }, { "answer_id": 83563, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "<p>If I understand right, you're trying to pass a list as a SQL parameter.</p>\n\n<p>Some folks have attempted this before with limited success:</p>\n\n<p><a href=\"http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm\" rel=\"nofollow noreferrer\">Passing Arrays to Stored Procedures</a></p>\n\n<p><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html\" rel=\"nofollow noreferrer\">Arrays and Lists in SQL 2005</a></p>\n\n<p><a href=\"http://sqlblogcasts.com/blogs/tonyrogerson/archive/2007/03/18/passing-an-array-of-values-to-sql-server-stored-procedure-without-parsing-string-manipulation.aspx\" rel=\"nofollow noreferrer\">Passing Array of Values to SQL Server without String Manipulation</a></p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2006/05/08/144263.aspx\" rel=\"nofollow noreferrer\">Using MS SQL 2005's XML capabilities to pass a list of values to a command</a></p>\n" }, { "answer_id": 83577, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 0, "selected": false, "text": "<p>If you want to pass the list as a string in a parameter, you could just build the query dynamically.</p>\n\n<p>DECLARE @query varchar(500)\nSET @query = 'SELECT blah blah WHERE blahblah in (' + @list + ')'\nEXECUTE(@query)</p>\n" }, { "answer_id": 83581, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 0, "selected": false, "text": "<p>I used to have the same problem, I think there is now way to do this directly over the ADO.NET API.</p>\n\n<p>You might consider inserting the words into a temptable (plus a queryid or something) and then refering to that temptable from the query. Or dynamically creating the query string and avoid sql injection by other measures (e.g. regex checks).</p>\n" }, { "answer_id": 83582, "author": "Mark Lindell", "author_id": 15978, "author_profile": "https://Stackoverflow.com/users/15978", "pm_score": 3, "selected": true, "text": "<p>What you are trying to do is possible but not using your current approach. This is a very common problem with all possible solutions prior to SQL Server 2008 having trade offs related to performance, security and memory usage. </p>\n\n<p><a href=\"http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters\" rel=\"nofollow noreferrer\">This link shows some approaches for SQL Server 2000/2005</a></p>\n\n<p><a href=\"http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters\" rel=\"nofollow noreferrer\">SQL Server 2008 supports passing a table value parameter.</a> </p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 92069, "author": "Dani", "author_id": 17330, "author_profile": "https://Stackoverflow.com/users/17330", "pm_score": 1, "selected": false, "text": "<ul>\n<li>Am I trying something impossible? </li>\n</ul>\n\n<p>No, it isn't impossible.</p>\n\n<ul>\n<li>Did I took the wrong approach? </li>\n</ul>\n\n<p>Your approach is not working (at least in .net 2)</p>\n\n<ul>\n<li>Do I have mistakes in this approach?</li>\n</ul>\n\n<p>I would try \"Joel Coehoorn\" solution (2nd answers) if it is possible.\nOtherwise, another option is to send a \"string\" parameter with all values delimited by an separator. Write a dynamic query (build it based on values from string) and execute it using \"exec\".</p>\n\n<p>Another solution will be o build the query directly from code. Somthing like this:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nfor (int i=0; i&lt; listOfWords.Count; i++)\n{\n sb.AppendFormat(\"p{0},\",i);\n comm.Parameters.AddWithValue(\"p\"+i.ToString(), listOfWords[i]);\n}\n\ncomm.CommandText = string.Format(\"\"SELECT blahblahblah WHERE blahblahblah IN ({0})\", \nsb.ToString().TrimEnd(','));\n</code></pre>\n\n<p>The command should look like: </p>\n\n<pre><code>SELECT blah WHERE blah IN (p0,p1,p2,p3...)...p0='aaa',p1='bbb'\n</code></pre>\n\n<p>In MsSql2005, \"IN\" is working only with 256 values.</p>\n" }, { "answer_id": 7614448, "author": "aarona", "author_id": 43792, "author_profile": "https://Stackoverflow.com/users/43792", "pm_score": 0, "selected": false, "text": "<p>This is an old question but I've come up with an elegant solution for this that I love to reuse and I think everyone else will find it useful.</p>\n\n<p>First of all you need to create a <code>FUNCTION</code> in SqlServer that takes a delimited input and returns a table with the items split into records.</p>\n\n<p>Here is the following code for this:</p>\n\n<pre><code>ALTER FUNCTION [dbo].[Split]\n(\n @RowData nvarchar(max),\n @SplitOn nvarchar(5) = ','\n) \nRETURNS @RtnValue table \n(\n Id int identity(1,1),\n Data nvarchar(100)\n) \nAS \nBEGIN \n Declare @Cnt int\n Set @Cnt = 1\n\n While (Charindex(@SplitOn,@RowData)&gt;0)\n Begin\n Insert Into @RtnValue (data)\n Select \n Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))\n\n Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))\n Set @Cnt = @Cnt + 1\n End\n\n Insert Into @RtnValue (data)\n Select Data = ltrim(rtrim(@RowData))\n\n Return\nEND\n</code></pre>\n\n<p>You can now do something like this:</p>\n\n<pre><code>Select Id, Data from dbo.Split('123,234,345,456',',')\n</code></pre>\n\n<p>And fear not, this can't be susceptible to Sql injection attacks.</p>\n\n<p>Next write a stored procedure that takes your comma delimited data and then you can write a sql statement that uses this Split function:</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[findDuplicates]\n @ids nvarchar(max)\nas\nbegin\n select ID\n from SomeTable with (nolock)\n where ID in (select Data from dbo.Split(@ids,','))\nend\n</code></pre>\n\n<p>Now you can write a C# wrapper around it:</p>\n\n<pre><code>public void SomeFunction(List&lt;int&gt; ids)\n{\n var idsAsDelimitedString = string.Join(\",\", ids.Select(id =&gt; id.ToString()).ToArray());\n\n // ... or however you make your connection\n var con = GetConnection();\n\n try\n {\n con.Open();\n\n var cmd = new SqlCommand(\"findDuplicates\", con);\n\n cmd.Parameters.Add(new SqlParameter(\"@ids\", idsAsDelimitedString));\n\n var reader = cmd.ExecuteReader();\n\n // .... do something here.\n\n }\n catch (Exception)\n {\n // catch an exception?\n }\n finally\n {\n con.Close();\n }\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15987/" ]
Working with a SqlCommand in C# I've created a query that contains a IN (list...) part in the where clause. Instead of looping through my string list generating the list I need for the query (dangerous if you think in sqlInjection). I thought that I could create a parameter like: ``` SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS ``` Then in the code I try to add a parameter like this: ``` DataTable dt = new DataTable(); dt.Columns.Add("word", typeof(string)); foreach (String word in listOfWords) { dt.Rows.Add(word); } comm.Parameters.Add("LISTOFWORDS", System.Data.SqlDbType.Structured).Value = dt; ``` But this doesn't work. Questions: * Am I trying something impossible? * Did I took the wrong approach? * Do I have mistakes in this approach? Thanks for your time :)
What you are trying to do is possible but not using your current approach. This is a very common problem with all possible solutions prior to SQL Server 2008 having trade offs related to performance, security and memory usage. [This link shows some approaches for SQL Server 2000/2005](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters) [SQL Server 2008 supports passing a table value parameter.](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters) I hope this helps.
83,531
<p>I'm trying to write a stored procedure to select employees who have birthdays that are upcoming. </p> <p><code>SELECT * FROM Employees WHERE Birthday &gt; @Today AND Birthday &lt; @Today + @NumDays</code></p> <p>This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' and '09-25-2008'. </p> <p>Is there a way to ignore the year portion of date fields and just compare month/days? </p> <p>This will be run every monday morning to alert managers of birthdays upcoming, so it possibly will span new years. </p> <p>Here is the working solution that I ended up creating, thanks Kogus. </p> <pre><code>SELECT * FROM Employees WHERE Cast(DATEDIFF(dd, birthdt, getDate()) / 365.25 as int) - Cast(DATEDIFF(dd, birthdt, futureDate) / 365.25 as int) &lt;&gt; 0 </code></pre>
[ { "answer_id": 83559, "author": "p4bl0", "author_id": 12043, "author_profile": "https://Stackoverflow.com/users/12043", "pm_score": 0, "selected": false, "text": "<p>You could use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html\" rel=\"nofollow noreferrer\">DATE_FORMAT</a> to extract the day and month parts of the birthday dates.</p>\n\n<p>EDIT: sorry i didn't see that he wasn't using MySQL.</p>\n" }, { "answer_id": 83571, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": -1, "selected": false, "text": "<p>Better, Add the difference in years to the BIRTHDAY date, to make everything this year, and then do your compares</p>\n\n<pre><code>SELECT * FROM Employees WHERE\n DATEADD ( year, YEAR(@Today) - YEAR(@Birthday), birthday) BETWEEN @Today AND @EndDate\n</code></pre>\n" }, { "answer_id": 83601, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<p>You could use the <code>DAYOFYEAR</code> function but be careful when you want to look for January birthdays in December. I think you'll be fine as long as the date range you're looking for doesn't span the New Year.</p>\n" }, { "answer_id": 83622, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 0, "selected": false, "text": "<p>Assuming this is T-SQL, use DATEPART to compare the month and date separately. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms174420.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms174420.aspx</a></p>\n\n<p>Alternatively, subtract January 1st of the current year from everyone's birthday, and then compare using the year 1900 (or whatever your epoch year is).</p>\n" }, { "answer_id": 83635, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Most of these solutions are close, but you have to remember a few extra scenarios. When working with birthdays and a sliding scale, you must be able to handle the transition into the next month. </p>\n\n<p>For example Stephens example works great for birthdays up until the last 4 days of the month. Then you have a logic fault as the valid dates if today was the 29th would be :29, 30, AND then 1, 2, 3 of the NEXT month, so you have to condition for that as well.</p>\n\n<p>An alternative would be to parse the date from the birthday field, and sub in the current year, then do a standard range comparison.</p>\n" }, { "answer_id": 83670, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 0, "selected": false, "text": "<p>Another thought: Add their age in whole years to their birthday (or one more if their Birthday hasn't happened yet and then compare as you do above. Use DATEPART and DATEADD to do this.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms186819.aspx</a></p>\n\n<p>The edge case of a range spanning the year would have to have special code.</p>\n\n<p>Bonus tip: consider using BETWEEN...AND instead of repeating the Birthday operand.</p>\n" }, { "answer_id": 83679, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>Sorry didn't see the requirement to neutralize the year.</p>\n\n<pre><code>select * from Employees\nwhere DATEADD (year, DatePart(year, getdate()) - DatePart(year, Birthday), Birthday)\n between convert(datetime, getdate(), 101) \n and convert(datetime, DateAdd(day, 5, getdate()), 101)\n</code></pre>\n\n<p>This should work.</p>\n" }, { "answer_id": 83688, "author": "bastos.sergio", "author_id": 12772, "author_profile": "https://Stackoverflow.com/users/12772", "pm_score": 0, "selected": false, "text": "<p>This should work...</p>\n\n<pre><code>DECLARE @endDate DATETIME\nDECLARE @today DATETIME\n\nSELECT @endDate = getDate()+6, @today = getDate()\n\nSELECT * FROM Employees \n WHERE \n (DATEPART (month, birthday) &gt;= DATEPART (month, @today)\n AND DATEPART (day, birthday) &gt;= DATEPART (day, @today))\n AND\n (DATEPART (month, birthday) &lt; DATEPART (month, @endDate)\n AND DATEPART (day, birthday) &lt; DATEPART (day, @endDate))\n</code></pre>\n" }, { "answer_id": 83783, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 6, "selected": true, "text": "<p><em>Note: I've edited this to fix what I believe was a significant bug. The currently posted version works for me.</em></p>\n\n<p>This should work after you modify the field and table names to correspond to your database.</p>\n\n<pre><code>SELECT \n BRTHDATE AS BIRTHDAY\n ,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25) AS AGE_NOW\n ,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25) AS AGE_ONE_WEEK_FROM_NOW\nFROM \n \"Database name\".dbo.EMPLOYEES EMP\nWHERE 1 = (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25))\n -\n (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25))\n</code></pre>\n\n<p>Basically, it gets the # of days from their birthday to now, and divides that by 365 (to avoid rounding issues that come up when you convert directly to years).</p>\n\n<p>Then it gets the # of days from their birthday to a week from now, and divides that by 365 to get their age a week from now.</p>\n\n<p>If their birthday is within a week, then the difference between those two values will be 1. So it returns all of those records.</p>\n" }, { "answer_id": 83822, "author": "Mostlyharmless", "author_id": 12881, "author_profile": "https://Stackoverflow.com/users/12881", "pm_score": 0, "selected": false, "text": "<p>I faced the same problem with my college project a few years ago. I responded (in a rather weasel way) by splitting the year and the date(MM:DD) in two separate columns. And before that, my project mate was simply getting all the dates and programatically going through them. We changed that because it was too inefficient - not that my solution was any more elegant either. Also, its probably not possible to do in a database that has been in use for a while by multiple apps.</p>\n" }, { "answer_id": 83934, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 0, "selected": false, "text": "<p>Give this a try:</p>\n\n<pre><code>SELECT * FROM Employees\nWHERE DATEADD(yyyy, DATEPART(yyyy, @Today)-DATEPART(yyyy, Birthday), Birthday) &gt; @Today \nAND DATEADD(yyyy, DATEPART(yyyy, @Today)-DATEPART(yyyy, Birthday), Birthday) &lt; DATEADD(dd, @NumDays, @Today)\n</code></pre>\n" }, { "answer_id": 84297, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 4, "selected": false, "text": "<p>Best use of datediff and dateadd. No rounding, no approximates, no 29th of february bug, nothing but date functions</p>\n\n<ol>\n<li><p><code>ageOfThePerson = DATEDIFF(yyyy,dateOfBirth, GETDATE())</code></p></li>\n<li><p><code>dateOfNextBirthday = DATEADD(yyyy,ageOfThePerson + 1, dateOfBirth)</code></p></li>\n<li><p><code>daysBeforeBirthday = DATEDIFF(d,GETDATE(), dateofNextBirthday)</code></p></li>\n</ol>\n\n<p>Thanks to @Gustavo Cardoso, new definition for the age of the person</p>\n\n<ol>\n<li><code>ageOfThePerson = FLOOR(DATEDIFF(d,dateOfBirth, GETDATE())/365.25)</code></li>\n</ol>\n" }, { "answer_id": 84536, "author": "clweeks", "author_id": 13748, "author_profile": "https://Stackoverflow.com/users/13748", "pm_score": 0, "selected": false, "text": "<p>Nuts! A good solution between when I started thinking about this and when I came back to answer. :)</p>\n\n<p>I came up with:</p>\n\n<pre><code>select (365 + datediff(d,getdate(),cast(cast(datepart(yy,getdate()) as varchar(4)) + '-' + cast(datepart(m,birthdt) as varchar(2)) + '-' + cast(datepart(d,birthdt) as varchar(2)) as datetime))) % 365\nfrom employees\nwhere (365 + datediff(d,getdate(),cast(cast(datepart(yy,getdate()) as varchar(4)) + '-' + cast(datepart(m,birthdt) as varchar(2)) + '-' + cast(datepart(d,birthdt) as varchar(2)) as datetime))) % 365 &lt; @NumDays\n</code></pre>\n\n<p>You don't need to cast getdate() as a datetime, right?</p>\n" }, { "answer_id": 330231, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Upcoming Birthday for the Employee - Sqlserver</p>\n\n<pre><code>DECLARE @sam TABLE\n(\n EmployeeIDs int,\n dob datetime\n)\nINSERT INTO @sam (dob, EmployeeIDs)\nSELECT DOBirth, EmployeeID FROM Employee\n\nSELECT *\nFROM\n(\n SELECT *, bd_this_year = DATEADD(YEAR, DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, dob), dob)\n FROM @sam s\n) d\nWHERE d.bd_this_year &gt; DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)\nAND d.bd_this_year &lt;= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 3)\n</code></pre>\n" }, { "answer_id": 528623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I hope this helps u in some way....</p>\n\n<pre><code>select Employeename,DOB \nfrom Employeemaster\nwhere day(Dob)&gt;day(getdate()) and month(DOB)&gt;=month(getDate())\n</code></pre>\n" }, { "answer_id": 2142833, "author": "Kyle", "author_id": 259594, "author_profile": "https://Stackoverflow.com/users/259594", "pm_score": 0, "selected": false, "text": "<p>This is a combination of a couple of the answers that was tested. This will find the next brithday after a certain date and the age they will be. Also the numdays will limit the range you are looking 7 days = week etc.</p>\n\n<pre><code>SELECT DISTINCT FLOOR(DATEDIFF(dd,Birthday, @BeginDate) / 365.25) + 1 age,\nDATEADD(yyyy, FLOOR(DATEDIFF(dd,Birthday, @BeginDate) / 365.25) + 1, Birthday) nextbirthday, birthday\nFROM table\nWHERE DATEADD(yyyy, FLOOR(DATEDIFF(dd,Birthday, @BeginDate) / 365.25) + 1, Birthday) &gt; @BeginDate \nAND DATEADD(yyyy, FLOOR(DATEDIFF(dd,Birthday, @BeginDate) / 365.25) + 1, Birthday) &lt; DATEADD(dd, @NumDays, @BeginDate)\norder by nextbirthday\n</code></pre>\n" }, { "answer_id": 2425453, "author": "Ramandeep Singh", "author_id": 291531, "author_profile": "https://Stackoverflow.com/users/291531", "pm_score": 0, "selected": false, "text": "<p>The best way to achieve the same is</p>\n\n<pre><code>DECLARE @StartDate DATETIME\nDECLARE @EndDate DATETIME\n\nSELECT Member.* from vwMember AS Member \nWHERE (DATEADD(YEAR, (DATEPART(YEAR, @StartDate) -\n DATEPART(YEAR, Member.dBirthDay)), Member.dBirthDay)\nBETWEEN @StartDate AND @EndDate)\n</code></pre>\n" }, { "answer_id": 4142816, "author": "strelc", "author_id": 502970, "author_profile": "https://Stackoverflow.com/users/502970", "pm_score": 1, "selected": false, "text": "<p>This is solution for MS SQL Server:\nIt returns employees with birthdays in 30 days.</p>\n\n<pre><code>SELECT * FROM rojstni_dnevi\n WHERE (DATEDIFF (dd, \n getdate(), \n DATEADD ( yyyy, \n DATEDIFF(yyyy, rDan, getdate()),\n rDan)\n nex )\n +365) % 365 &lt; 30\n</code></pre>\n" }, { "answer_id": 4352871, "author": "Nenad SRB", "author_id": 530324, "author_profile": "https://Stackoverflow.com/users/530324", "pm_score": -1, "selected": false, "text": "<p><strong>Try my solution... I have Informix database...</strong> </p>\n\n<pre><code>SELECT person, year(today)-year(birthdate) as years, birthdate,\n\nCASE\nWHEN MOD(year(birthdate)+((year(today)-year(birthdate))+1),4)&lt;&gt;0 AND MONTH(birthdate)=2 AND DAY(birthdate)=29 THEN \n CASE \n WHEN mdy(month(birthdate), 28, year(birthdate)+((year(today)-year(birthdate))+1))-today &gt;= 365 THEN (mdy(month(birthdate), 28, year(birthdate)+((year(today)-year(birthdate))+1))-today)-365\n WHEN mdy(month(birthdate), 28, year(birthdate)+((year(today)-year(birthdate))+1))-today &lt; 365 THEN mdy(month(birthdate), 28, year(birthdate)+((year(today)-year(birthdate))+1))-today\n END\nELSE\n CASE \n WHEN mdy(month(birthdate), day(birthdate), year(birthdate)+((year(today)-year(birthdate))+1))-today &gt;= 365 THEN (mdy(month(birthdate), day(birthdate), year(birthdate)+((year(today)-year(birthdate))+1))-today)-365\n WHEN mdy(month(birthdate), day(birthdate), year(birthdate)+((year(today)-year(birthdate))+1))-today &lt; 365 THEN mdy(month(birthdate), day(birthdate), year(birthdate)+((year(today)-year(birthdate))+1))-today\n END\nEND until\n\nFROM table_name\nWHERE mdy(month(birthdate), day(birthdate), 2000) &gt;= mdy(month(today), day(today), 2000)\nAND mdy(month(birthdate), day(birthdate), 2000) &lt;= mdy(month(today), day(today), 2000)+30\nOR\nmdy(month(birthdate), day(birthdate), 2000) &lt;= mdy(month(today), day(today), 2000)-(365-30)\nORDER BY 4, YEAR(birthdate)\n</code></pre>\n" }, { "answer_id": 5732821, "author": "Andres SK", "author_id": 338840, "author_profile": "https://Stackoverflow.com/users/338840", "pm_score": 4, "selected": false, "text": "<p>In case someone is still looking for a solution in <strong>MySQL</strong> (slightly different commands), here's the query:</p>\n\n<pre><code>SELECT\n name,birthday,\n FLOOR(DATEDIFF(DATE(NOW()),birthday) / 365.25) AS age_now,\n FLOOR(DATEDIFF(DATE_ADD(DATE(NOW()),INTERVAL 30 DAY),birthday) / 365.25) AS age_future\n\nFROM user\n\nWHERE 1 = (FLOOR(DATEDIFF(DATE_ADD(DATE(NOW()),INTERVAL 30 DAY),birthday) / 365.25)) - (FLOOR(DATEDIFF(DATE(NOW()),birthday) / 365.25))\n\nORDER BY MONTH(birthday),DAY(birthday)\n</code></pre>\n" }, { "answer_id": 8322697, "author": "Jovial", "author_id": 1072876, "author_profile": "https://Stackoverflow.com/users/1072876", "pm_score": 1, "selected": false, "text": "<p>I found the solution for this. This may save someone's precious time.</p>\n\n<pre><code> select EmployeeID,DOB,dates.date from emp_tb_eob_employeepersonal \n cross join dbo.GetDays(Getdate(),Getdate()+7) as dates where weekofmonthnumber&gt;0\n and month(dates.date)=month(DOB) and day(dates.date)=day(DOB)\n\n\n\nGO\n/****** Object: UserDefinedFunction [dbo].[GetDays] Script Date: 11/30/2011 13:19:17 ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n--SELECT [dbo].[GetDays] ('02/01/2011','02/28/2011')\n\nALTER FUNCTION [dbo].[GetDays](@startDate datetime, @endDate datetime)\nRETURNS @retValue TABLE\n(Days int ,Date datetime, WeekOfMonthNumber int, WeekOfMonthDescription varchar(10), DayName varchar(10))\nAS\nBEGIN\n DECLARE @nextDay int\n DECLARE @nextDate datetime \n DECLARE @WeekOfMonthNum int \n DECLARE @WeekOfMonthDes varchar(10) \n DECLARE @DayName varchar(10) \n SELECT @nextDate = @startDate, @WeekOfMonthNum = DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH,0,@startDate),0),@startDate) + 1, \n @WeekOfMonthDes = CASE @WeekOfMonthNum \n WHEN '1' THEN 'First' \n WHEN '2' THEN 'Second' \n WHEN '3' THEN 'Third' \n WHEN '4' THEN 'Fourth' \n WHEN '5' THEN 'Fifth' \n WHEN '6' THEN 'Sixth' \n END, \n @DayName \n = DATENAME(weekday, @startDate)\nSET @nextDay=1\nWHILE @nextDate &lt;= @endDate \nBEGIN \n INSERT INTO @retValue values (@nextDay,@nextDate, @WeekOfMonthNum, @WeekOfMonthDes, @DayName) \n SELECT @nextDay=@nextDay + 1 \nSELECT @nextDate = DATEADD(day,1,@nextDate), \n @WeekOfMonthNum \n = DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH,0, @nextDate),0), @nextDate) + 1, \n @WeekOfMonthDes \n = CASE @WeekOfMonthNum \n WHEN '1' THEN 'First' \n WHEN '2' THEN 'Second' \n WHEN '3' THEN 'Third' \n WHEN '4' THEN 'Fourth' \n WHEN '5' THEN 'Fifth' \n WHEN '6' THEN 'Sixth' \n END, \n @DayName \n = DATENAME(weekday, @nextDate) \n CONTINUE \nEND \n\nWHILE(@nextDay &lt;=31)\nBEGIN\n\n\n INSERT INTO @retValue values (@nextDay,@nextDate, 0, '', '') \n SELECT @nextDay=@nextDay + 1\n\nEND\n\n RETURN\nEND\n</code></pre>\n\n<p>Make a cross join with the dates and check for the comparison of month and dates.</p>\n" }, { "answer_id": 8762129, "author": "ButterDog", "author_id": 575085, "author_profile": "https://Stackoverflow.com/users/575085", "pm_score": 0, "selected": false, "text": "<p>I used this for <strong>MySQL</strong>, probably not the most efficient way to query but simple enough to implement. </p>\n\n<pre><code>select * from `schema`.`table` where date_format(birthday,'%m%d') &gt;= date_format(now(),'%m%d') and date_format(birthday,'%m%d') &lt; date_format(DATE_ADD(NOW(), INTERVAL 5 DAY),'%m%d');\n</code></pre>\n" }, { "answer_id": 10525075, "author": "RoMEoMusTDiE", "author_id": 1385774, "author_profile": "https://Stackoverflow.com/users/1385774", "pm_score": 0, "selected": false, "text": "<p>i believe this ticket has been closed ages ago but for the benefit of getting the correct sql query please have a look.</p>\n\n<pre><code>SELECT Employee_Name, DATE_OF_BIRTH\nFROM Hr_table \nWHERE \n\n/**\nfetching the original birth_date and replacing the birth year to the current but have to deduct 7 days to adjust jan 1-7 birthdate.\n**/\n\ndatediff(d,getdate(),DATEADD(year,datediff(year,DATEADD(d,-7,hr.DATE_OF_BIRTH),getdate()),hr.date_of_birth)) between 0 and 7\n\n-- current date looks ahead to 7 days for upcoming modified year birth date.\n\norder by\n\n-- sort by no of days before the birthday\ndatediff(d,getdate(),DATEADD(year,datediff(year,DATEADD(d,-7,hr.DATE_OF_BIRTH),getdate()),hr.date_of_birth))\n</code></pre>\n" }, { "answer_id": 10761415, "author": "Edyn", "author_id": 835561, "author_profile": "https://Stackoverflow.com/users/835561", "pm_score": 2, "selected": false, "text": "<p>Liked the approach of @strelc, but his sql was a bit off. Here's an updated version that works well and is simple to use:</p>\n\n<pre><code>SELECT * FROM User \nWHERE (DATEDIFF(dd, getdate(), DATEADD(yyyy, \n DATEDIFF(yyyy, birthdate, getdate()) + 1, birthdate)) + 1) % 366 &lt;= &lt;number of days&gt;\n</code></pre>\n\n<p>edit 10/2017: add single day to end</p>\n" }, { "answer_id": 15727698, "author": "The-Kido", "author_id": 2228838, "author_profile": "https://Stackoverflow.com/users/2228838", "pm_score": -1, "selected": false, "text": "<pre><code>CREATE PROCEDURE [dbo].[P_EmployeesGetBirths]\n @Date Date,\n @Days int\n as\n Begin\n SET NOCOUNT ON;\n\n Declare\n @From int = Month(@Date) * 100 + Day(@Date),\n @To int = Month(DateAdd(DD, @Days, @Date)) * 100 + Day(DateAdd(DD, @Days, @Date)),\n @NeutralDate Date = Cast('1900-'+cast(Month(@Date) as nvarchar(2))+'-' + cast(Day(@Date) as nvarchar(2)) as Date)\n\n Select\n DOB,\n DATEADD(DD, DateDiff(DD, @NeutralDate, DateAdd(YY, 1900-Year(DOB), DOB)), @Date) OnDate\n From\n Employees(nolock)\n Where\n DOB is not null and\n Month(DOB) * 100 + Day(DOB) between @From and @To\n order by\n Month(DOB) * 100 + Day(DOB)\n End\n Go\n</code></pre>\n" }, { "answer_id": 20287262, "author": "AjitChahal", "author_id": 1182993, "author_profile": "https://Stackoverflow.com/users/1182993", "pm_score": 0, "selected": false, "text": "<p>Better and easy solution:</p>\n\n<pre><code>select * from users with(nolock)\nwhere date_of_birth is not null \nand \n(\n DATEDIFF(dd,\n DATEADD(yy, -(YEAR(GETDATE())-1900),GETDATE()), --Today\n DATEADD(yy, -(YEAR(date_of_birth)-1901),date_of_birth)\n ) % 365\n) = 30\n</code></pre>\n" }, { "answer_id": 27052958, "author": "Danilo", "author_id": 4276813, "author_profile": "https://Stackoverflow.com/users/4276813", "pm_score": 1, "selected": false, "text": "<p>In less than a month:&nbsp;</p>\n\n<pre><code>SELECT * FROM people WHERE MOD( DATEDIFF( CURDATE( ) , `date_birth`) /30, 12 ) &lt;1 and (((month(`date_birth`)) = (month(curdate())) and (day(`date_birth`)) &gt; (day (curdate() ))) or ((month(`date_birth`)) &gt; (month(curdate())) and (day(`date_birth`)) &lt; (day (curdate() ))))\n</code></pre>\n" }, { "answer_id": 31208983, "author": "Pilso", "author_id": 3115921, "author_profile": "https://Stackoverflow.com/users/3115921", "pm_score": 0, "selected": false, "text": "<p>This solution also takes care for birthdays in the next year and the ordering:\n(dob = day of birth; bty = birthday this year; nbd = next birthday)</p>\n\n<pre><code>with rs (bty) as (\n SELECT DATEADD(Year, DATEPART(Year, GETDATE()) - DATEPART(Year, dob), dob) as bty FROM Employees\n),\nrs2 (nbd) as (\n select case when bty &lt; getdate() then DATEADD(yyyy, 1, bty) else bty end as nbd from rs\n)\nselect nbd, DATEDIFF(d, getdate(), nbd) as diff from rs2 where DATEDIFF(d, getdate(), nbd) &lt; 14 order by diff\n</code></pre>\n\n<p>This version, which avoids comparison of the dates, could be faster:</p>\n\n<pre><code>with rs (dob, bty) as (\n SELECT dob, DATEADD(Year, DATEPART(Year, GETDATE()) - DATEPART(Year, DOB), DOB) as bty FROM employee\n),\nrs2 (dob, nbd) as (\n select dob, DATEADD(yyyy, FLOOR(ABS((-1*(SIGN(DATEDIFF(d, getdate(), bty))))+0.1)), bty) as nbd from rs\n),\nrs3 (dob, diff) as (\n select dob, datediff(d, getdate(), nbd) as diff from rs2\n)\nselect dob, diff from rs3 where diff &lt; 14 order by diff\n</code></pre>\n\n<p>If the range covers the 29 of February in the next year, then use:</p>\n\n<pre><code>with rs (dob, ydiff) as (\n select dob, DATEPART(Year, GETDATE()) - DATEPART(Year, DOB) as ydiff from Employee\n),\nrs2 (dob, bty, ydiff) as (\n select dob, DATEADD(Year, ydiff, dob) as bty, ydiff from rs\n),\nrs3 (dob, nbd) as (\n select dob, DATEADD(yyyy, FLOOR(ABS((-1*(SIGN(DATEDIFF(d, getdate(), bty))))+0.1)) + ydiff, dob) as nbd from rs2\n),\nrs4 (dob, ddiff, nbd) as (\n select dob, datediff(d, getdate(), nbd) as diff, nbd from rs3\n)\nselect dob, nbd, ddiff from rs4 where ddiff &lt; 68 order by ddiff\n</code></pre>\n" }, { "answer_id": 31745302, "author": "Raj Sharma", "author_id": 5177678, "author_profile": "https://Stackoverflow.com/users/5177678", "pm_score": 0, "selected": false, "text": "<p>You can also use <code>DATEPART</code>:</p>\n\n<pre><code>-- To find out Today's Birthday\nDECLARE @today DATETIME\nSELECT @today = getdate()\n\nSELECT *\nFROM SMIS_Registration \nWHERE (DATEPART (month, DOB) &gt;= DATEPART (month, @today)\n AND DATEPART (day, DOB) = DATEPART (day, @today))\n</code></pre>\n" }, { "answer_id": 35137197, "author": "Fede H", "author_id": 2718127, "author_profile": "https://Stackoverflow.com/users/2718127", "pm_score": 2, "selected": false, "text": "<p>My guess is using \"365.25\" soon or later would be fail.</p>\n\n<p>So I test the working solution using \"365.25\"\nAnd It don't return the same numbers of rows for every case.\nHere an example:</p>\n\n<p><a href=\"http://sqlfiddle.com/#!3/94c3ce/7\" rel=\"nofollow\">http://sqlfiddle.com/#!3/94c3ce/7</a></p>\n\n<p>test with year 2016 and 2116 and you will see the difference. I only can post one link but change de /7 by /8 to see both queries. (/10 and /11 for the first answer)</p>\n\n<p>So, I suggest this another query, where the point is determinate next birthday from a starting date and then compare if it is in my range of interest.</p>\n\n<pre><code>SELECT * FROM Employees \nWHERE \nCASE WHEN (DATEADD(yyyy,DATEDIFF(yyyy, birthdt, @fromDate),birthdt) &lt; @fromDate )\nTHEN DATEADD(yyyy,DATEDIFF(yyyy, birthdt, @fromDate)+1,birthdt)\nELSE DATEADD(yyyy,DATEDIFF(yyyy, birthdt, @fromDate),birthdt) END\nBETWEEN @fromDate AND @toDate\n</code></pre>\n" }, { "answer_id": 35649323, "author": "Bhavesh Patel", "author_id": 3959714, "author_profile": "https://Stackoverflow.com/users/3959714", "pm_score": -1, "selected": false, "text": "<p>Current months birthday</p>\n\n<pre><code>SELECT * FROM tblMember m\nWHERE m.GDExpireDate != '' \nAND CONVERT(CHAR(2),CONVERT(datetime, m.dob, 103), 101) = CONVERT(CHAR(2), GETDATE(), 101) \nAND CONVERT(CHAR(2),CONVERT(datetime, m.dob, 103), 103) &gt;= CONVERT(CHAR(2), GETDATE(), 103)\n</code></pre>\n" }, { "answer_id": 39637799, "author": "hardik maheshwari", "author_id": 5860077, "author_profile": "https://Stackoverflow.com/users/5860077", "pm_score": 0, "selected": false, "text": "<p>select BirthDate,Name from Employees\norder by Case\nWHEN convert(nvarchar(5),BirthDate,101) &gt; convert(nvarchar(5),GETDATE(),101) then 2\nWHEN convert(nvarchar(5),BirthDate,101) &lt; convert(nvarchar(5),GETDATE(),101) then 3\nWHEN convert(nvarchar(5),BirthDate,101) = convert(nvarchar(5),GETDATE(),101) then 1 else 4 end ,convert(nvarchar(2),BirthDate,101),convert(nvarchar(2),BirthDate,105)</p>\n" }, { "answer_id": 52299426, "author": "Paresh Patel", "author_id": 3667653, "author_profile": "https://Stackoverflow.com/users/3667653", "pm_score": 0, "selected": false, "text": "<p>Below query will return all next birthday of employee, it is shortest query.</p>\n\n<pre><code>SELECT \n Employee.DOB,\n DATEADD(\n mm, \n (\n (\n (\n (\n DATEPART(yyyy, getdate())-DATEPART(yyyy, Employee.DOB )\n )\n +\n (\n 1-\n (\n ((DATEPART(mm, Employee.DOB)*100)+DATEPART(dd, Employee.DOB))\n /\n ((DATEPART(mm, getdate())*100) + DATEPART(dd, getdate()))\n )\n )\n )\n *12\n )\n ), \n Employee.DOB\n ) NextDOB\nFROM \n Employee \nORDER BY \n NextDOB ;\n</code></pre>\n\n<p>Above query will cover all next month excluding current date.</p>\n" }, { "answer_id": 55558001, "author": "smoothware", "author_id": 3465437, "author_profile": "https://Stackoverflow.com/users/3465437", "pm_score": 0, "selected": false, "text": "<p>Solution for <strong>SQLite3</strong>:</p>\n\n<pre><code>SELECT\n *, \n strftime('%j', birthday) - strftime('%j', 'now') AS days_remaining\nFROM\n person\nWHERE :n_days &gt;= CASE\n WHEN days_remaining &gt;= 0 THEN days_remaining\n ELSE days_remaining + strftime('%j', strftime('%Y-12-31', 'now'))\n END\n;\n</code></pre>\n\n<p>The solutions dividing by 325.25 to get the age, or bringing the birthdate to the current year etc. didn't work for me.\nWhat this does is computes the delta of the two daysOfTheYear (1-366). If the birthday didn't happen yet this year, you automatically get the correct number of remaining days, which you can compare to.\nIf the birthday already happened, remaining_days will be negative, and you can get the correct number of remaining days by still adding the total amount of days in the current year. This also correctly handles leap years, since in that case the extra day will be added as well (By using dayOfYear(Dec 31.))</p>\n" }, { "answer_id": 69908338, "author": "Santosh Kumar", "author_id": 17373939, "author_profile": "https://Stackoverflow.com/users/17373939", "pm_score": 0, "selected": false, "text": "<p>You can use this query for today birthday</p>\n<pre><code>select * \nfrom tableName\nwhere DAY(convert(date,GETDATE(),105))=DAY(convert(date,DOB,105))\nand month(convert(date,GETDATE(),105))=month(convert(date,DOB,105))\n</code></pre>\n" }, { "answer_id": 70525916, "author": "Renato M", "author_id": 7530317, "author_profile": "https://Stackoverflow.com/users/7530317", "pm_score": 0, "selected": false, "text": "<p>Here we need the real and the next to compare if it has already passed</p>\n<pre><code>CREATE FUNCTION dbo.FN_NEXT_BIRTHDAY(@BIRTHDAY DATE)\nRETURNS DATE\nAS\nBEGIN\n DECLARE @ACTUAL DATE = DATEADD(YEAR, DATEDIFF(YEAR, @BIRTHDAY , GETDATE()), @BIRTHDAY);\n DECLARE @NEXT DATE = DATEADD(YEAR, DATEDIFF(YEAR, @BIRTHDAY , GETDATE())+1, @BIRTHDAY);\n\n RETURN CASE WHEN @ACTUAL &gt; GETDATE() THEN @ACTUAL \n ELSE @NEXT \n END;\nEND;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2460/" ]
I'm trying to write a stored procedure to select employees who have birthdays that are upcoming. `SELECT * FROM Employees WHERE Birthday > @Today AND Birthday < @Today + @NumDays` This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' and '09-25-2008'. Is there a way to ignore the year portion of date fields and just compare month/days? This will be run every monday morning to alert managers of birthdays upcoming, so it possibly will span new years. Here is the working solution that I ended up creating, thanks Kogus. ``` SELECT * FROM Employees WHERE Cast(DATEDIFF(dd, birthdt, getDate()) / 365.25 as int) - Cast(DATEDIFF(dd, birthdt, futureDate) / 365.25 as int) <> 0 ```
*Note: I've edited this to fix what I believe was a significant bug. The currently posted version works for me.* This should work after you modify the field and table names to correspond to your database. ``` SELECT BRTHDATE AS BIRTHDAY ,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25) AS AGE_NOW ,FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25) AS AGE_ONE_WEEK_FROM_NOW FROM "Database name".dbo.EMPLOYEES EMP WHERE 1 = (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()+7) / 365.25)) - (FLOOR(DATEDIFF(dd,EMP.BRTHDATE,GETDATE()) / 365.25)) ``` Basically, it gets the # of days from their birthday to now, and divides that by 365 (to avoid rounding issues that come up when you convert directly to years). Then it gets the # of days from their birthday to a week from now, and divides that by 365 to get their age a week from now. If their birthday is within a week, then the difference between those two values will be 1. So it returns all of those records.
83,547
<p>I have a decimal number (let's call it <strong>goal</strong>) and an array of other decimal numbers (let's call the array <strong>elements</strong>) and I need to find all the combinations of numbers from <strong>elements</strong> which sum to goal.</p> <p>I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.</p> <p>Your method signature might look something like:</p> <pre><code>public decimal[][] Solve(decimal goal, decimal[] elements) </code></pre>
[ { "answer_id": 83596, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 2, "selected": false, "text": "<p>I think you've got a <a href=\"http://en.wikipedia.org/wiki/Bin_packing_problem\" rel=\"nofollow noreferrer\">bin packing problem</a> on your hands (which is NP-hard), so I think the only solution is going to be to try every possible combination until you find one that works.</p>\n\n<p>Edit: As pointed out in a comment, you won't <em>always</em> have to try <em>every</em> combination for <em>every</em> set of numbers you come across. However, any method you come up with has worst-case-scenario sets of numbers where you <em>will</em> have to try <em>every</em> combination -- or at least a subset of combinations that grows exponentially with the size of the set. </p>\n\n<p>Otherwise, it wouldn't be NP-hard.</p>\n" }, { "answer_id": 83603, "author": "ARKBAN", "author_id": 11889, "author_profile": "https://Stackoverflow.com/users/11889", "pm_score": 2, "selected": false, "text": "<p>You have described a <a href=\"http://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"nofollow noreferrer\">knapsack problem</a>, the only true solution is brute force. There are some approximation solutions which are faster, but they might not fit your needs.</p>\n" }, { "answer_id": 83748, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>The subset-sum problem, and the slightly more general knapsack problem, are solved with dynamic programming: brute-force enumeration of all combinations is not required. Consult Wikipedia or your favourite algorithms reference.</p>\n\n<p>Although the problems are NP-complete, they are very \"easy\" NP-complete. The algorithmic complexity in the number of elements is low.</p>\n" }, { "answer_id": 84168, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 5, "selected": true, "text": "<p>Interesting answers. Thank you for the pointers to Wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting/book balancing problem than a traditional bin-packing / knapsack problem.</p>\n\n<p>I have been following the development of stack overflow with interest and wondered how useful it would be. This problem came up at work and I wondered whether stack overflow could provide a ready-made answer (or a better answer) quicker than I could write it myself. Thanks also for the comments suggesting this be tagged homework - I guess that is reasonably accurate in light of the above.</p>\n\n<p>For those who are interested, here is my solution which uses recursion (naturally) I also changed my mind about the method signature and went for List> rather than decimal[][] as the return type:</p>\n\n<pre><code>public class Solver {\n\n private List&lt;List&lt;decimal&gt;&gt; mResults;\n\n public List&lt;List&lt;decimal&gt;&gt; Solve(decimal goal, decimal[] elements) {\n\n mResults = new List&lt;List&lt;decimal&gt;&gt;();\n RecursiveSolve(goal, 0.0m, \n new List&lt;decimal&gt;(), new List&lt;decimal&gt;(elements), 0);\n return mResults; \n }\n\n private void RecursiveSolve(decimal goal, decimal currentSum, \n List&lt;decimal&gt; included, List&lt;decimal&gt; notIncluded, int startIndex) {\n\n for (int index = startIndex; index &lt; notIncluded.Count; index++) {\n\n decimal nextValue = notIncluded[index];\n if (currentSum + nextValue == goal) {\n List&lt;decimal&gt; newResult = new List&lt;decimal&gt;(included);\n newResult.Add(nextValue);\n mResults.Add(newResult);\n }\n else if (currentSum + nextValue &lt; goal) {\n List&lt;decimal&gt; nextIncluded = new List&lt;decimal&gt;(included);\n nextIncluded.Add(nextValue);\n List&lt;decimal&gt; nextNotIncluded = new List&lt;decimal&gt;(notIncluded);\n nextNotIncluded.Remove(nextValue);\n RecursiveSolve(goal, currentSum + nextValue,\n nextIncluded, nextNotIncluded, startIndex++);\n }\n }\n }\n}\n</code></pre>\n\n<p>If you want an app to test this works, try this console app code:</p>\n\n<pre><code>class Program {\n static void Main(string[] args) {\n\n string input;\n decimal goal;\n decimal element;\n\n do {\n Console.WriteLine(\"Please enter the goal:\");\n input = Console.ReadLine();\n }\n while (!decimal.TryParse(input, out goal));\n\n Console.WriteLine(\"Please enter the elements (separated by spaces)\");\n input = Console.ReadLine();\n string[] elementsText = input.Split(' ');\n List&lt;decimal&gt; elementsList = new List&lt;decimal&gt;();\n foreach (string elementText in elementsText) {\n if (decimal.TryParse(elementText, out element)) {\n elementsList.Add(element);\n }\n }\n\n Solver solver = new Solver();\n List&lt;List&lt;decimal&gt;&gt; results = solver.Solve(goal, elementsList.ToArray());\n foreach(List&lt;decimal&gt; result in results) {\n foreach (decimal value in result) {\n Console.Write(\"{0}\\t\", value);\n }\n Console.WriteLine();\n }\n\n\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>I hope this helps someone else get their answer more quickly (whether for homework or otherwise).</p>\n\n<p>Cheers...</p>\n" }, { "answer_id": 85182, "author": "Adi", "author_id": 9090, "author_profile": "https://Stackoverflow.com/users/9090", "pm_score": 2, "selected": false, "text": "<p>While not solving the problem of brute force (as others already mentioned) you might want to sort your numbers first, and then go over the possible ones left (since once you passed Sum value, you can't add any number larger than Goal - Sum).</p>\n\n<p>This will change the way you implement your algorithm (in order to sort only once and then skip marked elements), but on the average would improve performance.</p>\n" }, { "answer_id": 2629125, "author": "guest", "author_id": 315410, "author_profile": "https://Stackoverflow.com/users/315410", "pm_score": -1, "selected": false, "text": "<pre><code>public class Logic1 {\n static int val = 121;\n public static void main(String[] args)\n {\n f(new int[] {1,4,5,17,16,100,100}, 0, 0, \"{\");\n }\n\n static void f(int[] numbers, int index, int sum, String output)\n {\n System.out.println(output + \" } = \" + sum);\n //System.out.println(\"Index value1 is \"+index);\n check (sum);\n if (index == numbers.length)\n {\n System.out.println(output + \" } = \" + sum);\n return;\n }\n\n // include numbers[index]\n f(numbers, index + 1, sum + numbers[index], output + \" \" + numbers[index]);\n check (sum);\n //System.out.println(\"Index value2 is \"+index);\n // exclude numbers[index]\n f(numbers, index + 1, sum, output);\n check (sum);\n }\n\n static void check (int sum1)\n {\n if (sum1 == val)\n System.exit(0);\n }\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16005/" ]
I have a decimal number (let's call it **goal**) and an array of other decimal numbers (let's call the array **elements**) and I need to find all the combinations of numbers from **elements** which sum to goal. I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective. Your method signature might look something like: ``` public decimal[][] Solve(decimal goal, decimal[] elements) ```
Interesting answers. Thank you for the pointers to Wikipedia - whilst interesting - they don't actually solve the problem as stated as I was looking for exact matches - more of an accounting/book balancing problem than a traditional bin-packing / knapsack problem. I have been following the development of stack overflow with interest and wondered how useful it would be. This problem came up at work and I wondered whether stack overflow could provide a ready-made answer (or a better answer) quicker than I could write it myself. Thanks also for the comments suggesting this be tagged homework - I guess that is reasonably accurate in light of the above. For those who are interested, here is my solution which uses recursion (naturally) I also changed my mind about the method signature and went for List> rather than decimal[][] as the return type: ``` public class Solver { private List<List<decimal>> mResults; public List<List<decimal>> Solve(decimal goal, decimal[] elements) { mResults = new List<List<decimal>>(); RecursiveSolve(goal, 0.0m, new List<decimal>(), new List<decimal>(elements), 0); return mResults; } private void RecursiveSolve(decimal goal, decimal currentSum, List<decimal> included, List<decimal> notIncluded, int startIndex) { for (int index = startIndex; index < notIncluded.Count; index++) { decimal nextValue = notIncluded[index]; if (currentSum + nextValue == goal) { List<decimal> newResult = new List<decimal>(included); newResult.Add(nextValue); mResults.Add(newResult); } else if (currentSum + nextValue < goal) { List<decimal> nextIncluded = new List<decimal>(included); nextIncluded.Add(nextValue); List<decimal> nextNotIncluded = new List<decimal>(notIncluded); nextNotIncluded.Remove(nextValue); RecursiveSolve(goal, currentSum + nextValue, nextIncluded, nextNotIncluded, startIndex++); } } } } ``` If you want an app to test this works, try this console app code: ``` class Program { static void Main(string[] args) { string input; decimal goal; decimal element; do { Console.WriteLine("Please enter the goal:"); input = Console.ReadLine(); } while (!decimal.TryParse(input, out goal)); Console.WriteLine("Please enter the elements (separated by spaces)"); input = Console.ReadLine(); string[] elementsText = input.Split(' '); List<decimal> elementsList = new List<decimal>(); foreach (string elementText in elementsText) { if (decimal.TryParse(elementText, out element)) { elementsList.Add(element); } } Solver solver = new Solver(); List<List<decimal>> results = solver.Solve(goal, elementsList.ToArray()); foreach(List<decimal> result in results) { foreach (decimal value in result) { Console.Write("{0}\t", value); } Console.WriteLine(); } Console.ReadLine(); } } ``` I hope this helps someone else get their answer more quickly (whether for homework or otherwise). Cheers...
83,553
<p>I need to write a program used internally where different users will have different abilities within the program.</p> <p>Rather than making users have a new username and password, how do I tie into an existing domain server's login system?</p> <p>Assume .NET (C#, VB, ASP, etc)</p> <p>-Adam</p>
[ { "answer_id": 83587, "author": "Matt Everson", "author_id": 7300, "author_profile": "https://Stackoverflow.com/users/7300", "pm_score": 3, "selected": true, "text": "<p>For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first.</p>\n\n<p>Use this to get the current user name:</p>\n\n<pre><code>private string getWindowsUsername()\n{\n AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);\n return Thread.CurrentPrincipal.Identity.Name;\n}\n</code></pre>\n\n<p>And then something like this to check a role:</p>\n\n<pre><code>if (Thread.CurrentPrincipal.IsInRole(\"Domain Users\") == true)\n{}\n</code></pre>\n\n<p>In ASP.NET, the thread will belong to IIS, so instead you should </p>\n\n<ol>\n<li>Set the virtual folder or website to require authentication</li>\n<li>Get the user name supplied by the browser with Request.ServerVariables(\"LOGON_USER\")</li>\n<li>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx\" rel=\"nofollow noreferrer\">DirectorySearcher</a> class to find the users groups</li>\n</ol>\n" }, { "answer_id": 83590, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 2, "selected": false, "text": "<p>I would use LDAP</p>\n\n<p>and the DirectorySearcher Class:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx</a></p>\n" }, { "answer_id": 83619, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>Assuming this is served through IIS, I would tell IIS to authenticate via the domain, but I would keep authorization (what roles a user is associated with, accessible functionality, etc) within the application itself. </p>\n\n<p>You can retreive the username used to authenticate via </p>\n\n<pre><code>Trim(Request.ServerVariables(\"LOGON_USER\")).Replace(\"/\", \"\\\").Replace(\"'\", \"''\")\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>CStr(Session(\"User\")).Substring(CStr(Session(\"User\")).LastIndexOf(\"\\\") + 1)\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
I need to write a program used internally where different users will have different abilities within the program. Rather than making users have a new username and password, how do I tie into an existing domain server's login system? Assume .NET (C#, VB, ASP, etc) -Adam
For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first. Use this to get the current user name: ``` private string getWindowsUsername() { AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); return Thread.CurrentPrincipal.Identity.Name; } ``` And then something like this to check a role: ``` if (Thread.CurrentPrincipal.IsInRole("Domain Users") == true) {} ``` In ASP.NET, the thread will belong to IIS, so instead you should 1. Set the virtual folder or website to require authentication 2. Get the user name supplied by the browser with Request.ServerVariables("LOGON\_USER") 3. Use the [DirectorySearcher](http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx) class to find the users groups
83,653
<p>The following returns </p> <blockquote> <p>Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '&lt;null&gt;'</p> </blockquote> <pre><code>aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null) </code></pre> <hr> <p>The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par.</p>
[ { "answer_id": 83664, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<pre><code>aNullableDouble = (double.TryParse(aString, out aDouble)?new Nullable&lt;double&gt;(aDouble):null)\n</code></pre>\n" }, { "answer_id": 83667, "author": "ljs", "author_id": 3394, "author_profile": "https://Stackoverflow.com/users/3394", "pm_score": 4, "selected": true, "text": "<pre><code>aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null;\n</code></pre>\n" }, { "answer_id": 83676, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 3, "selected": false, "text": "<p>Just blow the syntax out into the full syntax instead of the shorthand ... it'll be easier to read:</p>\n\n<pre><code>aNullableDouble = null;\nif (double.TryParse(aString, out aDouble))\n{\n aNullableDouble = aDouble;\n}\n</code></pre>\n" }, { "answer_id": 83690, "author": "Sean Hanley", "author_id": 7290, "author_profile": "https://Stackoverflow.com/users/7290", "pm_score": 0, "selected": false, "text": "<p>.NET supports <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx\" rel=\"nofollow noreferrer\">nullable types</a>, but by declaring them as such you have to treat them a bit differently (as, understandably, something which is normally a value type now is sort of reference-ish).</p>\n\n<p>This also might not help much if you end up having to do too much converting between nullable doubles and regular doubles... as might easily be the case with an auto-generated set of classes.</p>\n" }, { "answer_id": 83979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The interesting side-effect of using nullable types is that you can't really use a shorthand IF. Shorthand IF has to return the same Type from both conditions, and it can't be null in either case. So, cast or write it out :) </p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
The following returns > > Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '<null>' > > > ``` aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null) ``` --- The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par.
``` aNullableDouble = double.TryParse(aString, out aDouble) ? (double?)aDouble : null; ```
83,674
<p>I want to find records on a combination of created_on >= some date AND name IN some list of names.</p> <p>For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names.</p> <p>Is there a way to combine the two?</p>
[ { "answer_id": 83736, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 6, "selected": true, "text": "<p>You can use named scopes in rails 2.1 and above</p>\n\n<pre><code>Class Test &lt; ActiveRecord::Base\n named_scope :created_after_2005, :conditions =&gt; \"created_on &gt; 2005-01-01\"\n named_scope :named_fred, :conditions =&gt; { :name =&gt; \"fred\"}\nend\n</code></pre>\n\n<p>then you can do</p>\n\n<pre><code>Test.created_after_2005.named_fred\n</code></pre>\n\n<p>Or you can give named_scope a lambda allowing you to pass in arguments</p>\n\n<pre><code>Class Test &lt; ActiveRecord::Base\n named_scope :created_after, lambda { |date| {:conditions =&gt; [\"created_on &gt; ?\", date]} }\n named_scope :named, lambda { |name| {:conditions =&gt; {:name =&gt; name}} }\nend\n</code></pre>\n\n<p>then you can do</p>\n\n<pre><code>Test.created_after(Time.now-1.year).named(\"fred\")\n</code></pre>\n" }, { "answer_id": 83933, "author": "Sixty4Bit", "author_id": 1681, "author_profile": "https://Stackoverflow.com/users/1681", "pm_score": 2, "selected": false, "text": "<p>For more on named_scopes see <a href=\"http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality\" rel=\"nofollow noreferrer\">Ryan's announcement</a> and the <a href=\"http://railscasts.com/episodes/108\" rel=\"nofollow noreferrer\">Railscast on named_scopes</a></p>\n\n<pre><code>class Person &lt; ActiveRecord::Base\n named_scope :registered, lambda { |time_ago| { :conditions =&gt; ['created_at &gt; ?', time_ago] } }\n named_scope :with_names, lambda { |names| { :conditions =&gt; { :names =&gt; names } } }\nend\n</code></pre>\n\n<p>If you are going to pass in variables to your scopes you have to use a lambda.</p>\n" }, { "answer_id": 84256, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 1, "selected": false, "text": "<p>The named scopes already proposed are pretty fine. The clasic way to do it would be:</p>\n\n<pre><code>names = [\"dave\", \"jerry\", \"mike\"]\ndate = DateTime.now\nPerson.find(:all, :conidtions =&gt; [\"created_at &gt; ? AND name IN ?\", date, names])\n</code></pre>\n" }, { "answer_id": 85781, "author": "Josh Schwartzman", "author_id": 16447, "author_profile": "https://Stackoverflow.com/users/16447", "pm_score": 3, "selected": false, "text": "<p>If you're using an older version Rails, Honza's query is close, but you need to add parentheses for the strings that get placed in the IN condition:</p>\n\n<pre><code>Person.find(:all, :conditions =&gt; [\"created_at &gt; ? AND name IN (?)\", date, names])\n</code></pre>\n\n<p>Using IN can be a mixed bag: it's fastest for integers and slowest for a list of strings. If you find yourself using just one name, definitely use an equals operator:</p>\n\n<pre><code>Person.find(:all, :conditions =&gt; [\"created_at &gt; ? AND name = ?\", date, name])\n</code></pre>\n" }, { "answer_id": 89935, "author": "Tony Pitale", "author_id": 1167846, "author_profile": "https://Stackoverflow.com/users/1167846", "pm_score": 0, "selected": false, "text": "<p>I think I'm either going to use simple AR finders or <a href=\"http://www.binarylogic.com/2008/9/1/searchgasm-released\" rel=\"nofollow noreferrer\">Searchgasm</a>.</p>\n" }, { "answer_id": 127668, "author": "ismaSan", "author_id": 21702, "author_profile": "https://Stackoverflow.com/users/21702", "pm_score": 2, "selected": false, "text": "<p>The cool thing about named_scopes is that they work on collections too:</p>\n\n<pre><code>class Post &lt; ActiveRecord::Base\n named_scope :published, :conditions =&gt; {:status =&gt; 'published'}\nend\n\n@post = Post.published\n\n@posts = current_user.posts.published\n</code></pre>\n" }, { "answer_id": 16311941, "author": "Sujoy Gupta", "author_id": 634977, "author_profile": "https://Stackoverflow.com/users/634977", "pm_score": 2, "selected": false, "text": "<p>You can chain the <code>where</code> clause:</p>\n\n<p><code>Person.where(name: ['foo', 'bar', 'baz']).where('id &gt;= ?', 42).first</code></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167846/" ]
I want to find records on a combination of created\_on >= some date AND name IN some list of names. For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names. Is there a way to combine the two?
You can use named scopes in rails 2.1 and above ``` Class Test < ActiveRecord::Base named_scope :created_after_2005, :conditions => "created_on > 2005-01-01" named_scope :named_fred, :conditions => { :name => "fred"} end ``` then you can do ``` Test.created_after_2005.named_fred ``` Or you can give named\_scope a lambda allowing you to pass in arguments ``` Class Test < ActiveRecord::Base named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} } named_scope :named, lambda { |name| {:conditions => {:name => name}} } end ``` then you can do ``` Test.created_after(Time.now-1.year).named("fred") ```
83,770
<p>I'm trying to create a server control, which inherits from TextBox, that will automatically have a <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx" rel="nofollow noreferrer">CalendarExtender</a> attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.</p>
[ { "answer_id": 83951, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 3, "selected": true, "text": "<p>I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.</p>\n\n<p>In the <code>CreateChildControls</code> method of the CompositeControl I use code similar to this:</p>\n\n<pre><code>TextBox textbox = new TextBox();\ntextbox.ID = this.ID + \"Textbox\";\ntextbox.Text = this.EditableField.TextValue;\ntextbox.TextChanged += new EventHandler(HandleTextboxTextChanged);\ntextbox.Width = new Unit(100, UnitType.Pixel);\nCalendarExtender calExender = new CalendarExtender();\ncalExender.PopupButtonID = \"Image1\";\ncalExender.TargetControlID = textbox.ID;\nthis.Controls.Add(textbox);\nthis.Controls.Add(calExender);\n</code></pre>\n\n<p>Of course make sure that the form containing this CompositeControl has a toolkit script manager.</p>\n" }, { "answer_id": 2254764, "author": "spot", "author_id": 145103, "author_profile": "https://Stackoverflow.com/users/145103", "pm_score": 1, "selected": false, "text": "<p>I know this is an old thread, but I came across it when I had a similar question. This is what I ended up implementing, and it works great. If you want the control to BE a TextBox, then simply pump out the extender during the call to Render.</p>\n\n<pre><code>Imports System.Web.UI.WebControls\nImports AjaxControlToolkit\n\nPublic Class DateTextBox\n Inherits TextBox\n\n Private _dateValidator As CompareValidator\n Private _calendarExtender As CalendarExtender\n\n Protected Overrides Sub OnInit(ByVal e As System.EventArgs)\n MyBase.OnInit(e)\n\n _dateValidator = New CompareValidator\n With _dateValidator\n .ControlToValidate = ID\n Rem set your other properties\n End With\n Controls.Add(_dateValidator)\n\n _calendarExtender = New CalendarExtender\n With _calendarExtender\n .TargetControlID = ID\n End With\n Controls.Add(_calendarExtender)\n End Sub\n\n Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)\n MyBase.Render(writer)\n _dateValidator.RenderControl(writer)\n _calendarExtender.RenderControl(writer)\n End Sub\nEnd Class\n</code></pre>\n" }, { "answer_id": 8034387, "author": "Vikram chouhan", "author_id": 1033434, "author_profile": "https://Stackoverflow.com/users/1033434", "pm_score": 1, "selected": false, "text": "<p>You can easily add ajax calendar in custom server controls. You need to add two reference in your application.\n1. AjaxControlToolkit.dll\n2. System.Web.Extensions\nWith the help of second reference we will get all the property of “CalendarExtender” in your custom server controls.</p>\n" }, { "answer_id": 9359284, "author": "Ranadheer Reddy", "author_id": 1215594, "author_profile": "https://Stackoverflow.com/users/1215594", "pm_score": 0, "selected": false, "text": "<p>When you are trying to not allow users to type anything in the textbox, but only be filled by the calendar extender and then you try to get the selected date from the textbox control it may be empty string if you have set the textbox property to ReadOnly=\"True\".</p>\n\n<p>Its because read only controls are NOT posted back to the server. Workaround for this is the following:</p>\n\n<p>protected void Page_Load(object sender, EventArgs e)</p>\n\n<p>{</p>\n\n<p>TextBox1.Attributes.Add(\"readonly\", \"readonly\");</p>\n\n<p>}</p>\n\n<p>Hope it helps.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13583/" ]
I'm trying to create a server control, which inherits from TextBox, that will automatically have a [CalendarExtender](http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Calendar/Calendar.aspx) attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.
I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender. In the `CreateChildControls` method of the CompositeControl I use code similar to this: ``` TextBox textbox = new TextBox(); textbox.ID = this.ID + "Textbox"; textbox.Text = this.EditableField.TextValue; textbox.TextChanged += new EventHandler(HandleTextboxTextChanged); textbox.Width = new Unit(100, UnitType.Pixel); CalendarExtender calExender = new CalendarExtender(); calExender.PopupButtonID = "Image1"; calExender.TargetControlID = textbox.ID; this.Controls.Add(textbox); this.Controls.Add(calExender); ``` Of course make sure that the form containing this CompositeControl has a toolkit script manager.
83,807
<p>All I know about the constraint is it's name (<code>SYS_C003415</code>), but I want to see it's definition.</p>
[ { "answer_id": 83811, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 5, "selected": false, "text": "<p>Looks like I should be querying <code>ALL_CONSTRAINTS</code>.</p>\n\n<pre><code>select OWNER, CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION from ALL_CONSTRAINTS where CONSTRAINT_NAME = 'SYS_C003415';\n</code></pre>\n" }, { "answer_id": 83838, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 0, "selected": false, "text": "<p>Or to see all constaints use SYS.DBA_CONSTRAINTS (If you have the privileges)</p>\n" }, { "answer_id": 108376, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 4, "selected": true, "text": "<p>Another option would be to reverse engineer the DDL...</p>\n\n<pre><code>DBMS_METADATA.GET_DDL('CONSTRAINT', 'SYS_C003415')\n</code></pre>\n\n<p>Some examples here....</p>\n\n<p><a href=\"http://www.psoug.org/reference/dbms_metadata.html\" rel=\"noreferrer\">http://www.psoug.org/reference/dbms_metadata.html</a></p>\n" }, { "answer_id": 35593947, "author": "Rakesh", "author_id": 5238522, "author_profile": "https://Stackoverflow.com/users/5238522", "pm_score": 3, "selected": false, "text": "<p>Use following query to get a definition of constraint in oracle:</p>\n\n<pre><code>Select DBMS_METADATA.GET_DDL('CONSTRAINT', 'CONSTRAINT_NAME') from dual\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4203/" ]
All I know about the constraint is it's name (`SYS_C003415`), but I want to see it's definition.
Another option would be to reverse engineer the DDL... ``` DBMS_METADATA.GET_DDL('CONSTRAINT', 'SYS_C003415') ``` Some examples here.... <http://www.psoug.org/reference/dbms_metadata.html>
83,856
<p>I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value .</p> <p>Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ? I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table </p> <p>and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table </p>
[ { "answer_id": 83910, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 5, "selected": true, "text": "<p>Although it is not one call, you can nest the <code>replace()</code> calls:</p>\n\n<pre><code>SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval)\n</code></pre>\n" }, { "answer_id": 83958, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>If you are doing this inside of a select, you can just piece it together, if your replacement values are columns, using string concatenation.</p>\n" }, { "answer_id": 28584627, "author": "Florin Ghita", "author_id": 319875, "author_profile": "https://Stackoverflow.com/users/319875", "pm_score": 3, "selected": false, "text": "<p>If there are many variables to replace and you have them in another table and if the number of variables is variable you can use a recursive CTE to replace them.\nAn example below. In table fg_rulez you put the strings with their replacement. In table fg_data you have your input strings.</p>\n\n<pre><code>set define off;\ndrop table fg_rulez\ncreate table fg_rulez as \n select 1 id,'&lt;' symbol, 'less than' text from dual\n union all select 2, '&gt;', 'great than' from dual\n union all select 3, '$', 'dollars' from dual\n union all select 4, '&amp;', 'and' from dual;\ndrop table fg_data;\ncreate table fg_Data AS(\n SELECT 'amount $ must be &lt; 1 &amp; &gt; 2' str FROM dual\n union all\n SELECT 'John is &gt; Peter &amp; has many $' str FROM dual\n union all\n SELECT 'Eliana is &lt; mary &amp; do not has many $' str FROM dual\n\n );\n\n\nWITH q(str, id) as (\n SELECT str, 0 id \n FROM fg_Data \n UNION ALL\n SELECT replace(q.str,symbol,text), fg_rulez.id\n FROM q \n JOIN fg_rulez \n ON q.id = fg_rulez.id - 1\n)\nSELECT str from q where id = (select max(id) from fg_rulez);\n</code></pre>\n\n<p>So, a single <code>replace</code>.</p>\n\n<p>Result:</p>\n\n<pre><code>amount dollars must be less than 1 and great than 2 \nJohn is great than Peter and has many dollars \nEliana is less than mary and do not has many dollars\n</code></pre>\n\n<p>The terminology symbol instead of variable comes from <a href=\"https://stackoverflow.com/q/28580987/319875\">this duplicated question.</a></p>\n\n<p><strong>Oracle 11gR2</strong></p>\n" }, { "answer_id": 35405674, "author": "Ricardo Arnold", "author_id": 1197394, "author_profile": "https://Stackoverflow.com/users/1197394", "pm_score": 1, "selected": false, "text": "<p>If the number of values to replace is too big or you need to be able to easily maintain it, you could also split the string, use a dictionary table and finally aggregate the results <br></p>\n\n<p>In the example below I'm assuming that the words in your string are separated with blankspaces and the wordcount in the string will not be bigger than 100 (pivot table cardinality)</p>\n\n<pre><code>with Dict as\n (select '{1}' String, 'myfirstval' Repl from dual\n union all\n select '{2}' String, 'mysecondval' Repl from dual\n union all\n select '{3}' String, 'mythirdval' Repl from dual\n union all \n select '{Nth}' String, 'myNthval' Repl from dual \n\n )\n,MyStrings as\n (select 'This is the first example {1} ' Str, 1 strnum from dual\n union all\n select 'In the Second example all values are shown {1} {2} {3} {Nth} ', 2 from dual\n union all\n select '{3} Is the value for the third', 3 from dual\n union all\n select '{Nth} Is the value for the Nth', 4 from dual \n )\n,pivot as (\n Select Rownum Pnum\n From dual\n Connect By Rownum &lt;= 100 \n )\n,StrtoRow as\n(\nSELECT rownum rn\n ,ms.strnum\n ,REGEXP_SUBSTR (Str,'[^ ]+',1,pv.pnum) TXT\n FROM MyStrings ms\n ,pivot pv\nwhere REGEXP_SUBSTR (Str,'[^ ]+',1,pv.pnum) is not null\n)\nSelect Listagg(NVL(Repl,TXT),' ') within group (order by rn) \nfrom\n(\nSelect sr.TXT, d.Repl, sr.strnum, sr.rn\n from StrtoRow sr\n ,dict d\n where sr.TXT = d.String(+) \norder by strnum, rn \n) group by strnum\n</code></pre>\n" }, { "answer_id": 53215573, "author": "Olc", "author_id": 1770247, "author_profile": "https://Stackoverflow.com/users/1770247", "pm_score": 1, "selected": false, "text": "<p>Let's write the same sample as a CTE only:</p>\n\n<pre><code>with fg_rulez as (\n select 1 id,'&lt;' symbol, 'less than' text from dual\n union all select 2, '&gt;', 'greater than' from dual\n union all select 3, '$', 'dollars' from dual\n union all select 4, '+', 'and' from dual\n), fg_Data AS (\n SELECT 'amount $ must be &lt; 1 + &gt; 2' str FROM dual\n union all\n SELECT 'John is &gt; Peter + has many $' str FROM dual\n union all\n SELECT 'Eliana is &lt; mary + do not has many $' str FROM dual\n), q(str, id) as (\n SELECT str, 0 id \n FROM fg_Data \n UNION ALL\n SELECT replace(q.str,symbol,text), fg_rulez.id\n FROM q \n JOIN fg_rulez \n ON q.id = fg_rulez.id - 1\n)\nSELECT str from q where id = (select max(id) from fg_rulez);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14299/" ]
I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value . Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ? I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table
Although it is not one call, you can nest the `replace()` calls: ``` SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval) ```
83,863
<p>I want to find a way to develop database projects quickly in Visual Studio. Any ideas?</p>
[ { "answer_id": 83888, "author": "Chris Woodruff", "author_id": 7001, "author_profile": "https://Stackoverflow.com/users/7001", "pm_score": 3, "selected": true, "text": "<p>I have a method of creating and updating database projects in Visual Studio 2005 that I thought was common knowledge. After asking a few coworkers if they knew how to update their database projects with this method and receiving no's, I thought I would blog about it and pass along some helpful hints and best practices.</p>\n\n<p>I work a lot with databases and especially stored procedures that are built to be used with business logic/data access .NET framework. I enjoy working with databases and always create database projects to live with my .NET projects. I am psychotic about keeping database projects up to date. I have been burned too many time in my younger years where I needed to create a stored procedure that was deleted or was out of sync with the application using the database.</p>\n\n<p>After creating your database project in Visual Studio 2005 as shown:</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb16.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb16.png</a></p>\n\n<p>Create 3 new directories in the projects: Tables, Stored Procedures and Functions. I usually only stored these for my projects.</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb17.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb17.png</a></p>\n\n<p>I now open the Server Explorer in Visual Studio and create a new connection to my desired database. I am using Northwind as my example. I am not going to walk through the creation of the connection for this example.</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb18.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb18.png</a></p>\n\n<p>I will use a stored procedure as my example on how to update the database project. First I expand the \"Stored Procedures\" directory in the Server Explorer for the Northwind database. I select a stored procedure.</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb19.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb19.png</a></p>\n\n<p>I drag the stored procedure to the \"Stored Procedures\" directory in the Solution Explorer and drop it.</p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb20.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb20.png</a></p>\n\n<p><a href=\"http://www.cloudsocket.com/images/image-thumb21.png\" rel=\"nofollow noreferrer\">alt text http://www.cloudsocket.com/images/image-thumb21.png</a></p>\n\n<p>If you open the file for the dragged stored procedures you will find that the IDE created the script as followed:</p>\n\n<pre><code>/****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/\nIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC'))\nDROP PROCEDURE [dbo].[CustOrdersOrders]\nGO\n/****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nIF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC'))\nBEGIN\nEXEC dbo.sp_executesql @statement = N'\nCREATE PROCEDURE CustOrdersOrders @CustomerID nchar(5)\nAS\nSELECT OrderID,\n OrderDate,\n RequiredDate,\n ShippedDate\nFROM Orders\nWHERE CustomerID = @CustomerID\nORDER BY OrderID\n'\nEND\nGO\n</code></pre>\n\n<p>You can now drag over all the tables, functions and remaining stored procedures from your database. You can also right click on each script in the Solution Explorer and run the scripts on your database project's referenced database.</p>\n" }, { "answer_id": 83891, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 0, "selected": false, "text": "<p>DataDude? <a href=\"http://msdn.microsoft.com/en-us/vsts2008/db/default.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/vsts2008/db/default.aspx</a></p>\n" }, { "answer_id": 1066985, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Hey Chris, I also use the same way for keeping a database project, the only problem, is that you often make changes to stored procedures, and sometimes you forget which ones you changed, so you might drag one and forget the other.\nDo you know of a way to synchronize the database project with the database, or a way to import latest script for stored procs in your project, after they have been added by dragging the first time.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7001/" ]
I want to find a way to develop database projects quickly in Visual Studio. Any ideas?
I have a method of creating and updating database projects in Visual Studio 2005 that I thought was common knowledge. After asking a few coworkers if they knew how to update their database projects with this method and receiving no's, I thought I would blog about it and pass along some helpful hints and best practices. I work a lot with databases and especially stored procedures that are built to be used with business logic/data access .NET framework. I enjoy working with databases and always create database projects to live with my .NET projects. I am psychotic about keeping database projects up to date. I have been burned too many time in my younger years where I needed to create a stored procedure that was deleted or was out of sync with the application using the database. After creating your database project in Visual Studio 2005 as shown: [alt text http://www.cloudsocket.com/images/image-thumb16.png](http://www.cloudsocket.com/images/image-thumb16.png) Create 3 new directories in the projects: Tables, Stored Procedures and Functions. I usually only stored these for my projects. [alt text http://www.cloudsocket.com/images/image-thumb17.png](http://www.cloudsocket.com/images/image-thumb17.png) I now open the Server Explorer in Visual Studio and create a new connection to my desired database. I am using Northwind as my example. I am not going to walk through the creation of the connection for this example. [alt text http://www.cloudsocket.com/images/image-thumb18.png](http://www.cloudsocket.com/images/image-thumb18.png) I will use a stored procedure as my example on how to update the database project. First I expand the "Stored Procedures" directory in the Server Explorer for the Northwind database. I select a stored procedure. [alt text http://www.cloudsocket.com/images/image-thumb19.png](http://www.cloudsocket.com/images/image-thumb19.png) I drag the stored procedure to the "Stored Procedures" directory in the Solution Explorer and drop it. [alt text http://www.cloudsocket.com/images/image-thumb20.png](http://www.cloudsocket.com/images/image-thumb20.png) [alt text http://www.cloudsocket.com/images/image-thumb21.png](http://www.cloudsocket.com/images/image-thumb21.png) If you open the file for the dragged stored procedures you will find that the IDE created the script as followed: ``` /****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/ IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[CustOrdersOrders] GO /****** Object: StoredProcedure [dbo].[CustOrdersOrders] Script Date: 08/25/2007 15:22:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC')) BEGIN EXEC dbo.sp_executesql @statement = N' CREATE PROCEDURE CustOrdersOrders @CustomerID nchar(5) AS SELECT OrderID, OrderDate, RequiredDate, ShippedDate FROM Orders WHERE CustomerID = @CustomerID ORDER BY OrderID ' END GO ``` You can now drag over all the tables, functions and remaining stored procedures from your database. You can also right click on each script in the Solution Explorer and run the scripts on your database project's referenced database.
83,887
<p>Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class.</p> <pre><code>&lt;?php abstract class ParentClass { public static function whoAmI () { // NOT correct, always gives 'ParentClass' $class = __CLASS__; // NOT correct, always gives 'ParentClass'. // Also very round-about and likely slow. $trace = debug_backtrace(); $class = $trace[0]['class']; return $class; } } class ChildClass1 extends ParentClass { } class ChildClass2 extends ParentClass { } // Shows 'ParentClass' // Want to show 'ChildClass1' print ChildClass1::whoAmI(); print "\n"; // Shows 'ParentClass' // Want to show 'ChildClass2' print ChildClass2::whoAmI(); print "\n"; </code></pre>
[ { "answer_id": 83902, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "<p>I believe what you're referring to is a known php bug. Php 5.3 is aiming to address this issue with a new Late Static Binding feature. </p>\n\n<p><a href=\"http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html\" rel=\"nofollow noreferrer\">http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html</a></p>\n" }, { "answer_id": 84005, "author": "Andrei Dziahel", "author_id": 15961, "author_profile": "https://Stackoverflow.com/users/15961", "pm_score": 0, "selected": false, "text": "<p>No. Wait for PHP 5.3.</p>\n" }, { "answer_id": 109888, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Class identification is often a symptom of not well understood Polymorphism.</p>\n\n<p>The clients of ChildClass1 and ChildClass2 shouldn't need to distinguish between them. </p>\n\n<p>There's no place where any class should ask about <code>someObject.whoAmI()</code>.</p>\n\n<p>Whenever you have the urge to write <code>if someObject.whoAmI() == 'ChildClass1' { do X(someObject) }</code> you should really add an <code>X()</code> method to the ParentClass with various implementations in the various ChildClasses.</p>\n\n<p>This kind of \"run-time type identification\" can almost always be replaced with properly polymorphic class designs.</p>\n" }, { "answer_id": 278079, "author": "Ben Dowling", "author_id": 36191, "author_profile": "https://Stackoverflow.com/users/36191", "pm_score": 1, "selected": false, "text": "<p>As of PHP 5.3 it'll be possible with the use of the <a href=\"http://php.net/manual/en/language.oop5.static.php\" rel=\"nofollow noreferrer\">static keyword</a>, but for now it isn't possible.</p>\n" }, { "answer_id": 1384848, "author": "Adam Franco", "author_id": 15872, "author_profile": "https://Stackoverflow.com/users/15872", "pm_score": 3, "selected": true, "text": "<p>Now that PHP 5.3 is widely available in the wild, I wanted to put together a summary answer to this question to reflect newly available techniques. </p>\n\n<p>As mentioned in the other answers, PHP 5.3 has introduced <a href=\"http://php.benscom.com/manual/en/language.oop5.late-static-bindings.php\" rel=\"nofollow noreferrer\">Late Static Binding</a> via a new <a href=\"http://php.benscom.com/manual/en/language.oop5.static.php\" rel=\"nofollow noreferrer\"><code>static</code></a> keyword. As well, a new <a href=\"http://php.benscom.com/manual/en/function.get-called-class.php\" rel=\"nofollow noreferrer\"><code>get_called_class()</code></a> function is also available that can only be used within a class method (instance or static). </p>\n\n<p>For the purpose of determining the class as was asked in this question, the <code>get_called_class()</code> function is appropriate:</p>\n\n<pre><code>&lt;?php\n\nabstract class ParentClass {\n\n public static function whoAmI () {\n return get_called_class();\n }\n\n}\n\nclass ChildClass1 extends ParentClass {\n\n}\n\nclass ChildClass2 extends ParentClass {\n\n}\n\n// Shows 'ChildClass1'\nprint ChildClass1::whoAmI(); \nprint \"\\n\";\n\n// Shows 'ChildClass2'\nprint ChildClass2::whoAmI();\nprint \"\\n\";\n</code></pre>\n\n<p>The <a href=\"http://php.benscom.com/manual/en/function.get-called-class.php\" rel=\"nofollow noreferrer\">user contributed notes for <code>get_called_class()</code></a> include a few sample implementations that should work in PHP 5.2 as well by making use of <code>debug_backtrace()</code>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15872/" ]
Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class. ``` <?php abstract class ParentClass { public static function whoAmI () { // NOT correct, always gives 'ParentClass' $class = __CLASS__; // NOT correct, always gives 'ParentClass'. // Also very round-about and likely slow. $trace = debug_backtrace(); $class = $trace[0]['class']; return $class; } } class ChildClass1 extends ParentClass { } class ChildClass2 extends ParentClass { } // Shows 'ParentClass' // Want to show 'ChildClass1' print ChildClass1::whoAmI(); print "\n"; // Shows 'ParentClass' // Want to show 'ChildClass2' print ChildClass2::whoAmI(); print "\n"; ```
Now that PHP 5.3 is widely available in the wild, I wanted to put together a summary answer to this question to reflect newly available techniques. As mentioned in the other answers, PHP 5.3 has introduced [Late Static Binding](http://php.benscom.com/manual/en/language.oop5.late-static-bindings.php) via a new [`static`](http://php.benscom.com/manual/en/language.oop5.static.php) keyword. As well, a new [`get_called_class()`](http://php.benscom.com/manual/en/function.get-called-class.php) function is also available that can only be used within a class method (instance or static). For the purpose of determining the class as was asked in this question, the `get_called_class()` function is appropriate: ``` <?php abstract class ParentClass { public static function whoAmI () { return get_called_class(); } } class ChildClass1 extends ParentClass { } class ChildClass2 extends ParentClass { } // Shows 'ChildClass1' print ChildClass1::whoAmI(); print "\n"; // Shows 'ChildClass2' print ChildClass2::whoAmI(); print "\n"; ``` The [user contributed notes for `get_called_class()`](http://php.benscom.com/manual/en/function.get-called-class.php) include a few sample implementations that should work in PHP 5.2 as well by making use of `debug_backtrace()`.
83,914
<p>I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution.</p> <p>I know I can use a cursor, but that seems inelegant.</p> <p>MS-SQL 2000,BTW</p>
[ { "answer_id": 83932, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>You might be able to adapt something <a href=\"http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/249/creating-random-sql-server-test-data.aspx\" rel=\"nofollow noreferrer\">like this</a> to load a test dataset of values, depending on what you are looking for</p>\n" }, { "answer_id": 83938, "author": "Jeremy Coenen", "author_id": 7798, "author_profile": "https://Stackoverflow.com/users/7798", "pm_score": 0, "selected": false, "text": "<p>If this is a one time thing just to get data into the system I really see no issue with using a cursor as much as I hate cursors they do have their place. </p>\n" }, { "answer_id": 83943, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>Additionally, if you are just doing this for testing or one time use I would say that an elegant solution is not really necessary.</p>\n" }, { "answer_id": 83963, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<pre><code>update MyTable Set RandomFld = CONVERT(varchar(10), NEWID())\n</code></pre>\n" }, { "answer_id": 83965, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 0, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>UPDATE TBL SET Field = LEFT( CONVERT(varchar(255), @myid),10)\n</code></pre>\n" }, { "answer_id": 83973, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Why not use the first 10 characters of an md5 checksum of the current timestamp and a random number?</p>\n" }, { "answer_id": 83978, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 0, "selected": false, "text": "<p>if you are in SQL Server you can use </p>\n\n<pre><code>CAST(RAND() as varchar(10))\n</code></pre>\n\n<p><strong>EDIT</strong>: This will only work inside an iteration. As part of a multi-row insert it will use the same RAND() result for each row.</p>\n" }, { "answer_id": 84029, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>Something like (untested code):</p>\n\n<pre><code>UPDATE yourtable\nSET yourfield= CHAR(32+ROUND(RAND()*95,0));\n</code></pre>\n\n<p>Obviously, concatenate more random characters if you want up to ten chars.\nIt's possible that the query optimizer might set all fields to the same value; in that case, I would try</p>\n\n<pre><code>SET yourfield=LEFT(yourfield,0)+CHAR…\n</code></pre>\n\n<p>to trick the optimizer into recalculating each time the expression.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4230/" ]
I've got a new varchar(10) field in a database with 1000+ records. I'd like to update the table so I can have random data in the field. I'm looking for a SQL solution. I know I can use a cursor, but that seems inelegant. MS-SQL 2000,BTW
``` update MyTable Set RandomFld = CONVERT(varchar(10), NEWID()) ```
83,918
<p>We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate?</p> <p>Thanks<BR> Tom</p>
[ { "answer_id": 83998, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You could programmatically configure log4j when you initialize the job.</p>\n\n<p>You can also set the log4j.properties file at runtime via a system property. From the <a href=\"http://logging.apache.org/log4j/1.2/manual\" rel=\"nofollow noreferrer\">manual</a>:</p>\n\n<blockquote>\n <p>Set the resource string variable to the value of the <em>log4j.configuration</em> system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value \"log4j.properties\".</p>\n</blockquote>\n\n<p>Assuming you're running the jobs from different java commands, this will enable them to use different log4j.properties files and different filenames for each one.</p>\n\n<p>Without specific knowledge of how your jobs are run it's difficult to say!</p>\n" }, { "answer_id": 84021, "author": "Alexandre Victoor", "author_id": 11897, "author_profile": "https://Stackoverflow.com/users/11897", "pm_score": 0, "selected": false, "text": "<p>Tom you coud specify and appenders for each job. Let's that you have 2 jobs corresponding to two different java packages com.tom.firstbatch and com.tom.secondbatch, you would have something like this in log4j.xml :</p>\n\n<pre><code> &lt;category name=\"com.tom.firstbatch\"&gt;\n &lt;appender-ref ref=\"FIRST_APPENDER\"/&gt;\n &lt;/category&gt;\n &lt;category name=\"com.tom.secondtbatch\"&gt;\n &lt;appender-ref ref=\"SECOND_APPENDER\"/&gt;\n &lt;/category&gt;\n</code></pre>\n" }, { "answer_id": 84039, "author": "Asgeir S. Nilsen", "author_id": 16023, "author_profile": "https://Stackoverflow.com/users/16023", "pm_score": 2, "selected": false, "text": "<p>If the job names are known ahead of time, you could include the job name when you do the getLogger() call. You then can bind different appenders to different loggers, with separate file names (or other destinations).</p>\n\n<p>If you cannot know the job name ahead of time, you could configure the logger at runtime instead of using a configuration file:</p>\n\n<pre><code>FileAppender appender = new FileAppender();\nappender.setFileName(...);\nappender.setLayout(...);\nLogger logger = Logger.getLogger(\"com.company.job.\"+jobName);\nlogger.addAppender(appender);\n</code></pre>\n" }, { "answer_id": 84044, "author": "shadit", "author_id": 9925, "author_profile": "https://Stackoverflow.com/users/9925", "pm_score": 5, "selected": true, "text": "<p>Can you pass a Java system property for each job? If so, you can parameterize like this:</p>\n\n<pre><code>java -Dmy_var=somevalue my.job.Classname\n</code></pre>\n\n<p>And then in your log4j.properties:</p>\n\n<pre><code>log4j.appender.A.File=${my_var}/A.log\n</code></pre>\n\n<p>You could populate the Java system property with a value from the host's environment (for example) that would uniquely identify the instance of the job.</p>\n" }, { "answer_id": 84072, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "<p>You could write your own appender that makes up its own filename, perhaps using the [File.createTempFile](<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String))\" rel=\"nofollow noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String))</a> method. If the <code>FileAppender</code> class was written correctly, you should be able to extend it&mdash;or <code>RollingFileAppender</code>&mdash;and override the <code>getFile</code> method to return one that you choose based on whatever new properties you would like to add.</p>\n" }, { "answer_id": 84435, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 2, "selected": false, "text": "<p>You can have each job set NDC or MDC and then write an appender that varies the name based on the NDC or MDC value. Creating a new appender isn't too hard. There may also be a appender that will fit the bill in the log4j sandbox. Start looking in <a href=\"http://svn.apache.org/viewvc/logging/log4j/trunk/contribs/\" rel=\"nofollow noreferrer\">http://svn.apache.org/viewvc/logging/log4j/trunk/contribs/</a></p>\n" }, { "answer_id": 84575, "author": "pgras", "author_id": 12719, "author_profile": "https://Stackoverflow.com/users/12719", "pm_score": 0, "selected": false, "text": "<p>you may implement following:</p>\n\n<ul>\n<li>A ThreadLocal holder for the identity of your job.</li>\n<li>Extend FileAppender, your FileAppender has to keep a Map holding a QuietWriter for every job identity. In method subAppend, you get the identity of your job from the ThreadLocal, you look up (or create) the QuietWriter and write to it...</li>\n</ul>\n\n<p>I may send you some code by mail if you wish...</p>\n" }, { "answer_id": 84988, "author": "18Rabbit", "author_id": 12662, "author_profile": "https://Stackoverflow.com/users/12662", "pm_score": 2, "selected": false, "text": "<p>We have something similar implemented in our system. We store the specific loggers in a HashMap and initialize appenders for each of them as needed.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>public class JobLogger {\nprivate static Hashtable&lt;String, Logger&gt; m_loggers = new Hashtable&lt;String, Logger&gt;();\nprivate static String m_filename = \"...\"; // Root log directory\n\npublic static synchronized void logMessage(String jobName, String message)\n{\n Logger l = getJobLogger(jobName);\n l.info(message);\n}\n\npublic static synchronized void logException(String jobName, Exception e)\n{\n Logger l = getJobLogger(partner);\n l.info(e.getMessage(), e);\n}\n\nprivate static synchronized Logger getJobLogger(String jobName)\n{\n Logger logger = m_loggers.get(jobName);\n if (logger == null) {\n Layout layout = new PatternLayout(\"...\");\n logger = Logger.getLogger(jobName);\n m_loggers.put(jobName, logger);\n logger.setLevel(Level.INFO);\n try {\n File file = new File(m_filename);\n file.mkdirs();\n file = new File(m_filename + jobName + \".log\");\n FileAppender appender = new FileAppender(layout, file.getAbsolutePath(), false);\n logger.removeAllAppenders();\n logger.addAppender(appender);\n }\n catch (Exception e)\n { ... }\n }\n return logger;\n}\n}\n</code></pre>\n\n<p>Then to use this in your job you just have to use a one line entry like this:</p>\n\n<pre><code>JobLogger.logMessage(jobName, logMessage);\n</code></pre>\n\n<p>This will create one log file for each job name and drop it in its own file with that job name in whichever directory you specify.</p>\n\n<p>You can fiddle with other types of appenders and such, as written it will continue appending until the JVM is restarted which may not work if you run the same job on a server that is always up, but this gives the general idea of how it can work.</p>\n" }, { "answer_id": 12650365, "author": "Vishal Zanzrukia", "author_id": 1326692, "author_profile": "https://Stackoverflow.com/users/1326692", "pm_score": 0, "selected": false, "text": "<p>log4j.logger.com.foo.admin=,AdminFileAppender \nlog4j.logger.com.foo.report=,ReportFileAppender</p>\n\n<p>It's another way to do this task.. here com.foo.admin is the full package name</p>\n" }, { "answer_id": 13640828, "author": "runaros", "author_id": 4464, "author_profile": "https://Stackoverflow.com/users/4464", "pm_score": 1, "selected": false, "text": "<p>Building on <a href=\"https://stackoverflow.com/questions/83918/log4j-log-file-names/84044#84044\">shadit</a>'s answer. If each job can be identified by which class' main method was started you can use the system property <code>sun.java.command</code> that contais the full name of the class started. For instance like this:</p>\n\n<pre><code>log4j.appender.LOGFILE.File=${sun.java.command}.log\n</code></pre>\n\n<p>I use it together with a <a href=\"http://markmail.org/message/5on2bmatywehnbn7\" rel=\"nofollow noreferrer\">TimestampFileAppender</a> like this:</p>\n\n<pre><code>log4j.appender.LOGFILE=TimestampFileAppender\nlog4j.appender.LOGFILE.TimestampPattern=yyyy_MM_dd__HH_mm\nlog4j.appender.LOGFILE.File=${sun.java.command}_{timestamp}.log\n</code></pre>\n\n<p>This way when I'm developing in Eclipse I get a new log file for each new process that I run, identified by the classname of the class with the main method and the time it was started.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5659/" ]
We have several jobs that run concurrently that have to use the same config info for log4j. They are all dumping the logs into one file using the same appender. Is there a way to have each job dynamically name its log file so they stay seperate? Thanks Tom
Can you pass a Java system property for each job? If so, you can parameterize like this: ``` java -Dmy_var=somevalue my.job.Classname ``` And then in your log4j.properties: ``` log4j.appender.A.File=${my_var}/A.log ``` You could populate the Java system property with a value from the host's environment (for example) that would uniquely identify the instance of the job.
83,953
<pre><code>foreach ($_GET as $field =&gt; $label) { $datarray[]=$_GET[$field]; echo "$_GET[$field]"; echo "&lt;br&gt;"; } print_r($datarray); </code></pre> <hr> <p>This is the output I am getting. I see the data is there in datarray but when I <code>echo $_GET[$field]</code> </p> <p>I only get "Array"</p> <p>But <code>print_r($datarray)</code> prints all the data. Any idea how I pull those values?</p> <h2>OUTPUT</h2> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; Grade1 [1] =&gt; ln [2] =&gt; North America [3] =&gt; yuiyyu [4] =&gt; iuy [5] =&gt; uiyui [6] =&gt; yui [7] =&gt; uiy [8] =&gt; 0:0:5 ) ) </code></pre>
[ { "answer_id": 84040, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 0, "selected": false, "text": "<p>Use <code>&lt;pre&gt;</code> tags before <code>print_r</code>, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.</p>\n\n<p>I suggest further reading on <a href=\"http://www.php.net/manual/en/language.variables.external.php\" rel=\"nofollow noreferrer\"><code>$_GET</code></a> variable and <a href=\"http://www.php.net/types.array\" rel=\"nofollow noreferrer\">arrays</a>, for a better understanding of its values</p>\n" }, { "answer_id": 84066, "author": "Joshua", "author_id": 11981, "author_profile": "https://Stackoverflow.com/users/11981", "pm_score": -1, "selected": false, "text": "<p>Perhaps the GET variables are arrays themselves? i.e. <a href=\"http://site.com?var[]=1&amp;var[]=2\" rel=\"nofollow noreferrer\">http://site.com?var[]=1&amp;var[]=2</a></p>\n" }, { "answer_id": 84156, "author": "ksuralta", "author_id": 16139, "author_profile": "https://Stackoverflow.com/users/16139", "pm_score": 0, "selected": false, "text": "<p>calling echo on an array will always output \"Array\".\nprint_r (from the PHP manual) prints human-readable information about a variable.</p>\n" }, { "answer_id": 84204, "author": "smo", "author_id": 16080, "author_profile": "https://Stackoverflow.com/users/16080", "pm_score": -1, "selected": false, "text": "<p>It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.</p>\n" }, { "answer_id": 84208, "author": "jackbravo", "author_id": 9055, "author_profile": "https://Stackoverflow.com/users/9055", "pm_score": 1, "selected": false, "text": "<p>Use <code>var_export($_GET)</code> to more easily see what kind of array you are getting.</p>\n\n<p>From the output of your script I can see that you have multiple nested arrays. It seems to be something like:</p>\n\n<pre><code>$_GET = array( array( array(\"Grade1\", \"ln\", \"North America\", \"yuiyyu\", \"iuy\", \"uiyui\", \"yui\",\"uiy\",\"0:0:5\")))\n</code></pre>\n\n<p>so to get those variables out you need something like:</p>\n\n<pre><code>echo $_GET[0][0][0]; // =&gt; \"Grade1\"\n</code></pre>\n" }, { "answer_id": 84557, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 2, "selected": true, "text": "<p>EDIT: When I completed your test, here was the final URL:</p>\n\n<p><a href=\"http://hofstrateach.org/Roberto/process.php?keys=Grade1&amp;keys=Nathan&amp;keys=North%20America&amp;keys=5&amp;keys=3&amp;keys=no&amp;keys=foo&amp;keys=blat&amp;keys=0%3A0%3A24\" rel=\"nofollow noreferrer\">http://hofstrateach.org/Roberto/process.php?keys=Grade1&amp;keys=Nathan&amp;keys=North%20America&amp;keys=5&amp;keys=3&amp;keys=no&amp;keys=foo&amp;keys=blat&amp;keys=0%3A0%3A24</a></p>\n\n<p>This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:</p>\n\n<p><a href=\"http://hofstrateach.org/Roberto/process.php?grade=Grade1&amp;schoolname=Nathan&amp;region=North%20America&amp;answer[]=5&amp;answer[]=3&amp;answer[]=no&amp;answer[]=foo&amp;answer[]=blat&amp;time=0%3A0%3A24\" rel=\"nofollow noreferrer\">http://hofstrateach.org/Roberto/process.php?grade=Grade1&amp;schoolname=Nathan&amp;region=North%20America&amp;answer[]=5&amp;answer[]=3&amp;answer[]=no&amp;answer[]=foo&amp;answer[]=blat&amp;time=0%3A0%3A24</a></p>\n\n<p>This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.</p>\n\n<p>Bottom line: fix your Flash file.</p>\n" }, { "answer_id": 84703, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>foreach ($_GET as $field =&gt; $label)\n{\n $datarray[]=$_GET[$field];\n\n echo $_GET[$field]; // you don't really need quotes\n\n echo \"With quotes: {$_GET[$field]}\"; // but if you want to use them\n\n echo $field; // this is really the same thing as echo $_GET[$field], so\n\n if($label == $_GET[$field]) {\n echo \"Should always be true&lt;br&gt;\";\n }\n echo \"&lt;br&gt;\";\n}\nprint_r($datarray);\n</code></pre>\n" }, { "answer_id": 85833, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 0, "selected": false, "text": "<p>It's printing just \"Array\" because when you say</p>\n\n<pre><code> echo \"$_GET[$field]\";\n</code></pre>\n\n<p>PHP can't know that you mean <code>$_GET</code> element <code>$field</code>, it sees it as you wanting to print variable <code>$_GET</code>. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:</p>\n\n<pre><code>echo \"The foo element of get is: {$_GET['foo']}\";\n</code></pre>\n\n<p>The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is <code>$_GET</code> by itself.</p>\n\n<p>In your case though you don't need that, what you need is:</p>\n\n<pre><code>foreach ($_GET as $field =&gt; $label)\n{\n $datarray[] = $label;\n}\n</code></pre>\n\n<p>and if you want to print it, just do </p>\n\n<pre><code>echo $label; // or $_GET[$field], but that's kind of pointless.\n</code></pre>\n\n<p>The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from <code>$_GET</code> into another array anyway?</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` foreach ($_GET as $field => $label) { $datarray[]=$_GET[$field]; echo "$_GET[$field]"; echo "<br>"; } print_r($datarray); ``` --- This is the output I am getting. I see the data is there in datarray but when I `echo $_GET[$field]` I only get "Array" But `print_r($datarray)` prints all the data. Any idea how I pull those values? OUTPUT ------ ``` Array ( [0] => Array ( [0] => Grade1 [1] => ln [2] => North America [3] => yuiyyu [4] => iuy [5] => uiyui [6] => yui [7] => uiy [8] => 0:0:5 ) ) ```
EDIT: When I completed your test, here was the final URL: <http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24> This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like: <http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan&region=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24> This will create individual entries for most of the fields, and make $\_GET['answer'] be an array of the answers provided by the user. Bottom line: fix your Flash file.
83,962
<p>Test the following code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; main() { const char *yytext="0"; const float f=(float)atof(yytext); size_t t = *((size_t*)&amp;f); printf("t should be 0 but is %d\n", t); } </code></pre> <p>Compile it with:</p> <pre><code>gcc -O3 test.c </code></pre> <p>The GOOD output should be:</p> <pre><code>"t should be 0 but is 0" </code></pre> <p>But with my gcc 4.1.3, I have:</p> <pre><code>"t should be 0 but is -1209357172" </code></pre>
[ { "answer_id": 83997, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 5, "selected": true, "text": "<p>Use the compiler flag -fno-strict-aliasing.</p>\n\n<p>With strict aliasing enabled, as it is by default for at least -O3, in the line:</p>\n\n<pre><code>size_t t = *((size_t*)&amp;f);\n</code></pre>\n\n<p>the compiler assumes that the size_t* does NOT point to the same memory area as the float*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out).</p>\n\n<p>If I recall correctly, you can use an intermediate cast to char* to get around this. (compiler assumes char* can alias anything)</p>\n\n<p>In other words, try this (can't test it myself right now but I think it will work):</p>\n\n<pre><code>size_t t = *((size_t*)(char*)&amp;f);\n</code></pre>\n" }, { "answer_id": 84001, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Why would you think that t should be 0? </p>\n\n<p>Or, more accuractely phrased, \"Why would you think that the binary representation of a floating point zero would be the same as the binary representation of an integer zero?\"</p>\n" }, { "answer_id": 84020, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": -1, "selected": false, "text": "<p>-O3 is not deemed \"sane\", -O2 is generally the upper threshold except maybe for some multimedia apps. </p>\n\n<p>Some apps can't even go that far, and die if you go beyond -O1 . </p>\n\n<p>If you have a new enough GCC ( I'm on 4.3 here ), it may support this command </p>\n\n<pre><code> gcc -c -Q -O3 --help=optimizers &gt; /tmp/O3-opts\n</code></pre>\n\n<p>If you're careful, you'll possibly be able to go through that list and find the given singular optimization you're enabling which causes this bug. </p>\n\n<p>From <code>man gcc</code> :</p>\n\n<pre><code> The output is sensitive to the effects of previous command line options, so for example it is possible to find out which\n optimizations are enabled at -O2 by using:\n\n -O2 --help=optimizers\n\n Alternatively you can discover which binary optimizations are enabled by -O3 by using:\n\n gcc -c -Q -O3 --help=optimizers &gt; /tmp/O3-opts\n gcc -c -Q -O2 --help=optimizers &gt; /tmp/O2-opts\n diff /tmp/O2-opts /tmp/O3-opts | grep enabled\n</code></pre>\n" }, { "answer_id": 84024, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 3, "selected": false, "text": "<p>This is no longer allowed according to C99 rules on pointer aliasing. Pointers of two different types cannot point to the same location in memory. The exceptions to this rule are void and char pointers.</p>\n\n<p>So in your code where you are casting to a pointer of size_t, the compiler can choose to ignore this. If you want to get the float value as a size_t, just assign it and the float will be cast (truncated not rounded) as such:</p>\n\n<p>size_t size = (size_t)(f); // this works</p>\n\n<p>This is commonly reported as a bug, but in fact really is a feature that allows optimizers to work more efficiently. </p>\n\n<p>In gcc you can disable this with a compiler switch. I beleive -fno_strict_aliasing.</p>\n" }, { "answer_id": 84032, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 1, "selected": false, "text": "<p>This is bad C code. Your cast breaks C aliasing rules, and the optimiser is free do things that break this code. You will probably find that GCC has cheduled the size_t read before the floating-point write (to hide fp pipeline latency). </p>\n\n<p>You can set the -fno-strict-aliasing switch, or use a union or a reinterpret_cast to reinterpret the value in a standards-compliant way.</p>\n" }, { "answer_id": 84054, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 3, "selected": false, "text": "<p>It is bad C code :-)</p>\n\n<p>The problematic part is that you access one object of type float by casting it to an integer pointer and dereferencing it.</p>\n\n<p>This breaks the aliasing rule. The compiler is free to assume that pointers to different types such as float or int don't overlap in memory. You've done exactly that.</p>\n\n<p>What the compiler sees is that you calculate something, store it in the float f and never access it anymore. Most likely the compiler has removed part of the code and the assignment has never happend.</p>\n\n<p>The dereferencing via your size_t pointer will in this case return some uninitialized garbage from the stack.</p>\n\n<p>You can do two things to work-around this:</p>\n\n<ol>\n<li><p>use a union with a float and a size_t member and do the casting via type punning. Not nice but works.</p></li>\n<li><p>use memcopy to copy the contents of f into your size_t. The compiler is smart enough to detect and optimize this case.</p></li>\n</ol>\n" }, { "answer_id": 84078, "author": "nutario", "author_id": 5334, "author_profile": "https://Stackoverflow.com/users/5334", "pm_score": -1, "selected": false, "text": "<p>I tested your code with:\n\"i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465)\"</p>\n\n<p>and there was no Problem.\nOutput: </p>\n\n<pre><code>t should be 0 but is 0\n</code></pre>\n\n<p>So there isn't a bug in you code. That doesn't mean that it is good code.\nBut I would add the returntype of the main-function and the \"return 0;\" at the end of the function.</p>\n" }, { "answer_id": 84242, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>In the C99 standard, this is covered by the following rule in 6.5-7:</p>\n\n<blockquote>\n <p>An object shall have its stored value accessed only by an lvalue expression that has one of\n the following types:73)</p>\n \n <ul>\n <li><p>a type compatible with the effective type of the object,</p></li>\n <li><p>a qualified version of a type compatible with the effective type of the object,</p></li>\n <li><p>a type that is the signed or unsigned type corresponding to the effective type of the\n object,</p></li>\n <li><p>a type that is the signed or unsigned type corresponding to a qualified version of the\n effective type of the object,</p></li>\n <li><p>an aggregate or union type that includes one of the aforementioned types among its\n members (including, recursively, a member of a subaggregate or contained union), or</p></li>\n <li><p>a character type.</p></li>\n </ul>\n</blockquote>\n\n<p>The last item is why casting first to a (char*) works.</p>\n" }, { "answer_id": 720468, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 1, "selected": false, "text": "<p>Aside the pointer alignments, you're expecting that sizeof(size_t)==sizeof(float). I don't think it is (on 64-bit Linux size_t should be 64 bits but float 32 bits), meaning your code will read something uninitialized.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6605/" ]
Test the following code: ``` #include <stdio.h> #include <stdlib.h> main() { const char *yytext="0"; const float f=(float)atof(yytext); size_t t = *((size_t*)&f); printf("t should be 0 but is %d\n", t); } ``` Compile it with: ``` gcc -O3 test.c ``` The GOOD output should be: ``` "t should be 0 but is 0" ``` But with my gcc 4.1.3, I have: ``` "t should be 0 but is -1209357172" ```
Use the compiler flag -fno-strict-aliasing. With strict aliasing enabled, as it is by default for at least -O3, in the line: ``` size_t t = *((size_t*)&f); ``` the compiler assumes that the size\_t\* does NOT point to the same memory area as the float\*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out). If I recall correctly, you can use an intermediate cast to char\* to get around this. (compiler assumes char\* can alias anything) In other words, try this (can't test it myself right now but I think it will work): ``` size_t t = *((size_t*)(char*)&f); ```
83,983
<p>example:</p> <pre><code>a_list = [1, 2, 3] a_list.len() # doesn't work len(a_list) # works </code></pre> <p>Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object. Plus I keep trying the wrong solution since it appears as the logical one to me</p>
[ { "answer_id": 84016, "author": "Bill Barksdale", "author_id": 16113, "author_profile": "https://Stackoverflow.com/users/16113", "pm_score": 2, "selected": false, "text": "<p>Maybe you're looking for <code>__len__</code>. If that method exists, then len(a) calls it:</p>\n\n<pre><code>&gt;&gt;&gt; class Spam:\n... def __len__(self): return 3\n... \n&gt;&gt;&gt; s = Spam()\n&gt;&gt;&gt; len(s)\n3\n</code></pre>\n" }, { "answer_id": 84019, "author": "Nate", "author_id": 12779, "author_profile": "https://Stackoverflow.com/users/12779", "pm_score": 4, "selected": false, "text": "<p>It just isn't.</p>\n\n<p>You can, however, do:</p>\n\n<pre><code>&gt;&gt;&gt; [1,2,3].__len__()\n\n3\n</code></pre>\n\n<p>Adding a <code>__len__()</code> method to a class is what makes the <code>len()</code> magic work.</p>\n" }, { "answer_id": 84038, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>Well, there actually is a length method, it is just hidden:</p>\n\n<pre><code>&gt;&gt;&gt; a_list = [1, 2, 3]\n&gt;&gt;&gt; a_list.__len__()\n3\n</code></pre>\n\n<p>The len() built-in function appears to be simply a wrapper for a call to the hidden <strong>len</strong>() method of the object.</p>\n\n<p>Not sure why they made the decision to implement things this way though.</p>\n" }, { "answer_id": 84154, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 7, "selected": true, "text": "<p>Guido's explanation is <a href=\"http://mail.python.org/pipermail/python-3000/2006-November/004643.html\" rel=\"noreferrer\">here</a>:</p>\n<blockquote>\n<p>First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:</p>\n<p>(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation.</p>\n<p>(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.</p>\n<p>Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/</p>\n</blockquote>\n" }, { "answer_id": 84155, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "<p>The short answer: 1) backwards compatibility and 2) there's not enough of a difference for it to really matter. For a more detailed explanation, read on.</p>\n\n<p>The idiomatic Python approach to such operations is special methods which aren't intended to be called directly. For example, to make <code>x + y</code> work for your own class, you write a <code>__add__</code> method. To make sure that <code>int(spam)</code> properly converts your custom class, write a <code>__int__</code> method. To make sure that <code>len(foo)</code> does something sensible, write a <code>__len__</code> method.</p>\n\n<p>This is how things have always been with Python, and I think it makes a lot of sense for some things. In particular, this seems like a sensible way to implement operator overloading. As for the rest, different languages disagree; in Ruby you'd convert something to an integer by calling <code>spam.to_i</code> directly instead of saying <code>int(spam)</code>.</p>\n\n<p>You're right that Python is an extremely object-oriented language and that having to call an external function on an object to get its length seems odd. On the other hand, <code>len(silly_walks)</code> isn't any more onerous than <code>silly_walks.len()</code>, and Guido has said that he actually prefers it (<a href=\"http://mail.python.org/pipermail/python-3000/2006-November/004643.html\" rel=\"noreferrer\">http://mail.python.org/pipermail/python-3000/2006-November/004643.html</a>).</p>\n" }, { "answer_id": 84205, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 3, "selected": false, "text": "<p>This way fits in better with the rest of the language. The convention in python is that you add <code>__foo__</code> special methods to objects to make them have certain capabilities (rather than e.g. deriving from a specific base class). For example, an object is </p>\n\n<ul>\n<li>callable if it has a <code>__call__</code> method </li>\n<li>iterable if it has an <code>__iter__</code> method, </li>\n<li>supports access with [] if it has <code>__getitem__</code> and <code>__setitem__</code>. </li>\n<li>...</li>\n</ul>\n\n<p>One of these special methods is <code>__len__</code> which makes it have a length accessible with <code>len()</code>.</p>\n" }, { "answer_id": 84337, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 2, "selected": false, "text": "<p>there is some good info below on why certain things are functions and other are methods. It does indeed cause some inconsistencies in the language.</p>\n\n<p><a href=\"http://mail.python.org/pipermail/python-dev/2008-January/076612.html\" rel=\"nofollow noreferrer\">http://mail.python.org/pipermail/python-dev/2008-January/076612.html</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/83983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16070/" ]
example: ``` a_list = [1, 2, 3] a_list.len() # doesn't work len(a_list) # works ``` Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object. Plus I keep trying the wrong solution since it appears as the logical one to me
Guido's explanation is [here](http://mail.python.org/pipermail/python-3000/2006-November/004643.html): > > First of all, I chose len(x) over x.len() for HCI reasons (def \_\_len\_\_() came much later). There are two intertwined reasons actually, both HCI: > > > (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x\*(a+b) into x\*a + x\*b to the clumsiness of doing the same thing using a raw OO notation. > > > (b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method. > > > Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/ > > >
84,007
<p>Do you guys know how I can use the Curl command line to POST SOAP to test a web service?</p> <p>I have a file (soap.xml) which has all the soap message attached to it I just don't seem to be able to properly post it.</p> <p>Thanks!</p>
[ { "answer_id": 84046, "author": "lbz", "author_id": 11530, "author_profile": "https://Stackoverflow.com/users/11530", "pm_score": 6, "selected": true, "text": "<p>Posting a string:</p>\n\n<pre><code>curl -d \"String to post\" \"http://www.example.com/target\"\n</code></pre>\n\n<p>Posting the contents of a file:</p>\n\n<pre><code>curl -d @soap.xml \"http://www.example.com/target\"\n</code></pre>\n" }, { "answer_id": 2704484, "author": "oliland", "author_id": 281340, "author_profile": "https://Stackoverflow.com/users/281340", "pm_score": 2, "selected": false, "text": "<p>If you want a fluffier interface than the terminal, <a href=\"http://hurl.it/\" rel=\"nofollow noreferrer\">http://hurl.it/</a> is awesome.</p>\n" }, { "answer_id": 4574519, "author": "Kris C", "author_id": 42234, "author_profile": "https://Stackoverflow.com/users/42234", "pm_score": 5, "selected": false, "text": "<p>For a SOAP 1.2 Webservice, I normally use</p>\n\n<pre><code>curl --header \"content-type: application/soap+xml\" --data @filetopost.xml http://domain/path\n</code></pre>\n" }, { "answer_id": 9366090, "author": "Zibri", "author_id": 236062, "author_profile": "https://Stackoverflow.com/users/236062", "pm_score": 5, "selected": false, "text": "<p>Wrong. \nThat doesn't work for me.</p>\n\n<p>For me this one works:</p>\n\n<pre><code>curl \n-H 'SOAPACTION: \"urn:samsung.com:service:MainTVAgent2:1#CheckPIN\"' \n-X POST \n-H 'Content-type: text/xml' \n-d @/tmp/pinrequest.xml \n192.168.1.5:52235/MainTVServer2/control/MainTVAgent2\n</code></pre>\n" }, { "answer_id": 13475416, "author": "Ahmet Karakaya", "author_id": 1297641, "author_profile": "https://Stackoverflow.com/users/1297641", "pm_score": 3, "selected": false, "text": "<pre><code>curl -H \"Content-Type: text/xml; charset=utf-8\" \\\n-H \"SOAPAction:\" \\\n-d @soap.txt -X POST http://someurl\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13469/" ]
Do you guys know how I can use the Curl command line to POST SOAP to test a web service? I have a file (soap.xml) which has all the soap message attached to it I just don't seem to be able to properly post it. Thanks!
Posting a string: ``` curl -d "String to post" "http://www.example.com/target" ``` Posting the contents of a file: ``` curl -d @soap.xml "http://www.example.com/target" ```
84,064
<p>I'm trying to use <code>SQLBindParameter</code> to prepare my driver for input via <code>SQLPutData</code>. The field in the database is a <code>TEXT</code> field. My function is crafted based on MS's example here: <a href="http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx</a>.</p> <p>I've setup the environment, made the connection, and prepared my statement successfully but when I call <code>SQLBindParam</code> (using code below) it consistently fails reporting: <code>[Microsoft][SQL Native Client]Invalid precision value</code></p> <pre><code>int col_num = 1; SQLINTEGER length = very_long_string.length( ); retcode = SQLBindParameter( StatementHandle, col_num, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, NULL, NULL, (SQLPOINTER) col_num, NULL, &amp;length ); </code></pre> <p>The above relies on the driver in use returning "N" for the <code>SQL_NEED_LONG_DATA_LEN</code> information type in <code>SQLGetInfo</code>. My driver returns "Y". How do I bind so that I can use <code>SQLPutData</code>?</p>
[ { "answer_id": 85102, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": true, "text": "<p>you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col_num parameter. Also, you should pass a value for the ColumnSize or DecimalDigits parameters. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx</a></p>\n" }, { "answer_id": 89423, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": 2, "selected": false, "text": "<p>Though it doesn't look just like the documentation's example code, I found the following solution to work for what I'm trying to accomplish. Thanks gbjbaanb for making me retest my input combinations to SQLBindParameter.</p>\n\n<pre><code> SQLINTEGER length;\n RETCODE retcode = SQLBindParameter( StatementHandle,\n col_num, // position of the parameter in the query\n SQL_PARAM_INPUT,\n SQL_C_CHAR,\n SQL_VARCHAR,\n data_length, // size of our data\n NULL, // decimal precision: not used our data types\n &amp;my_string, // SQLParamData will return this value later to indicate what data it's looking for so let's pass in the address of our std::string\n data_length,\n &amp;length ); // it needs a length buffer\n\n // length in the following operation must still exist when SQLExecDirect or SQLExecute is called\n // in my code, I used a pointer on the heap for this.\n length = SQL_LEN_DATA_AT_EXEC( data_length ); \n</code></pre>\n\n<p>After a statement is executed, you can use SQLParamData to determine what data SQL wants you to send it as follows:</p>\n\n<pre><code> std::string* my_string;\n // set string pointer to value given to SQLBindParameter\n retcode = SQLParamData( StatementHandle, (SQLPOINTER*) &amp;my_string ); \n</code></pre>\n\n<p>Finally, use SQLPutData to send the contents of your string to SQL:</p>\n\n<pre><code> // send data in chunks until everything is sent\n SQLINTEGER len;\n for ( int i(0); i &lt; my_string-&gt;length( ); i += CHUNK_SIZE )\n {\n std::string substr = my_string-&gt;substr( i, CHUNK_SIZE );\n\n len = substr.length( );\n\n retcode = SQLPutData( StatementHandle, (SQLPOINTER) substr.c_str( ), len );\n }\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625/" ]
I'm trying to use `SQLBindParameter` to prepare my driver for input via `SQLPutData`. The field in the database is a `TEXT` field. My function is crafted based on MS's example here: <http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx>. I've setup the environment, made the connection, and prepared my statement successfully but when I call `SQLBindParam` (using code below) it consistently fails reporting: `[Microsoft][SQL Native Client]Invalid precision value` ``` int col_num = 1; SQLINTEGER length = very_long_string.length( ); retcode = SQLBindParameter( StatementHandle, col_num, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, NULL, NULL, (SQLPOINTER) col_num, NULL, &length ); ``` The above relies on the driver in use returning "N" for the `SQL_NEED_LONG_DATA_LEN` information type in `SQLGetInfo`. My driver returns "Y". How do I bind so that I can use `SQLPutData`?
you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col\_num parameter. Also, you should pass a value for the ColumnSize or DecimalDigits parameters. <http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx>
84,096
<p>ssh will look for its keys by default in the ~/.ssh folder. I want to force it to always look in another location.</p> <p>The workaround I'm using is to add the keys from the non-standard location to the agent:</p> <pre><code>ssh-agent ssh-add /path/to/where/keys/really/are/id_rsa </code></pre> <p>(on Linux and MingW32 shell on Windows)</p>
[ { "answer_id": 84212, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": 5, "selected": false, "text": "<p><code>man ssh</code> gives me this options would could be useful.</p>\n<blockquote>\n<p>-i identity_file\nSelects a file from which the identity (private key) for RSA or\nDSA authentication is read. The default is ~/.ssh/identity for\nprotocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro-\ntocol version 2. Identity files may also be specified on a per-\nhost basis in the configuration file. It is possible to have\nmultiple -i options (and multiple identities specified in config-\nuration files).</p>\n</blockquote>\n<p>So you could create an alias in your bash config with something like</p>\n<blockquote>\n<p>alias ssh=&quot;ssh -i /path/to/private_key&quot;</p>\n</blockquote>\n<p>I haven't looked into a ssh configuration file, but like the <code>-i</code> option this too could be aliased</p>\n<blockquote>\n<p>-F configfile\nSpecifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.</p>\n</blockquote>\n" }, { "answer_id": 84419, "author": "Drew Frezell", "author_id": 10954, "author_profile": "https://Stackoverflow.com/users/10954", "pm_score": 8, "selected": true, "text": "<p>If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:</p>\n\n<pre><code>IdentityFile ~/.foo/identity\n</code></pre>\n\n<p><code>man ssh_config</code> to find other config options.</p>\n" }, { "answer_id": 70339236, "author": "Fabien Haddadi", "author_id": 4287943, "author_profile": "https://Stackoverflow.com/users/4287943", "pm_score": 0, "selected": false, "text": "<p>Update for <strong>Git Bash on Windows 10</strong>: on my system, git bash app will work over the ssh layer (brought by <strong>OpenSSH</strong>) look for an environment variable called <strong>HOME</strong> (To Windows key and type in &quot;env&quot; to edit env vars). If this variable points to a place that doesn't exist, git bash may never open.</p>\n<p>Like on Linux, <strong>Git Bash</strong> app will look for its <code>config</code> file in <code>%HOME%\\.ssh</code>.</p>\n<p>e.g. If you set HOME to <code>C:\\Users\\Yourname</code>, than it will look for <code>C:\\Users\\Yourname\\.ssh</code></p>\n<p>Finally, within config text file, git bash will look for <code>IdentifyFile</code> path.\nOn Windows, set the path using cygwin notation.</p>\n<p>e.g. to <code>/e/var/www/certs/keys/your_passwordless_key.key</code></p>\n<p>Bonus: for free, PHPStorm will use that setup. Restart IDE if you've just changed settings.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6329/" ]
ssh will look for its keys by default in the ~/.ssh folder. I want to force it to always look in another location. The workaround I'm using is to add the keys from the non-standard location to the agent: ``` ssh-agent ssh-add /path/to/where/keys/really/are/id_rsa ``` (on Linux and MingW32 shell on Windows)
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry: ``` IdentityFile ~/.foo/identity ``` `man ssh_config` to find other config options.
84,102
<p>I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.</p>
[ { "answer_id": 84140, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "<p>Idiomatic code is code that does a common task in the common way for your language. It's similar to a design pattern, but at a much smaller scale. Idioms differ widely by language. One idiom in C# might be to use an iterator to iterate through a collection rather than looping through it. Other languages without iterators might rely on the loop idiom.</p>\n" }, { "answer_id": 84270, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 8, "selected": true, "text": "<p>Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.</p>\n\n<p>non-idiomatic python using a loop with append:</p>\n\n<pre><code>mylist = [1, 2, 3, 4]\nnewlist = []\nfor i in mylist:\n newlist.append(i * 2)\n</code></pre>\n\n<p>idiomatic python using a list comprehension:</p>\n\n<pre><code>mylist = [1, 2, 3, 4]\nnewlist = [(i * 2) for i in mylist] \n</code></pre>\n" }, { "answer_id": 84406, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 5, "selected": false, "text": "<p>Some examples:</p>\n\n<p><strong>Resource management</strong>, non idiomatic:</p>\n\n<pre><code>string content;\nStreamReader sr = null;\ntry {\n File.OpenText(path);\n content = sr.ReadToEnd();\n}\nfinally {\n if (sr != null) {\n sr.Close();\n }\n}\n</code></pre>\n\n<p>Idiomatic:</p>\n\n<pre><code>string content;\nusing (StreamReader sr = File.OpenText(path)) {\n content = sr.ReadToEnd();\n}\n</code></pre>\n\n<p><strong>Iteration</strong>, non idiomatic:</p>\n\n<pre><code>for (int i=0;i&lt;list.Count; i++) {\n DoSomething(list[i]);\n}\n</code></pre>\n\n<p>Also non-idiomatic:</p>\n\n<pre><code>IEnumerator e = list.GetEnumerator();\ndo {\n DoSomenthing(e.Current);\n} while (e.MoveNext());\n</code></pre>\n\n<p>Idiomatic:</p>\n\n<pre><code>foreach (Item item in list) {\n DoSomething(item);\n}\n</code></pre>\n\n<p><strong>Filtering</strong>, non-idiomatic:</p>\n\n<pre><code>List&lt;int&gt; list2 = new List&lt;int&gt;();\nfor (int num in list1) {\n if (num&gt;100) list2.Add(num);\n}\n</code></pre>\n\n<p>idiomatic:</p>\n\n<pre><code>var list2 = list1.Where(num=&gt;num&gt;100);\n</code></pre>\n" }, { "answer_id": 84768, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": 3, "selected": false, "text": "<p>Practically speaking, it means writing code in a consistent way, i.e. all developers who work on your code base should follow the same conventions when writing similar code constructs.</p>\n\n<p>So the idiomatic way is the way that matches the style of the other code, non-idiomatic way means you are writing the kind of function but in a different way.</p>\n\n<p>e.g. if you are looping a certain number of items, you could write the loop in several ways:</p>\n\n<pre><code>for (int i = 0; i &lt; itemCount; i++)\n\nfor (int i = 1; i &lt;= itemCount; i++)\n\nfor (int i = 0; i &lt; itemCount; ++i)\n</code></pre>\n\n<p>etc</p>\n\n<p>What is most important is that the chosen style is used consistently. That way people become very familiar and confident with how to use it, and when you spy a usage which looks different it can be a sign of a mistake being introduced, perhaps an off by one error, e.g.</p>\n\n<pre><code>for (int i = 1; i &lt; itemCount; i++)\n</code></pre>\n" }, { "answer_id": 2553355, "author": "jmoz", "author_id": 68534, "author_profile": "https://Stackoverflow.com/users/68534", "pm_score": 3, "selected": false, "text": "<p>In PHP I sometimes encounter code like:</p>\n\n<pre><code>foreach ($array as $value) {\n $trimmed[] = trim($value);\n}\nreturn $trimmed;\n</code></pre>\n\n<p>Which idiomatically can be implemented with:</p>\n\n<pre><code>return array_map('trim', $array);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13578/" ]
I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.
Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language. non-idiomatic python using a loop with append: ``` mylist = [1, 2, 3, 4] newlist = [] for i in mylist: newlist.append(i * 2) ``` idiomatic python using a list comprehension: ``` mylist = [1, 2, 3, 4] newlist = [(i * 2) for i in mylist] ```
84,149
<p>What is a good way to render data produced by a Java process in the browser? </p> <p>I've made extensive use of JSP and the various associated frameworks (<a href="http://java.sun.com/products/jsp/jstl/" rel="nofollow noreferrer">JSTL</a>, <a href="http://struts.apache.org/" rel="nofollow noreferrer">Struts</a>, <a href="http://tapestry.apache.org/" rel="nofollow noreferrer">Tapestry</a>, etc), as well as more comprehensive frameworks not related to JSP (<a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">GWT</a>, <a href="http://www.openlaszlo.org/" rel="nofollow noreferrer">OpenLaszlo</a>). None of the solutions have ever been entirely satisfactory - in most cases the framework is too constrained or too complex for my needs, while others would require extensive refactoring of existing code. Additionally, most frameworks seem to have performance problems.</p> <p>Currently I'm leaning towards the solution of exposing my java data via a simple servlet that returns JSON, and then rendering the data using PHP or Ruby. This has the added benefit of instantly exposing my service as a web service as well, but I'm wondering if I'm reinventing the wheel here.</p>
[ { "answer_id": 84203, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Perhaps you could generate the data as XML and render it using XSLT?</p>\n\n<p>I'm not sure PHP or Ruby are the answer if Java isn't fast enough for you!</p>\n" }, { "answer_id": 84206, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 1, "selected": false, "text": "<p>We're using <a href=\"http://www.stripesframework.org/\" rel=\"nofollow noreferrer\">Stripes</a>. It gives you more structure than straight servlets, but it lets you control your urls through a @UrlBinding annotation. We use it to stream xml and json back to the browser for ajax stuff. </p>\n\n<p>You could easily consume it with another technology if you wanted to go that route, but you may actually enjoy developing with stripes.</p>\n" }, { "answer_id": 84207, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 1, "selected": false, "text": "<p>Check out <a href=\"http://restlet.org\" rel=\"nofollow noreferrer\">Restlet</a> for a good framework for exposing your domain model as REST services (including JSON and trivial XML output). </p>\n\n<p>For rendering your info, maybe you can use GWT on the client side and consume your data services? If GWT doesn't float your boat, then maybe JQuery would?</p>\n" }, { "answer_id": 87111, "author": "Andreas Holstenson", "author_id": 16351, "author_profile": "https://Stackoverflow.com/users/16351", "pm_score": 3, "selected": true, "text": "<p>I personally use <a href=\"http://tapestry.apache.org/tapestry5/\" rel=\"nofollow noreferrer\">Tapestry 5</a> for creating webpages with Java, but I agree that it can sometimes be a bit overkill. I would look into using JAX-RS (<a href=\"https://jsr311.dev.java.net/\" rel=\"nofollow noreferrer\">java.net project</a>, <a href=\"http://jcp.org/en/jsr/detail?id=311\" rel=\"nofollow noreferrer\">jsr311</a>) it is pretty simple to use, it supports marshalling and unmarshalling objects to/from XML out of the box. It is possible to extend it to support JSON via <a href=\"http://jettison.codehaus.org/\" rel=\"nofollow noreferrer\">Jettison</a>.</p>\n\n<p>There are two implementations that I have tried:</p>\n\n<ul>\n<li><a href=\"http://jersey.java.net/\" rel=\"nofollow noreferrer\">Jersey</a> - the reference implementation for JAX-RS.</li>\n<li><a href=\"http://www.jboss.org/resteasy/\" rel=\"nofollow noreferrer\">Resteasy</a> - the implementation I prefer, good support for marshalling and unmarshalling a wide-range of formats. Also pretty stable and has more features that Jersey.</li>\n</ul>\n\n<p>Take a look at the following code to get a feeling for what JAX-RS can do for you:</p>\n\n<pre><code>@Path(\"/\")\nclass TestClass {\n @GET\n @Path(\"text\")\n @Produces(\"text/plain\")\n String getText() {\n return \"String value\";\n }\n}\n</code></pre>\n\n<p>This tiny class will expose itself at the root of the server (@Path on the class), then expose the getText() method at the URI /text and allow access to it via HTTP GET. The @Produces annotation tells the JAX-RS framework to attempt to turn the result of the method into plain text.</p>\n\n<p>The easiest way to learn about what is possible with JAX-RS is to read the <a href=\"http://jcp.org/en/jsr/detail?id=311\" rel=\"nofollow noreferrer\">specification</a>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12457/" ]
What is a good way to render data produced by a Java process in the browser? I've made extensive use of JSP and the various associated frameworks ([JSTL](http://java.sun.com/products/jsp/jstl/), [Struts](http://struts.apache.org/), [Tapestry](http://tapestry.apache.org/), etc), as well as more comprehensive frameworks not related to JSP ([GWT](http://code.google.com/webtoolkit/), [OpenLaszlo](http://www.openlaszlo.org/)). None of the solutions have ever been entirely satisfactory - in most cases the framework is too constrained or too complex for my needs, while others would require extensive refactoring of existing code. Additionally, most frameworks seem to have performance problems. Currently I'm leaning towards the solution of exposing my java data via a simple servlet that returns JSON, and then rendering the data using PHP or Ruby. This has the added benefit of instantly exposing my service as a web service as well, but I'm wondering if I'm reinventing the wheel here.
I personally use [Tapestry 5](http://tapestry.apache.org/tapestry5/) for creating webpages with Java, but I agree that it can sometimes be a bit overkill. I would look into using JAX-RS ([java.net project](https://jsr311.dev.java.net/), [jsr311](http://jcp.org/en/jsr/detail?id=311)) it is pretty simple to use, it supports marshalling and unmarshalling objects to/from XML out of the box. It is possible to extend it to support JSON via [Jettison](http://jettison.codehaus.org/). There are two implementations that I have tried: * [Jersey](http://jersey.java.net/) - the reference implementation for JAX-RS. * [Resteasy](http://www.jboss.org/resteasy/) - the implementation I prefer, good support for marshalling and unmarshalling a wide-range of formats. Also pretty stable and has more features that Jersey. Take a look at the following code to get a feeling for what JAX-RS can do for you: ``` @Path("/") class TestClass { @GET @Path("text") @Produces("text/plain") String getText() { return "String value"; } } ``` This tiny class will expose itself at the root of the server (@Path on the class), then expose the getText() method at the URI /text and allow access to it via HTTP GET. The @Produces annotation tells the JAX-RS framework to attempt to turn the result of the method into plain text. The easiest way to learn about what is possible with JAX-RS is to read the [specification](http://jcp.org/en/jsr/detail?id=311).
84,163
<p>Here's a challenge that I was tasked with recently. I still haven't figured out the best way to do it, maybe someone else has an idea. </p> <p>Using PHP and/or HTML, create a page that cycles through any number of other pages at a given interval.</p> <p>For instance, we would load this page and it would take us to google for 20 seconds, then on to yahoo for 10 seconds, then on to stackoverflow for 180 seconds and so on an so forth. </p>
[ { "answer_id": 84190, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<p>Use a separate iframe for the content, then use Javascript to <code>delay()</code> a period of time and set the iframe's <code>location</code> property.</p>\n" }, { "answer_id": 84200, "author": "Ben", "author_id": 11522, "author_profile": "https://Stackoverflow.com/users/11522", "pm_score": 1, "selected": false, "text": "<p>When you are taken to another site (e.g. Google) control passes to that site, so in order for your script to keep running, you'd need to load the new site in a frame, and keep your script (which I'd imagine could most readily be implemented using Javascript) in another frame (which could be made very small so you can't see it).</p>\n" }, { "answer_id": 84217, "author": "shadit", "author_id": 9925, "author_profile": "https://Stackoverflow.com/users/9925", "pm_score": 0, "selected": false, "text": "<p>You could do this with JavaScript quite easily. It would help to know the deployment environment. Is it a kiosk or something?</p>\n\n<p>For the JavaScript solution, serve up a page that contains a JavaScript that will pop open a new browser window. The controller page will then cause the new browser window to cycle through a series of pages. That's about the simplest way to do this that I can think of.</p>\n\n<p><strong>Edit:</strong> Agree with Simon's comment. This solution would work best in a kiosk or large, public display environment where the pages are just being shown without any user interaction.</p>\n" }, { "answer_id": 84219, "author": "Simon Collins", "author_id": 12412, "author_profile": "https://Stackoverflow.com/users/12412", "pm_score": 0, "selected": false, "text": "<p>Depends on your exact requirements. If you allow JavaScript and allow frames then you can stick a hidden frame within a frameset on your page into which you load some JavaScript. This JavaScript will then control the content of the main frame using the window.location object and setTimeout function.</p>\n\n<p>The downside would be that the user's address bar would not update with the new URL. I'm not sure how this would achievable otherwise. If you can clarify the constraints I can provide more help.</p>\n\n<p><strong>Edit</strong> - Shad's suggestion is a possibility although unless the user triggers the action the browser may block the popup. Again you'd have to clarify whether a popup is allowable.</p>\n" }, { "answer_id": 84226, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 0, "selected": false, "text": "<p>Create a wrapper HTML page with an IFrame in it, sized at <code>100% x 100%</code>. Then add in some javascript that changes the <code>src</code> of the IFrame between set intervals.</p>\n" }, { "answer_id": 84235, "author": "Max Cantor", "author_id": 16034, "author_profile": "https://Stackoverflow.com/users/16034", "pm_score": 0, "selected": false, "text": "<p>I think it would have to work like <a href=\"http://gabbly.com\" rel=\"nofollow noreferrer\">gabbly.com</a>, which sucks in other websites and displays them with its own content over it.</p>\n\n<p>Once you read the other site in and were ready to display it, you couldn't really do it \"in PHP\"; you would have to send an HTML redirect meta-tag:</p>\n\n<pre><code>&lt;meta HTTP-EQUIV=\"REFRESH\" content=\"15; url=http://www.thepagecycler.com/nextpage.html\"&gt;\n</code></pre>\n\n<p>Or you could use Javascript instead of the meta-tag.</p>\n" }, { "answer_id": 84241, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is not doable in a PHP script, unless you want to edit the redirect.... PHP is a back end technology; you're going to need to do this in Javascript or the like.</p>\n\n<p>The best you're going to do, as far as I know, is to create a text file on your web server and load a different HTTP address based on time out of that text file, then redirect the browser to the site found in that text file.</p>\n" }, { "answer_id": 84259, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 0, "selected": false, "text": "<p>The first solution that jumps to mind is to do this in a frameset. Hide one of the frames, and the other display the pages in question. Drive the page transitions with Javascript from the hidden frame.</p>\n\n<pre><code>function RefreshFrame()\n{\n parent.VisibleFrame.location.href = urlArray[i];\n i++;\n\n if(i &lt; urlArray.length) SetTimeout(\"RefreshFrame()\", 20000);\n}\n\nvar i = 0;\nvar urlArray = ['http://google.com','http://yahoo.com', 'http://www.search.com'];\nRefreshFrame();\n</code></pre>\n\n<p>In this example the Javascript would be in the hiddend frame, and you would name your visible frame \"VisibleFrame\".</p>\n\n<p>Disclaimer: I just wrote this code in the comment window and have not tested it</p>\n" }, { "answer_id": 84432, "author": "GreenO", "author_id": 13399, "author_profile": "https://Stackoverflow.com/users/13399", "pm_score": 0, "selected": false, "text": "<p>The theory behind the request is basically the ability to cycle through web page dashboards for various systems from a \"kiosk\" PC. I oversee a data center and we have several monitor systems that allow me view dashboards for temps, system up time, etc etc.\nThe idea is load a page that would cycle from dashboard to dashboard remaining on each for an amount of time specified by me, 1 minute on this board, 30 seconds on the next board, 2 minutes on the next and so on.. Javascript is absolutely allowable (though I have little experience with it). My mediums of choice are PHP/HTML and I'm not seeing a way to make this happen cleanly with just them..</p>\n" }, { "answer_id": 85196, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n&lt;title&gt;Dashboard Example&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\nbody, html { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }\niframe { border: none; }\n&lt;/style&gt;\n&lt;script type=\"text/javascript\"&gt;\nvar Dash = {\n nextIndex: 0,\n\n dashboards: [\n {url: \"http://www.google.com\", time: 5},\n {url: \"http://www.yahoo.com\", time: 10},\n {url: \"http://www.stackoverflow.com\", time: 15}\n ],\n\n display: function()\n {\n var dashboard = Dash.dashboards[Dash.nextIndex];\n frames[\"displayArea\"].location.href = dashboard.url;\n Dash.nextIndex = (Dash.nextIndex + 1) % Dash.dashboards.length;\n setTimeout(Dash.display, dashboard.time * 1000);\n }\n};\n\nwindow.onload = Dash.display;\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;iframe name=\"displayArea\" width=\"100%\" height=\"100%\"&gt;&lt;/iframe&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 85818, "author": "GreenO", "author_id": 13399, "author_profile": "https://Stackoverflow.com/users/13399", "pm_score": 1, "selected": false, "text": "<p>I managed to create this thing. It's not pretty but it does work.</p>\n\n<pre><code>&lt;?php\n# Path the config file, full or relative.\n$configfile=\"config.conf\"; \n$tempfile=\"tmp.html\";\n# Read the file into an array\n$farray=file($configfile); \n# Count array elements\n$count=count($farray); \nif(!isset($_GET['s'])){\n $s=0;\n}else{ \n $s=$_GET['s'];\nif($s==($count-1)){ # -1 because of the offset in starting our loop at 0 instead of 1\n $s=0;\n}else{\n $s=$_GET['s']+1; # Increment the counter\n}\n}\n# Get the line from the array\n$entry=$farray[$s];\n# Break the line on the comma into 2 entries\n$arr=explode(\",\",$entry); \n# Now each line is in 2 pieces - URL and TimeDelay\n$url=strtolower($arr[0]);\n# Check our url to see if it has an HTTP prepended, if it doesn't, give it one.\n$check=strstr($url,\"http://\"); \nif($check==FALSE){\n $url=\"http://\".$url;\n } \n# Trim unwanted crap from the time\n$time=rtrim($arr[1]); \n# Get a handle to the temp file\n$tmphandle=fopen($tempfile,\"w\");\n# What does our meta refresh look like?\n$meta=\"&lt;meta http-equiv=\\\"refresh\\\" content=\\\"\".$time.\";url=index.php?s=\".$s.\"\\\"&gt;\\n\";\n# The iframe to display\n$content=\"&lt;iframe src =\\\"\".$url.\"\\\" height=\\\"100%\\\" width=\\\"100%\\\"&gt;&lt;/iframe&gt;\";\n# roll up the meta and content to be written\n$str=$meta.$content;\n# Write it\nfwrite($tmphandle,$str);\n# Close the handle\nfclose($tmphandle);\n# Load the page\ndie(header(\"Location:tmp.html\")); \n?&gt;\n</code></pre>\n\n<p>Config files looks like (URL, Time to stay on that page):\ngoogle.com,5\n<a href=\"http://yahoo.com,10\" rel=\"nofollow noreferrer\">http://yahoo.com,10</a></p>\n" }, { "answer_id": 21739582, "author": "Cheyne", "author_id": 573616, "author_profile": "https://Stackoverflow.com/users/573616", "pm_score": -1, "selected": false, "text": "<p>There's a bunch of ways you can do this, iv written several scripts and tools with everything from JS to Ruby </p>\n\n<p>In the end It was much easier to use <a href=\"http://dashboardrotator.com\" rel=\"nofollow\">http://dashboardrotator.com</a> . It handled browser restarts, memory allocation and accidental window closure for me with a nice simple GUI.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13399/" ]
Here's a challenge that I was tasked with recently. I still haven't figured out the best way to do it, maybe someone else has an idea. Using PHP and/or HTML, create a page that cycles through any number of other pages at a given interval. For instance, we would load this page and it would take us to google for 20 seconds, then on to yahoo for 10 seconds, then on to stackoverflow for 180 seconds and so on an so forth.
``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Dashboard Example</title> <style type="text/css"> body, html { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; } iframe { border: none; } </style> <script type="text/javascript"> var Dash = { nextIndex: 0, dashboards: [ {url: "http://www.google.com", time: 5}, {url: "http://www.yahoo.com", time: 10}, {url: "http://www.stackoverflow.com", time: 15} ], display: function() { var dashboard = Dash.dashboards[Dash.nextIndex]; frames["displayArea"].location.href = dashboard.url; Dash.nextIndex = (Dash.nextIndex + 1) % Dash.dashboards.length; setTimeout(Dash.display, dashboard.time * 1000); } }; window.onload = Dash.display; </script> </head> <body> <iframe name="displayArea" width="100%" height="100%"></iframe> </body> </html> ```
84,174
<p>I have been trying out <a href="http://www.codeplex.com/servicefactory" rel="nofollow noreferrer">Service Factory</a> and have run into some problems in regards to long filenames - surpassing the limit in Vista/XP. The problem is that when generating code from the models service factory prefixes everything with the namespace specified. Making the folder structure huge. For example starting in</p> <p>c:\work\sftest\MyWebService</p> <p>I create each of the models with moderate length of names in data contracts and service interface. I set the namespace to be MyCompany.SFTest.MyWebservice</p> <p>After generating code I end up with </p> <pre> c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Business Logic c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Resource Access c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.DataContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.FaultContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.MessageContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Tests </pre> <p>Under each of the folders is a project file with the same prefix </p> <pre> c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation\MyCompany.SFTest.MyWebService.ServiceImplementation.proj </pre> <p>This blows up the recipe as windows can't accept filenames exceeding a specific length.</p> <p>Is it necessary to explicitly include the namespace in each of the foldernames? Obviously at some point I might want to branch a service to another location but for the same reason as above might be unable to. Is there a workaround for this?</p>
[ { "answer_id": 84250, "author": "Loofer", "author_id": 5552, "author_profile": "https://Stackoverflow.com/users/5552", "pm_score": 2, "selected": false, "text": "<p>I have always been in the fortunate position to have Red Gate <a href=\"http://www.red-gate.com/products/SQL_Compare/index.htm\" rel=\"nofollow noreferrer\">Schema compare</a> which i think would do what you ask. Cheap at twice the price!</p>\n" }, { "answer_id": 84469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I do this by querying the system tables directly. Look into the <code>syscolumns</code> and <code>sysobjects</code> tables. You can also join across linked servers too</p>\n\n<pre><code>select t1.name as tname,c1.name as cname\nfrom adventureworks.dbo.syscolumns c1\njoin adventureworks.dbo.sysobjects t1 on c1.id = t1.id \nwhere t1.type = 'U' \norder by t1.name,c1.colorder\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15771/" ]
I have been trying out [Service Factory](http://www.codeplex.com/servicefactory) and have run into some problems in regards to long filenames - surpassing the limit in Vista/XP. The problem is that when generating code from the models service factory prefixes everything with the namespace specified. Making the folder structure huge. For example starting in c:\work\sftest\MyWebService I create each of the models with moderate length of names in data contracts and service interface. I set the namespace to be MyCompany.SFTest.MyWebservice After generating code I end up with ``` c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Business Logic c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Resource Access c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.DataContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.FaultContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.MessageContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceContracts c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Tests ``` Under each of the folders is a project file with the same prefix ``` c:\work\sftest\MyWebService\MyCompany.SFTest.MyWebService\Source\Service Interface\MyCompany.SFTest.MyWebService.ServiceImplementation\MyCompany.SFTest.MyWebService.ServiceImplementation.proj ``` This blows up the recipe as windows can't accept filenames exceeding a specific length. Is it necessary to explicitly include the namespace in each of the foldernames? Obviously at some point I might want to branch a service to another location but for the same reason as above might be unable to. Is there a workaround for this?
I have always been in the fortunate position to have Red Gate [Schema compare](http://www.red-gate.com/products/SQL_Compare/index.htm) which i think would do what you ask. Cheap at twice the price!
84,178
<p>I'm running in a windows environment with Trac / SVN and I want commits to the repository to integrate to Trac and close the bugs that were noted in the SVN Comment.</p> <p>I know there's some post commit hooks to do that, but there's not much information about how to do it on windows.</p> <p>Anyone done it successfully? And what were the steps you followed to achive it?</p> <p>Here's the hook I need to put in place in SVN, but I'm not exactly sure how to do this in the Windows environment.</p> <p><a href="http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920" rel="nofollow noreferrer">Trac Post Commit Hook</a></p>
[ { "answer_id": 84301, "author": "Benjamin W. Smith", "author_id": 1068060, "author_profile": "https://Stackoverflow.com/users/1068060", "pm_score": 0, "selected": false, "text": "<p>Post commit hooks live in the \"hooks\" directory where ever you have the repository living on the server side. I don't know where you have them in your environment, so this is just an example</p>\n\n<p>e.g. (windows):</p>\n\n<pre><code>C:\\Subversion\\repositories\\repo1\\hooks\\post-commit\n</code></pre>\n\n<p>e.g. (llinux/unix):</p>\n\n<pre><code>/usr/local/subversion/repositories/repo1/hooks/post-commit\n</code></pre>\n" }, { "answer_id": 85089, "author": "Craig Boland", "author_id": 16285, "author_profile": "https://Stackoverflow.com/users/16285", "pm_score": 2, "selected": false, "text": "<p>Benjamin's answer is close, but on Windows you need to give the hook script files an executable extension, such as .bat or .cmd. I use .cmd. You can take the template scripts, which are unix shell scripts, shell scripts and convert them to .bat/.cmd syntax.</p>\n\n<p>But to answer the question of integrating with Trac, follow these steps.</p>\n\n<ol>\n<li><p>Ensure that Python.exe is on the system path. This will make your life easier.</p></li>\n<li><p>Create post-commit.cmd in \\hooks folder. This is the actual hook script that Subversion will execute on the post-commit event.</p>\n\n<pre><code>@ECHO OFF\n\n:: POST-COMMIT HOOK\n::\n:: The post-commit hook is invoked after a commit. Subversion runs\n:: this hook by invoking a program (script, executable, binary, etc.)\n:: named 'post-commit' (for which this file is a template) with the \n:: following ordered arguments:\n::\n:: [1] REPOS-PATH (the path to this repository)\n:: [2] REV (the number of the revision just committed)\n::\n:: The default working directory for the invocation is undefined, so\n:: the program should set one explicitly if it cares.\n::\n:: Because the commit has already completed and cannot be undone,\n:: the exit code of the hook program is ignored. The hook program\n:: can use the 'svnlook' utility to help it examine the\n:: newly-committed tree.\n::\n:: On a Unix system, the normal procedure is to have 'post-commit'\n:: invoke other programs to do the real work, though it may do the\n:: work itself too.\n::\n:: Note that 'post-commit' must be executable by the user(s) who will\n:: invoke it (typically the user httpd runs as), and that user must\n:: have filesystem-level permission to access the repository.\n::\n:: On a Windows system, you should name the hook program\n:: 'post-commit.bat' or 'post-commit.exe',\n:: but the basic idea is the same.\n:: \n:: The hook program typically does not inherit the environment of\n:: its parent process. For example, a common problem is for the\n:: PATH environment variable to not be set to its usual value, so\n:: that subprograms fail to launch unless invoked via absolute path.\n:: If you're having unexpected problems with a hook program, the\n:: culprit may be unusual (or missing) environment variables.\n:: \n:: Here is an example hook script, for a Unix /bin/sh interpreter.\n:: For more examples and pre-written hooks, see those in\n:: the Subversion repository at\n:: http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/ and\n:: http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/\n\nsetlocal\n\n:: Debugging setup\n:: 1. Make a copy of this file.\n:: 2. Enable the command below to call the copied file.\n:: 3. Remove all other commands\n::call %~dp0post-commit-run.cmd %* &gt; %1/hooks/post-commit.log 2&gt;&amp;1\n\n:: Call Trac post-commit hook\ncall %~dp0trac-post-commit.cmd %* || exit 1\n\nendlocal\n</code></pre></li>\n<li><p>Create trac-post-commit.cmd in \\hooks folder:</p>\n\n<pre><code>@ECHO OFF\n::\n:: Trac post-commit-hook script for Windows\n::\n:: Contributed by markus, modified by cboos.\n\n:: Usage:\n::\n:: 1) Insert the following line in your post-commit.bat script\n::\n:: call %~dp0\\trac-post-commit-hook.cmd %1 %2\n::\n:: 2) Check the 'Modify paths' section below, be sure to set at least TRAC_ENV\n\nsetlocal\n\n:: ----------------------------------------------------------\n:: Modify paths here:\n\n:: -- this one *must* be set\nSET TRAC_ENV=D:\\projects\\trac\\membershipdnn\n\n:: -- set if Python is not in the system path\nSET PYTHON_PATH=\n\n:: -- set to the folder containing trac/ if installed in a non-standard location\nSET TRAC_PATH=\n:: ----------------------------------------------------------\n\n:: Do not execute hook if trac environment does not exist\nIF NOT EXIST %TRAC_ENV% GOTO :EOF\n\nset PATH=%PYTHON_PATH%;%PATH%\nset PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%\n\nSET REV=%2\n\n:: Resolve ticket references (fixes, closes, refs, etc.)\nPython \"%~dp0trac-post-commit-resolve-ticket-ref.py\" -p \"%TRAC_ENV%\" -r \"%REV%\"\n\nendlocal\n</code></pre></li>\n<li><p>Create trac-post-commit-resolve-ticket-ref.py in \\hooks folder. I used <a href=\"http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920\" rel=\"nofollow noreferrer\">the same script from EdgeWall</a>, only I renamed it to better clarify its purpose.</p></li>\n</ol>\n" }, { "answer_id": 110241, "author": "Dean Poulin", "author_id": 5462, "author_profile": "https://Stackoverflow.com/users/5462", "pm_score": 3, "selected": true, "text": "<p>Alright, now that I've got some time to post my experience after figuring this all out, and thanks to Craig for getting me on the right track. Here's what you need to do (at least with SVN v1.4 and Trac v0.10.3):</p>\n\n<ol>\n<li>Locate your SVN repository that you want to enable the Post Commit Hook for.</li>\n<li>inside the SVN repository there's a directory called hooks, this is where you'll be placing the post commit hook.</li>\n<li>create a file post-commit.bat (this is the batch file that's automatically called by SVN post commit).</li>\n<li>Place the following code inside the post-commit.bat file ( this will call your post commit cmd file passing in the parameters that SVN automatically passes %1 is the repository, %2 is the revision that was committed.</li>\n</ol>\n\n<p>%~dp0\\trac-post-commit-hook.cmd %1 %2</p>\n\n<ol start=\"5\">\n<li>Now create the trac-post-commit-hook.cmd file as follows:</li>\n</ol>\n\n<blockquote>\n <p>@ECHO OFF<br> ::<br> :: Trac\n post-commit-hook script for\n Windows<br> ::<br> :: Contributed by\n markus, modified by cboos.<br> <br> ::\n Usage:<br> ::<br> :: 1) Insert the\n following line in your post-commit.bat\n script<br> ::<br> :: call\n %~dp0\\trac-post-commit-hook.cmd %1\n %2<br> ::<br> :: 2) Check the 'Modify\n paths' section below, be sure to set\n at least TRAC_ENV<br> <br> <br> ::\n ----------------------------------------------------------<br> :: Modify paths here:<br> <br> :: --\n this one <em>must</em> be set<br> SET\n TRAC_ENV=C:\\trac\\MySpecialProject<br>\n <br> :: -- set if Python is not in the\n system path<br> :: SET\n PYTHON_PATH=<br> <br> :: -- set to the\n folder containing trac/ if installed\n in a non-standard location <br> :: SET\n TRAC_PATH=<br> ::\n ----------------------------------------------------------<br> <br> :: Do not execute hook if trac\n environment does not exist<br> IF NOT\n EXIST %TRAC_ENV% GOTO :EOF<br> <br>\n set PATH=%PYTHON_PATH%;%PATH%<br> set\n PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%<br>\n <br> SET REV=%2<br> <br> :: GET THE\n AUTHOR AND THE LOG MESSAGE<br> for /F\n %%A in ('svnlook author -r %REV% %1')\n do set AUTHOR=%%A<br> for /F\n \"delims==\" %%B in ('svnlook log -r\n %REV% %1') do set LOG=%%B<br> <br> ::\n CALL THE PYTHON SCRIPT<br> Python\n \"%~dp0\\trac-post-commit-hook\" -p\n \"%TRAC_ENV%\" -r \"%REV%\" -u \"%AUTHOR%\"\n -m \"%LOG%\"<br></p>\n</blockquote>\n\n<p>The most important parts here are to set your TRAC_ENV which is the path to the repository root (SET TRAC_ENV=C:\\trac\\MySpecialProject)</p>\n\n<p>The next MAJORLY IMPORTANT THING in this script is to do the following:</p>\n\n<blockquote>\n <p>:: GET THE AUTHOR AND THE LOG\n MESSAGE<br> for /F %%A in ('svnlook\n author -r %REV% %1') do set\n AUTHOR=%%A<br> for /F \"delims==\" %%B\n in ('svnlook log -r %REV% %1') do set\n LOG=%%B<br></p>\n</blockquote>\n\n<p>if you see in the script file above I'm using svnlook (which is a command line utility with SVN) to get the LOG message and the author that made the commit to the repository.</p>\n\n<p>Then, the next line of the script is actually calling the Python code to perform the closing of the tickets and parse the log message. I had to modify this to pass in the Log message and the author (which the usernames I use in Trac match the usernames in SVN so that was easy).</p>\n\n<blockquote>\n <p>CALL THE PYTHON SCRIPT<br> Python\n \"%~dp0\\trac-post-commit-hook\" -p\n \"%TRAC_ENV%\" -r \"%REV%\" -u \"%AUTHOR%\"\n -m \"%LOG%\"<br></p>\n</blockquote>\n\n<p>The above line in the script will pass into the python script the Trac Environment, the revision, the person that made the commit, and their comment.</p>\n\n<p>Here's the Python script that I used. One thing that I did additional to the regular script is we use a custom field (fixed_in_ver) which is used by our QA team to tell if the fix they're validating is in the version of code that they're testing in QA. So, I modified the code in the python script to update that field on the ticket. You can remove that code as you won't need it, but it's a good example of what you can do to update custom fields in Trac if you also want to do that.</p>\n\n<p>I did that by having the users optionally include in their comment something like:</p>\n\n<blockquote>\n <p>(version 2.1.2223.0)</p>\n</blockquote>\n\n<p>I then use the same technique that the python script uses with regular expressions to get the information out. It wasn't too bad.</p>\n\n<p>Anyway, here's the python script I used, Hopefully this is a good tutorial on exactly what I did to get it to work in the windows world so you all can leverage this in your own shop...</p>\n\n<p>If you don't want to deal with my additional code for updating the custom field, get the base script from this location as mentioned by Craig above (<a href=\"http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920\" rel=\"nofollow noreferrer\">Script From Edgewall</a>)</p>\n\n<pre><code>#!/usr/bin/env python\n\n# trac-post-commit-hook\n# ----------------------------------------------------------------------------\n# Copyright (c) 2004 Stephen Hansen \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software. \n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n# ----------------------------------------------------------------------------\n\n# This Subversion post-commit hook script is meant to interface to the\n# Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc \n# system.\n# \n# It should be called from the 'post-commit' script in Subversion, such as\n# via:\n#\n# REPOS=\"$1\"\n# REV=\"$2\"\n# LOG=`/usr/bin/svnlook log -r $REV $REPOS`\n# AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS`\n# TRAC_ENV='/somewhere/trac/project/'\n# TRAC_URL='http://trac.mysite.com/project/'\n#\n# /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \\\n# -p \"$TRAC_ENV\" \\\n# -r \"$REV\" \\\n# -u \"$AUTHOR\" \\\n# -m \"$LOG\" \\\n# -s \"$TRAC_URL\"\n#\n# It searches commit messages for text in the form of:\n# command #1\n# command #1, #2\n# command #1 &amp; #2 \n# command #1 and #2\n#\n# You can have more then one command in a message. The following commands\n# are supported. There is more then one spelling for each command, to make\n# this as user-friendly as possible.\n#\n# closes, fixes\n# The specified issue numbers are closed with the contents of this\n# commit message being added to it. \n# references, refs, addresses, re \n# The specified issue numbers are left in their current status, but \n# the contents of this commit message are added to their notes. \n#\n# A fairly complicated example of what you can do is with a commit message\n# of:\n#\n# Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12.\n#\n# This will close #10 and #12, and add a note to #12.\n\nimport re\nimport os\nimport sys\nimport time \n\nfrom trac.env import open_environment\nfrom trac.ticket.notification import TicketNotifyEmail\nfrom trac.ticket import Ticket\nfrom trac.ticket.web_ui import TicketModule\n# TODO: move grouped_changelog_entries to model.py\nfrom trac.util.text import to_unicode\nfrom trac.web.href import Href\n\ntry:\n from optparse import OptionParser\nexcept ImportError:\n try:\n from optik import OptionParser\n except ImportError:\n raise ImportError, 'Requires Python 2.3 or the Optik option parsing library.'\n\nparser = OptionParser()\nparser.add_option('-e', '--require-envelope', dest='env', default='',\n help='Require commands to be enclosed in an envelope. If -e[], '\n 'then commands must be in the form of [closes #4]. Must '\n 'be two characters.')\nparser.add_option('-p', '--project', dest='project',\n help='Path to the Trac project.')\nparser.add_option('-r', '--revision', dest='rev',\n help='Repository revision number.')\nparser.add_option('-u', '--user', dest='user',\n help='The user who is responsible for this action')\nparser.add_option('-m', '--msg', dest='msg',\n help='The log message to search.')\nparser.add_option('-c', '--encoding', dest='encoding',\n help='The encoding used by the log message.')\nparser.add_option('-s', '--siteurl', dest='url',\n help='The base URL to the project\\'s trac website (to which '\n '/ticket/## is appended). If this is not specified, '\n 'the project URL from trac.ini will be used.')\n\n(options, args) = parser.parse_args(sys.argv[1:])\n\nif options.env:\n leftEnv = '\\\\' + options.env[0]\n rghtEnv = '\\\\' + options.env[1]\nelse:\n leftEnv = ''\n rghtEnv = ''\n\ncommandPattern = re.compile(leftEnv + r'(?P&lt;action&gt;[A-Za-z]*).?(?P&lt;ticket&gt;#[0-9]+(?:(?:[, &amp;]*|[ ]?and[ ]?)#[0-9]+)*)' + rghtEnv)\nticketPattern = re.compile(r'#([0-9]*)')\nversionPattern = re.compile(r\"\\(version[ ]+(?P&lt;version&gt;([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+))\\)\")\n\nclass CommitHook:\n _supported_cmds = {'close': '_cmdClose',\n 'closed': '_cmdClose',\n 'closes': '_cmdClose',\n 'fix': '_cmdClose',\n 'fixed': '_cmdClose',\n 'fixes': '_cmdClose',\n 'addresses': '_cmdRefs',\n 're': '_cmdRefs',\n 'references': '_cmdRefs',\n 'refs': '_cmdRefs',\n 'see': '_cmdRefs'}\n\n def __init__(self, project=options.project, author=options.user,\n rev=options.rev, msg=options.msg, url=options.url,\n encoding=options.encoding):\n msg = to_unicode(msg, encoding)\n self.author = author\n self.rev = rev\n self.msg = \"(In [%s]) %s\" % (rev, msg)\n self.now = int(time.time()) \n self.env = open_environment(project)\n if url is None:\n url = self.env.config.get('project', 'url')\n self.env.href = Href(url)\n self.env.abs_href = Href(url)\n\n cmdGroups = commandPattern.findall(msg)\n\n\n tickets = {}\n\n for cmd, tkts in cmdGroups:\n funcname = CommitHook._supported_cmds.get(cmd.lower(), '')\n\n if funcname:\n\n for tkt_id in ticketPattern.findall(tkts):\n func = getattr(self, funcname)\n tickets.setdefault(tkt_id, []).append(func)\n\n for tkt_id, cmds in tickets.iteritems():\n try:\n db = self.env.get_db_cnx()\n\n ticket = Ticket(self.env, int(tkt_id), db)\n for cmd in cmds:\n cmd(ticket)\n\n # determine sequence number... \n cnum = 0\n tm = TicketModule(self.env)\n for change in tm.grouped_changelog_entries(ticket, db):\n if change['permanent']:\n cnum += 1\n\n # get the version number from the checkin... and update the ticket with it.\n version = versionPattern.search(msg)\n if version != None and version.group(\"version\") != None:\n ticket['fixed_in_ver'] = version.group(\"version\")\n\n ticket.save_changes(self.author, self.msg, self.now, db, cnum+1)\n db.commit()\n\n tn = TicketNotifyEmail(self.env)\n tn.notify(ticket, newticket=0, modtime=self.now)\n except Exception, e:\n # import traceback\n # traceback.print_exc(file=sys.stderr)\n print&gt;&gt;sys.stderr, 'Unexpected error while processing ticket ' \\\n 'ID %s: %s' % (tkt_id, e)\n\n\n def _cmdClose(self, ticket):\n ticket['status'] = 'closed'\n ticket['resolution'] = 'fixed'\n\n def _cmdRefs(self, ticket):\n pass\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) &lt; 5:\n print \"For usage: %s --help\" % (sys.argv[0])\n else:\n CommitHook()\n</code></pre>\n" }, { "answer_id": 1111147, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>One thing I'll add \"Code Monkey's Answer is PERFECT\" - is to be wary of this (my mistake)</p>\n\n<pre><code>:: Modify paths here:\n\n:: -- this one must be set\nSET TRAC_ENV=d:\\trac\\MySpecialProject\n\n:: -- set if Python is not in the system path\n:: SET PYTHON_PATH=**d:\\python**\n\n:: -- set to the folder containing trac/ if installed in a non-standard location \n:: SET TRAC_PATH=**d:\\python\\Lib\\site-packages\\trac**\n</code></pre>\n\n<p>I hadn't set the Non-System paths and took me a while to see the obvious :D </p>\n\n<p>Just match sure no-one else makes the same mistake! Thanks Code Monkey! 1000000000 points :D</p>\n" }, { "answer_id": 1219756, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>First a big thanks to Code Monkey!</p>\n\n<p>However, it's important to get the right python script depending on your trac version. To get the appropriate version, SVN check out the folder:</p>\n\n<p><a href=\"http://svn.edgewall.com/repos/trac/branches/\" rel=\"nofollow noreferrer\">http://svn.edgewall.com/repos/trac/branches/</a><strong>xxx</strong>-stable/contrib</p>\n\n<p>where <strong>xxx</strong> corresponds to the trac version you're using, for instance: 0.11</p>\n\n<p>Otherwise you'll get a post-commit error that looks like this:</p>\n\n<p>commit failed (details follow): MERGE of '/svn/project/trunk/web/directory/': 200 OK</p>\n" }, { "answer_id": 1309873, "author": "zveljkovic", "author_id": 185056, "author_profile": "https://Stackoverflow.com/users/185056", "pm_score": 0, "selected": false, "text": "<p>For all Windows users who wants to install newest trac (0.11.5):\nFollow the instructions on Trac's site named TracOnWindows.</p>\n\n<p>Download 32bit 1.5 Python even if You have 64bit Windows. \n note: I saw somewhere instructions how to compile trac to work natively on 64bit system.</p>\n\n<p>When You install all that is required go to the repository folder. There is folder hooks.\nInside it put files Code Monkey mentioned, but dont create \"trac-post-commit-resolve-ticket-ref.py\" like he did. Take advice from Quant Analyst and do like he said:</p>\n\n<p>\"However, it's important to get the right python script depending on your trac version. To get the appropriate version, SVN check out the folder:\n<a href=\"http://svn.edgewall.com/repos/trac/branches/\" rel=\"nofollow noreferrer\">http://svn.edgewall.com/repos/trac/branches/</a>xxx-stable/contrib\nwhere xxx corresponds to the trac version you're using, for instance: 0.11\"</p>\n\n<p>From there downoad file \"trac-post-commit-hook\" and put it in hooks folder.</p>\n\n<p>Edit these lines in trac-post-commit.cmd</p>\n\n<blockquote>\n <p>SET PYTHON_PATH=\"Path to python installation folder\" </p>\n \n <p>SET TRAC_ENV=\"Path to folder where you\n did tracd initenv\"</p>\n</blockquote>\n\n<p>Remember no last \\ !!!</p>\n\n<p>I have removed quotes from last line -r \"%REV%\" to be -r %REV% but i dont know if this is needed. This will not work now ( at least on my win 2008 server ), because hook will fail ( commit will go ok). This got to do with permissions. By default permissions are restricted and we need to allow python or svn or trac ( whatever i dont know ) to change trac information. So go to your trac folder,project folder,db folder, right click trac.db and choose properties. Go to the security tab and edit permissions to allow everyone full control. This isn't so secure but i wasted all day on this security matter and i don't want to waste another just to find for which user you should enable permissions.</p>\n\n<p>Hope this helps....</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5462/" ]
I'm running in a windows environment with Trac / SVN and I want commits to the repository to integrate to Trac and close the bugs that were noted in the SVN Comment. I know there's some post commit hooks to do that, but there's not much information about how to do it on windows. Anyone done it successfully? And what were the steps you followed to achive it? Here's the hook I need to put in place in SVN, but I'm not exactly sure how to do this in the Windows environment. [Trac Post Commit Hook](http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920)
Alright, now that I've got some time to post my experience after figuring this all out, and thanks to Craig for getting me on the right track. Here's what you need to do (at least with SVN v1.4 and Trac v0.10.3): 1. Locate your SVN repository that you want to enable the Post Commit Hook for. 2. inside the SVN repository there's a directory called hooks, this is where you'll be placing the post commit hook. 3. create a file post-commit.bat (this is the batch file that's automatically called by SVN post commit). 4. Place the following code inside the post-commit.bat file ( this will call your post commit cmd file passing in the parameters that SVN automatically passes %1 is the repository, %2 is the revision that was committed. %~dp0\trac-post-commit-hook.cmd %1 %2 5. Now create the trac-post-commit-hook.cmd file as follows: > > @ECHO OFF > :: > :: Trac > post-commit-hook script for > Windows > :: > :: Contributed by > markus, modified by cboos. > > :: > Usage: > :: > :: 1) Insert the > following line in your post-commit.bat > script > :: > :: call > %~dp0\trac-post-commit-hook.cmd %1 > %2 > :: > :: 2) Check the 'Modify > paths' section below, be sure to set > at least TRAC\_ENV > > > :: > ---------------------------------------------------------- > :: Modify paths here: > > :: -- > this one *must* be set > SET > TRAC\_ENV=C:\trac\MySpecialProject > > > :: -- set if Python is not in the > system path > :: SET > PYTHON\_PATH= > > :: -- set to the > folder containing trac/ if installed > in a non-standard location > :: SET > TRAC\_PATH= > :: > ---------------------------------------------------------- > > :: Do not execute hook if trac > environment does not exist > IF NOT > EXIST %TRAC\_ENV% GOTO :EOF > > > set PATH=%PYTHON\_PATH%;%PATH% > set > PYTHONPATH=%TRAC\_PATH%;%PYTHONPATH% > > > SET REV=%2 > > :: GET THE > AUTHOR AND THE LOG MESSAGE > for /F > %%A in ('svnlook author -r %REV% %1') > do set AUTHOR=%%A > for /F > "delims==" %%B in ('svnlook log -r > %REV% %1') do set LOG=%%B > > :: > CALL THE PYTHON SCRIPT > Python > "%~dp0\trac-post-commit-hook" -p > "%TRAC\_ENV%" -r "%REV%" -u "%AUTHOR%" > -m "%LOG%" > > > > The most important parts here are to set your TRAC\_ENV which is the path to the repository root (SET TRAC\_ENV=C:\trac\MySpecialProject) The next MAJORLY IMPORTANT THING in this script is to do the following: > > :: GET THE AUTHOR AND THE LOG > MESSAGE > for /F %%A in ('svnlook > author -r %REV% %1') do set > AUTHOR=%%A > for /F "delims==" %%B > in ('svnlook log -r %REV% %1') do set > LOG=%%B > > > > if you see in the script file above I'm using svnlook (which is a command line utility with SVN) to get the LOG message and the author that made the commit to the repository. Then, the next line of the script is actually calling the Python code to perform the closing of the tickets and parse the log message. I had to modify this to pass in the Log message and the author (which the usernames I use in Trac match the usernames in SVN so that was easy). > > CALL THE PYTHON SCRIPT > Python > "%~dp0\trac-post-commit-hook" -p > "%TRAC\_ENV%" -r "%REV%" -u "%AUTHOR%" > -m "%LOG%" > > > > The above line in the script will pass into the python script the Trac Environment, the revision, the person that made the commit, and their comment. Here's the Python script that I used. One thing that I did additional to the regular script is we use a custom field (fixed\_in\_ver) which is used by our QA team to tell if the fix they're validating is in the version of code that they're testing in QA. So, I modified the code in the python script to update that field on the ticket. You can remove that code as you won't need it, but it's a good example of what you can do to update custom fields in Trac if you also want to do that. I did that by having the users optionally include in their comment something like: > > (version 2.1.2223.0) > > > I then use the same technique that the python script uses with regular expressions to get the information out. It wasn't too bad. Anyway, here's the python script I used, Hopefully this is a good tutorial on exactly what I did to get it to work in the windows world so you all can leverage this in your own shop... If you don't want to deal with my additional code for updating the custom field, get the base script from this location as mentioned by Craig above ([Script From Edgewall](http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920)) ``` #!/usr/bin/env python # trac-post-commit-hook # ---------------------------------------------------------------------------- # Copyright (c) 2004 Stephen Hansen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # ---------------------------------------------------------------------------- # This Subversion post-commit hook script is meant to interface to the # Trac (http://www.edgewall.com/products/trac/) issue tracking/wiki/etc # system. # # It should be called from the 'post-commit' script in Subversion, such as # via: # # REPOS="$1" # REV="$2" # LOG=`/usr/bin/svnlook log -r $REV $REPOS` # AUTHOR=`/usr/bin/svnlook author -r $REV $REPOS` # TRAC_ENV='/somewhere/trac/project/' # TRAC_URL='http://trac.mysite.com/project/' # # /usr/bin/python /usr/local/src/trac/contrib/trac-post-commit-hook \ # -p "$TRAC_ENV" \ # -r "$REV" \ # -u "$AUTHOR" \ # -m "$LOG" \ # -s "$TRAC_URL" # # It searches commit messages for text in the form of: # command #1 # command #1, #2 # command #1 & #2 # command #1 and #2 # # You can have more then one command in a message. The following commands # are supported. There is more then one spelling for each command, to make # this as user-friendly as possible. # # closes, fixes # The specified issue numbers are closed with the contents of this # commit message being added to it. # references, refs, addresses, re # The specified issue numbers are left in their current status, but # the contents of this commit message are added to their notes. # # A fairly complicated example of what you can do is with a commit message # of: # # Changed blah and foo to do this or that. Fixes #10 and #12, and refs #12. # # This will close #10 and #12, and add a note to #12. import re import os import sys import time from trac.env import open_environment from trac.ticket.notification import TicketNotifyEmail from trac.ticket import Ticket from trac.ticket.web_ui import TicketModule # TODO: move grouped_changelog_entries to model.py from trac.util.text import to_unicode from trac.web.href import Href try: from optparse import OptionParser except ImportError: try: from optik import OptionParser except ImportError: raise ImportError, 'Requires Python 2.3 or the Optik option parsing library.' parser = OptionParser() parser.add_option('-e', '--require-envelope', dest='env', default='', help='Require commands to be enclosed in an envelope. If -e[], ' 'then commands must be in the form of [closes #4]. Must ' 'be two characters.') parser.add_option('-p', '--project', dest='project', help='Path to the Trac project.') parser.add_option('-r', '--revision', dest='rev', help='Repository revision number.') parser.add_option('-u', '--user', dest='user', help='The user who is responsible for this action') parser.add_option('-m', '--msg', dest='msg', help='The log message to search.') parser.add_option('-c', '--encoding', dest='encoding', help='The encoding used by the log message.') parser.add_option('-s', '--siteurl', dest='url', help='The base URL to the project\'s trac website (to which ' '/ticket/## is appended). If this is not specified, ' 'the project URL from trac.ini will be used.') (options, args) = parser.parse_args(sys.argv[1:]) if options.env: leftEnv = '\\' + options.env[0] rghtEnv = '\\' + options.env[1] else: leftEnv = '' rghtEnv = '' commandPattern = re.compile(leftEnv + r'(?P<action>[A-Za-z]*).?(?P<ticket>#[0-9]+(?:(?:[, &]*|[ ]?and[ ]?)#[0-9]+)*)' + rghtEnv) ticketPattern = re.compile(r'#([0-9]*)') versionPattern = re.compile(r"\(version[ ]+(?P<version>([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+))\)") class CommitHook: _supported_cmds = {'close': '_cmdClose', 'closed': '_cmdClose', 'closes': '_cmdClose', 'fix': '_cmdClose', 'fixed': '_cmdClose', 'fixes': '_cmdClose', 'addresses': '_cmdRefs', 're': '_cmdRefs', 'references': '_cmdRefs', 'refs': '_cmdRefs', 'see': '_cmdRefs'} def __init__(self, project=options.project, author=options.user, rev=options.rev, msg=options.msg, url=options.url, encoding=options.encoding): msg = to_unicode(msg, encoding) self.author = author self.rev = rev self.msg = "(In [%s]) %s" % (rev, msg) self.now = int(time.time()) self.env = open_environment(project) if url is None: url = self.env.config.get('project', 'url') self.env.href = Href(url) self.env.abs_href = Href(url) cmdGroups = commandPattern.findall(msg) tickets = {} for cmd, tkts in cmdGroups: funcname = CommitHook._supported_cmds.get(cmd.lower(), '') if funcname: for tkt_id in ticketPattern.findall(tkts): func = getattr(self, funcname) tickets.setdefault(tkt_id, []).append(func) for tkt_id, cmds in tickets.iteritems(): try: db = self.env.get_db_cnx() ticket = Ticket(self.env, int(tkt_id), db) for cmd in cmds: cmd(ticket) # determine sequence number... cnum = 0 tm = TicketModule(self.env) for change in tm.grouped_changelog_entries(ticket, db): if change['permanent']: cnum += 1 # get the version number from the checkin... and update the ticket with it. version = versionPattern.search(msg) if version != None and version.group("version") != None: ticket['fixed_in_ver'] = version.group("version") ticket.save_changes(self.author, self.msg, self.now, db, cnum+1) db.commit() tn = TicketNotifyEmail(self.env) tn.notify(ticket, newticket=0, modtime=self.now) except Exception, e: # import traceback # traceback.print_exc(file=sys.stderr) print>>sys.stderr, 'Unexpected error while processing ticket ' \ 'ID %s: %s' % (tkt_id, e) def _cmdClose(self, ticket): ticket['status'] = 'closed' ticket['resolution'] = 'fixed' def _cmdRefs(self, ticket): pass if __name__ == "__main__": if len(sys.argv) < 5: print "For usage: %s --help" % (sys.argv[0]) else: CommitHook() ```
84,209
<p><strong>Introduction</strong></p> <p>I've always been searching for a way to make Visual Studio draw a line after a certain amount of characters.</p> <p>Below is a guide to enable these so called <em>guidelines</em> for various versions of Visual Studio.</p> <p><strong>Visual Studio 2013 or later</strong></p> <p>Install Paul Harrington's <a href="http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459/view/Reviews" rel="noreferrer">Editor Guidelines extension</a>.</p> <p><strong>Visual Studio 2010 and 2012</strong></p> <ol> <li>Install Paul Harrington's Editor Guidelines extension for <a href="http://visualstudiogallery.msdn.microsoft.com/0fbf2878-e678-4577-9fdb-9030389b338c" rel="noreferrer">VS 2010</a> or <a href="http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459?SRC=Home" rel="noreferrer">VS 2012</a>.</li> <li>Open the registry at: <br />VS 2010: <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor</code> <br />VS 2012: <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor</code> <br />and add a new string called <code>Guides</code> with the value <code>RGB(100,100,100), 80</code>. The first part specifies the color, while the other one (<code>80</code>) is the column the line will be displayed.</li> <li>Or install the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91" rel="noreferrer">Guidelines UI</a> extension (which is also a part of the <a href="http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/" rel="noreferrer">Productivity Power Tools</a>), which will add entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. The current disadvantage of this method is that you can't specify the column directly.</li> </ol> <p><strong>Visual Studio 2008 and Other Versions</strong></p> <p>If you are using Visual Studio 2008 open the registry at <code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor</code> and add a new string called <code>Guides</code> with the value <code>RGB(100,100,100), 80</code>. The first part specifies the color, while the other one (<code>80</code>) is the column the line will be displayed. The vertical line will appear, when you restart Visual Studio.</p> <p>This trick also works for various other version of Visual Studio, as long as you use the correct path:</p> <pre><code>2003: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor 2005: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor 2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor 2008 Express: HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor </code></pre> <p><a href="https://stackoverflow.com/a/332577/11387">This also works in SQL Server 2005 and probably other versions.</a></p>
[ { "answer_id": 84325, "author": "Rory MacLeod", "author_id": 1016, "author_profile": "https://Stackoverflow.com/users/1016", "pm_score": 2, "selected": false, "text": "<p>The registry path for Visual Studio 2008 is the same, but with 9.0 as the version number:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\9.0\\Text Editor\n</code></pre>\n" }, { "answer_id": 84467, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 8, "selected": true, "text": "<p>This is originally from Sara's <a href=\"https://web.archive.org/web/20160221095812/http://blogs.msdn.com:80/b/saraford/archive/2004/11/15/257953.aspx\" rel=\"nofollow noreferrer\">blog</a>.</p>\n<p>It also works with almost any version of Visual Studio, you just need to change the &quot;8.0&quot; in the registry key to the appropriate version number for your version of Visual Studio.</p>\n<p>The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.)</p>\n<p>You can also have the guide in multiple columns by listing more than one number after the color specifier:</p>\n<pre><code>RGB(230,230,230), 4, 80\n</code></pre>\n<p>Puts a white line at column 4 and column 80. This should be the value of a string value <code>Guides</code> in &quot;Text Editor&quot; key (see bellow).</p>\n<p>Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221).</p>\n<p>Here are the registry keys that I know of:</p>\n<p><strong>Visual Studio 2010</strong>: HKCU\\Software\\Microsoft\\VisualStudio\\10.0\\Text Editor</p>\n<p><strong>Visual Studio 2008</strong>: HKCU\\Software\\Microsoft\\VisualStudio\\9.0\\Text Editor</p>\n<p><strong>Visual Studio 2005</strong>: HKCU\\Software\\Microsoft\\VisualStudio\\8.0\\Text Editor</p>\n<p><strong>Visual Studio 2003</strong>: HKCU\\Software\\Microsoft\\VisualStudio\\7.1\\Text Editor</p>\n<p>For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself:</p>\n<ul>\n<li><p><a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c\" rel=\"nofollow noreferrer\">http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c</a></p>\n</li>\n<li><p><a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91\" rel=\"nofollow noreferrer\">http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91</a></p>\n</li>\n</ul>\n<p>These are also part of the <a href=\"https://web.archive.org/web/20110119025922/http://visualstudiogallery.msdn.microsoft.com:80/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef\" rel=\"nofollow noreferrer\">Productivity Power Tools</a>, which includes many other very useful extensions.</p>\n" }, { "answer_id": 281333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If you are a user of the free Visual Studio Express edition the right key is in </p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VCExpress\\9.0\\Text Editor\n</code></pre>\n\n<p>{note the VCExpress instead of VisualStudio) but it works! :)</p>\n" }, { "answer_id": 344396, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 3, "selected": false, "text": "<p>This works for <a href=\"https://stackoverflow.com/questions/332574/how-can-i-see-where-the-tab-stops-are-in-the-sql-server-management-studio-editor\">SQL Server Management Studio</a> also.</p>\n" }, { "answer_id": 2111416, "author": "Noah Richards", "author_id": 128945, "author_profile": "https://Stackoverflow.com/users/128945", "pm_score": 3, "selected": false, "text": "<p>This will also work in Visual Studio 2010 (Beta 2), as long as you install Paul Harrington's extension to enable the guidelines <a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c\" rel=\"noreferrer\">from the VSGallery</a> or from the extension manager inside VS2010. Since this is version 10.0, you should use the following registry key:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\10.0\\Text Editor\n</code></pre>\n\n<p>Also, Paul wrote an extension that adds entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. You can find it here: <a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91\" rel=\"noreferrer\">http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91</a></p>\n" }, { "answer_id": 3830406, "author": "rony l", "author_id": 16418, "author_profile": "https://Stackoverflow.com/users/16418", "pm_score": 6, "selected": false, "text": "<p>Without the need to edit any registry keys, the <a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef\" rel=\"noreferrer\">Productivity Power Tools extension</a> (available for all versions of visual studio) provides guideline functionality.</p>\n\n<p>Once installed just right click while in the editor window and choose the add guide line option. Note that the guideline will always be placed on the column where your editing cursor is currently at, regardless of where you right click in the editor window.</p>\n\n<p><a href=\"https://i.stack.imgur.com/S5yyn.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/S5yyn.png\" alt=\"enter image description here\"></a></p>\n\n<p>To turn off go to options and find <code>Productivity Power Tools</code> and in that section turn off <code>Column Guides</code>. A reboot will be necessary.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8Rj4o.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8Rj4o.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 10186168, "author": "Dio", "author_id": 1337969, "author_profile": "https://Stackoverflow.com/users/1337969", "pm_score": 3, "selected": false, "text": "<p>I found this Visual Studio 2010 extension: Indent Guides</p>\n\n<p><a href=\"http://visualstudiogallery.msdn.microsoft.com/e792686d-542b-474a-8c55-630980e72c30\" rel=\"nofollow\">http://visualstudiogallery.msdn.microsoft.com/e792686d-542b-474a-8c55-630980e72c30</a></p>\n\n<p>It works just fine.\n<a href=\"https://i.stack.imgur.com/6uR9P.png\" rel=\"nofollow\"><img src=\"https://i.stack.imgur.com/6uR9P.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 12402353, "author": "brianpeiris", "author_id": 22417, "author_profile": "https://Stackoverflow.com/users/22417", "pm_score": 4, "selected": false, "text": "<p>There is now an extension for Visual Studio 2012 and 2013:</p>\n\n<p><a href=\"http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459\" rel=\"noreferrer\">http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459</a></p>\n" }, { "answer_id": 25581622, "author": "eddyq", "author_id": 215779, "author_profile": "https://Stackoverflow.com/users/215779", "pm_score": 2, "selected": false, "text": "<p>With VS 2013 Express this key does not exist. What I see is HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\12.0 and there is no mention of Text Editor under that.</p>\n" }, { "answer_id": 51170072, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p><strong>Visual Studio 2017 / 2019</strong></p>\n<p>For anyone looking for an answer for a newer version of Visual Studio, <a href=\"https://marketplace.visualstudio.com/items?itemName=PaulHarrington.EditorGuidelines\" rel=\"noreferrer\">install the Editor Guidelines plugin</a>, then right-click in the editor and select this:</p>\n<p><a href=\"https://i.stack.imgur.com/VUxyQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VUxyQ.png\" alt=\"Add guidelines in Visual Studio 2017\" /></a></p>\n<p><strong>Visual Studio 2022</strong></p>\n<p>Same author as the package above but seems he had to split the extension to work with 2022.</p>\n<p><a href=\"https://marketplace.visualstudio.com/items?itemName=PaulHarrington.EditorGuidelinesPreview&amp;ssr=false#overview\" rel=\"noreferrer\">https://marketplace.visualstudio.com/items?itemName=PaulHarrington.EditorGuidelinesPreview&amp;ssr=false#overview</a></p>\n" }, { "answer_id": 54382823, "author": "Pavel P", "author_id": 468725, "author_profile": "https://Stackoverflow.com/users/468725", "pm_score": 2, "selected": false, "text": "<p>For those who use <a href=\"https://www.wholetomato.com/\" rel=\"nofollow noreferrer\">Visual Assist</a>, vertical guidelines can be enabled from <code>Display</code> section in Visual Assist's options:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bb7A1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bb7A1.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 62960343, "author": "Daniel Fisher lennybacon", "author_id": 12679, "author_profile": "https://Stackoverflow.com/users/12679", "pm_score": 0, "selected": false, "text": "<p>For VS 2019 just use this powershell script:</p>\n<pre><code>Get-ChildItem &quot;$($env:LOCALAPPDATA)\\Microsoft\\VisualStudio\\16.0_*&quot; | \nForeach-Object {\n $dir = $_;\n $regFile = &quot;$($dir.FullName)\\privateregistry.bin&quot;;\n Write-Host &quot;Loading $($dir.BaseName) from ``$regFile``&quot;\n &amp; reg load &quot;HKLM\\_TMPVS_&quot; &quot;$regFile&quot;\n New-ItemProperty -Name &quot;Guides&quot; -Path &quot;HKLM:\\_TMPVS_\\Software\\Microsoft\\VisualStudio\\$($dir.BaseName)\\Text Editor&quot; -Value &quot;RGB(255,0,0), 80&quot; -force | Out-Null;\n \n Sleep -Seconds 5; # might take some time befor the file can be unloaded\n &amp; reg unload &quot;HKLM\\_TMPVS_&quot;;\n Write-Host &quot;Unloaded $($dir.BaseName) from ``$regFile``&quot;\n}\n</code></pre>\n" }, { "answer_id": 67421471, "author": "Sven Voigt", "author_id": 10821861, "author_profile": "https://Stackoverflow.com/users/10821861", "pm_score": -1, "selected": false, "text": "<p>You might be looking for rulers not guidelines.</p>\n<p>Go to settings &gt; editor &gt; rulers &gt; and give an array of character counts to provide lines at the specified values.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11387/" ]
**Introduction** I've always been searching for a way to make Visual Studio draw a line after a certain amount of characters. Below is a guide to enable these so called *guidelines* for various versions of Visual Studio. **Visual Studio 2013 or later** Install Paul Harrington's [Editor Guidelines extension](http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459/view/Reviews). **Visual Studio 2010 and 2012** 1. Install Paul Harrington's Editor Guidelines extension for [VS 2010](http://visualstudiogallery.msdn.microsoft.com/0fbf2878-e678-4577-9fdb-9030389b338c) or [VS 2012](http://visualstudiogallery.msdn.microsoft.com/da227a0b-0e31-4a11-8f6b-3a149cf2e459?SRC=Home). 2. Open the registry at: VS 2010: `HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor` VS 2012: `HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\Text Editor` and add a new string called `Guides` with the value `RGB(100,100,100), 80`. The first part specifies the color, while the other one (`80`) is the column the line will be displayed. 3. Or install the [Guidelines UI](http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91) extension (which is also a part of the [Productivity Power Tools](http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/)), which will add entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. The current disadvantage of this method is that you can't specify the column directly. **Visual Studio 2008 and Other Versions** If you are using Visual Studio 2008 open the registry at `HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor` and add a new string called `Guides` with the value `RGB(100,100,100), 80`. The first part specifies the color, while the other one (`80`) is the column the line will be displayed. The vertical line will appear, when you restart Visual Studio. This trick also works for various other version of Visual Studio, as long as you use the correct path: ``` 2003: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor 2005: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor 2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor 2008 Express: HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor ``` [This also works in SQL Server 2005 and probably other versions.](https://stackoverflow.com/a/332577/11387)
This is originally from Sara's [blog](https://web.archive.org/web/20160221095812/http://blogs.msdn.com:80/b/saraford/archive/2004/11/15/257953.aspx). It also works with almost any version of Visual Studio, you just need to change the "8.0" in the registry key to the appropriate version number for your version of Visual Studio. The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.) You can also have the guide in multiple columns by listing more than one number after the color specifier: ``` RGB(230,230,230), 4, 80 ``` Puts a white line at column 4 and column 80. This should be the value of a string value `Guides` in "Text Editor" key (see bellow). Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221). Here are the registry keys that I know of: **Visual Studio 2010**: HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor **Visual Studio 2008**: HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor **Visual Studio 2005**: HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor **Visual Studio 2003**: HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself: * <http://visualstudiogallery.msdn.microsoft.com/en-us/0fbf2878-e678-4577-9fdb-9030389b338c> * <http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91> These are also part of the [Productivity Power Tools](https://web.archive.org/web/20110119025922/http://visualstudiogallery.msdn.microsoft.com:80/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef), which includes many other very useful extensions.
84,278
<p>How do I use <code>RelativeSource</code> with WPF bindings and what are the different use-cases?</p>
[ { "answer_id": 84314, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 5, "selected": false, "text": "<p>Don't forget TemplatedParent:</p>\n\n<pre><code>&lt;Binding RelativeSource=\"{RelativeSource TemplatedParent}\"/&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>{Binding RelativeSource={RelativeSource TemplatedParent}}\n</code></pre>\n" }, { "answer_id": 84317, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 11, "selected": true, "text": "<p>If you want to bind to another property on the object:</p>\n\n<pre><code>{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}\n</code></pre>\n\n<p>If you want to get a property on an ancestor:</p>\n\n<pre><code>{Binding Path=PathToProperty,\n RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}\n</code></pre>\n\n<p>If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)</p>\n\n<pre><code>{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}\n</code></pre>\n\n<p>or, shorter (this only works for OneWay bindings):</p>\n\n<pre><code>{TemplateBinding Path=PathToProperty}\n</code></pre>\n" }, { "answer_id": 605695, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 7, "selected": false, "text": "<pre><code>Binding RelativeSource={\n RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemType}\n}\n...\n</code></pre>\n\n<p>The default attribute of <code>RelativeSource</code> is the <code>Mode</code> property. A complete set of valid values is given here (<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.relativesourcemode.aspx\" rel=\"noreferrer\">from MSDN</a>):</p>\n\n<ul>\n<li><p><em>PreviousData</em> Allows you to bind the previous data item (not that control that contains the data item) in the list of data items being displayed.</p></li>\n<li><p><em>TemplatedParent</em> Refers to the element to which the template (in which the data-bound element exists) is applied. This is similar to setting a TemplateBindingExtension and is only applicable if the Binding is within a template.</p></li>\n<li><p><em>Self</em> Refers to the element on which you are setting the binding and allows you to bind one property of that element to another property on the same element.</p></li>\n<li><p><em>FindAncestor</em> Refers to the ancestor in the parent chain of the data-bound element. You can use this to bind to an ancestor of a specific type or its subclasses. This is the mode you use if you want to specify AncestorType and/or AncestorLevel.</p></li>\n</ul>\n" }, { "answer_id": 2705121, "author": "Matthew Black", "author_id": 320433, "author_profile": "https://Stackoverflow.com/users/320433", "pm_score": 4, "selected": false, "text": "<p>It's worthy of note that for those stumbling across this thinking of Silverlight:</p>\n\n<p>Silverlight offers a reduced subset only, of these commands</p>\n" }, { "answer_id": 3547783, "author": "Juve", "author_id": 8986, "author_profile": "https://Stackoverflow.com/users/8986", "pm_score": 4, "selected": false, "text": "<p>I just posted <a href=\"https://stackoverflow.com/questions/3404707/wpf-access-parent-datacontext-from-datatemplate/3547707#3547707\"><strong>another solution</strong></a> for accessing the DataContext of a parent element in Silverlight that works for me. It uses <code>Binding ElementName</code>.</p>\n" }, { "answer_id": 5320426, "author": "Jeffrey Knight", "author_id": 83418, "author_profile": "https://Stackoverflow.com/users/83418", "pm_score": 7, "selected": false, "text": "<p>Here's a more visual explanation in the context of a MVVM architecture:</p>\n\n<p><img src=\"https://i.stack.imgur.com/6Tcc6.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 11833632, "author": "Luis Perez", "author_id": 984780, "author_profile": "https://Stackoverflow.com/users/984780", "pm_score": 4, "selected": false, "text": "<p>I created a library to simplify the binding syntax of WPF including making it easier to use RelativeSource. Here are some examples. Before:</p>\n\n<pre><code>{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}\n{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}\n{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}\n{Binding Path=Text, ElementName=MyTextBox}\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>{BindTo PathToProperty}\n{BindTo Ancestor.typeOfAncestor.PathToProperty}\n{BindTo Template.PathToProperty}\n{BindTo #MyTextBox.Text}\n</code></pre>\n\n<p>Here is an example of how method binding is simplified. Before:</p>\n\n<pre><code>// C# code\nprivate ICommand _saveCommand;\npublic ICommand SaveCommand {\n get {\n if (_saveCommand == null) {\n _saveCommand = new RelayCommand(x =&gt; this.SaveObject());\n }\n return _saveCommand;\n }\n}\n\nprivate void SaveObject() {\n // do something\n}\n\n// XAML\n{Binding Path=SaveCommand}\n</code></pre>\n\n<p>After:</p>\n\n<pre><code>// C# code\nprivate void SaveObject() {\n // do something\n}\n\n// XAML\n{BindTo SaveObject()}\n</code></pre>\n\n<p>You can find the library here: <a href=\"http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html\">http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html</a></p>\n\n<p>Note in the 'BEFORE' example that I use for method binding that code was already optimized by using <code>RelayCommand</code> which last I checked is not a native part of WPF. Without that the 'BEFORE' example would have been even longer.</p>\n" }, { "answer_id": 13137935, "author": "Nathan Cooper", "author_id": 1734730, "author_profile": "https://Stackoverflow.com/users/1734730", "pm_score": 4, "selected": false, "text": "<p>Some useful bits and pieces:</p>\n\n<p>Here's how to do it mostly in code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Binding b = new Binding();\nb.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, this.GetType(), 1);\nb.Path = new PropertyPath(\"MyElementThatNeedsBinding\");\nMyLabel.SetBinding(ContentProperty, b);\n</code></pre>\n\n<p>I largely copied this from <em><a href=\"http://social.msdn.microsoft.com/Forums/en/wpf/thread/c5a59f07-c932-4715-8774-fa7e8472b75b\" rel=\"noreferrer\">Binding Relative Source in code Behind</a></em>.</p>\n\n<p>Also, the MSDN page is pretty good as far as examples go: <em><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.relativesource.aspx\" rel=\"noreferrer\">RelativeSource Class</a></em></p>\n" }, { "answer_id": 19470853, "author": "Cornel Marian", "author_id": 736113, "author_profile": "https://Stackoverflow.com/users/736113", "pm_score": 6, "selected": false, "text": "<p>Bechir Bejaoui exposes the use cases of the RelativeSources in WPF in <a href=\"http://www.c-sharpcorner.com/UploadFile/yougerthen/relativesources-in-wpf/\">his article here</a>:</p>\n\n<blockquote>\n <p>The RelativeSource is a markup extension that is used in particular\n binding cases when we try to bind a property of a given object to\n another property of the object itself, when we try to bind a property\n of a object to another one of its relative parents, when binding a\n dependency property value to a piece of XAML in case of custom control\n development and finally in case of using a differential of a series of\n a bound data. All of those situations are expressed as relative source\n modes. I will expose all of those cases one by one.</p>\n \n <ol>\n <li>Mode Self:</li>\n </ol>\n \n <p>Imagine this case, a rectangle that we want that its height is always\n equal to its width, a square let's say. We can do this using the\n element name</p>\n\n<pre><code>&lt;Rectangle Fill=\"Red\" Name=\"rectangle\" \n Height=\"100\" Stroke=\"Black\" \n Canvas.Top=\"100\" Canvas.Left=\"100\"\n Width=\"{Binding ElementName=rectangle,\n Path=Height}\"/&gt;\n</code></pre>\n \n <p>But in this above case we are obliged to indicate the name of the\n binding object, namely the rectangle. We can reach the same purpose\n differently using the RelativeSource </p>\n\n<pre><code>&lt;Rectangle Fill=\"Red\" Height=\"100\" \n Stroke=\"Black\" \n Width=\"{Binding RelativeSource={RelativeSource Self},\n Path=Height}\"/&gt;\n</code></pre>\n \n <p>For that case we are not obliged to mention the name of the binding\n object and the Width will be always equal to the Height whenever the\n height is changed. </p>\n \n <p>If you want to parameter the Width to be the half of the height then\n you can do this by adding a converter to the Binding markup extension.\n Let's imagine another case now:</p>\n\n<pre><code> &lt;TextBlock Width=\"{Binding RelativeSource={RelativeSource Self},\n Path=Parent.ActualWidth}\"/&gt;\n</code></pre>\n \n <p>The above case is used to tie a given property of a given element to\n one of its direct parent ones as this element holds a property that is\n called Parent. This leads us to another relative source mode which is\n the FindAncestor one. </p>\n \n <ol>\n <li>Mode FindAncestor</li>\n </ol>\n \n <p>In this case, a property of a given element will be tied to one of its\n parents, Of Corse. The main difference with the above case is the fact\n that, it's up to you to determine the ancestor type and the ancestor\n rank in the hierarchy to tie the property. By the way try to play with\n this piece of XAML</p>\n\n<pre><code>&lt;Canvas Name=\"Parent0\"&gt;\n &lt;Border Name=\"Parent1\"\n Width=\"{Binding RelativeSource={RelativeSource Self},\n Path=Parent.ActualWidth}\"\n Height=\"{Binding RelativeSource={RelativeSource Self},\n Path=Parent.ActualHeight}\"&gt;\n &lt;Canvas Name=\"Parent2\"&gt;\n &lt;Border Name=\"Parent3\"\n Width=\"{Binding RelativeSource={RelativeSource Self},\n Path=Parent.ActualWidth}\"\n Height=\"{Binding RelativeSource={RelativeSource Self},\n Path=Parent.ActualHeight}\"&gt;\n &lt;Canvas Name=\"Parent4\"&gt;\n &lt;TextBlock FontSize=\"16\" \n Margin=\"5\" Text=\"Display the name of the ancestor\"/&gt;\n &lt;TextBlock FontSize=\"16\" \n Margin=\"50\" \n Text=\"{Binding RelativeSource={RelativeSource \n FindAncestor,\n AncestorType={x:Type Border}, \n AncestorLevel=2},Path=Name}\" \n Width=\"200\"/&gt;\n &lt;/Canvas&gt;\n &lt;/Border&gt;\n &lt;/Canvas&gt;\n &lt;/Border&gt;\n &lt;/Canvas&gt;\n</code></pre>\n \n <p>The above situation is of two TextBlock elements those are embedded\n within a series of borders and canvas elements those represent their\n hierarchical parents. The second TextBlock will display the name of\n the given parent at the relative source level.</p>\n \n <p>So try to change AncestorLevel=2 to AncestorLevel=1 and see what\n happens. Then try to change the type of the ancestor from\n AncestorType=Border to AncestorType=Canvas and see what's happens. </p>\n \n <p>The displayed text will change according to the Ancestor type and\n level. Then what's happen if the ancestor level is not suitable to the\n ancestor type? This is a good question, I know that you're about to\n ask it. The response is no exceptions will be thrown and nothings will\n be displayed at the TextBlock level. </p>\n \n <ol>\n <li>TemplatedParent</li>\n </ol>\n \n <p>This mode enables tie a given ControlTemplate property to a property\n of the control that the ControlTemplate is applied to. To well\n understand the issue here is an example bellow</p>\n\n<pre><code>&lt;Window.Resources&gt;\n&lt;ControlTemplate x:Key=\"template\"&gt;\n &lt;Canvas&gt;\n &lt;Canvas.RenderTransform&gt;\n &lt;RotateTransform Angle=\"20\"/&gt;\n &lt;/Canvas.RenderTransform&gt;\n &lt;Ellipse Height=\"100\" Width=\"150\" \n Fill=\"{Binding \n RelativeSource={RelativeSource TemplatedParent},\n Path=Background}\"&gt;\n\n &lt;/Ellipse&gt;\n &lt;ContentPresenter Margin=\"35\" \n Content=\"{Binding RelativeSource={RelativeSource \n TemplatedParent},Path=Content}\"/&gt;\n &lt;/Canvas&gt;\n &lt;/ControlTemplate&gt;\n&lt;/Window.Resources&gt;\n &lt;Canvas Name=\"Parent0\"&gt;\n &lt;Button Margin=\"50\" \n Template=\"{StaticResource template}\" Height=\"0\" \n Canvas.Left=\"0\" Canvas.Top=\"0\" Width=\"0\"&gt;\n &lt;TextBlock FontSize=\"22\"&gt;Click me&lt;/TextBlock&gt;\n &lt;/Button&gt;\n &lt;/Canvas&gt;\n</code></pre>\n \n <p>If I want to apply the properties of a given control to its control\n template then I can use the TemplatedParent mode. There is also a\n similar one to this markup extension which is the TemplateBinding\n which is a kind of short hand of the first one, but the\n TemplateBinding is evaluated at compile time at the contrast of the\n TemplatedParent which is evaluated just after the first run time. As\n you can remark in the bellow figure, the background and the content\n are applied from within the button to the control template.</p>\n</blockquote>\n" }, { "answer_id": 29946000, "author": "Edd", "author_id": 2399164, "author_profile": "https://Stackoverflow.com/users/2399164", "pm_score": 3, "selected": false, "text": "<p>This is an example of the use of this pattern that worked for me on empty datagrids.</p>\n\n<pre><code>&lt;Style.Triggers&gt;\n &lt;DataTrigger Binding=\"{Binding Items.Count, RelativeSource={RelativeSource Self}}\" Value=\"0\"&gt;\n &lt;Setter Property=\"Background\"&gt;\n &lt;Setter.Value&gt;\n &lt;VisualBrush Stretch=\"None\"&gt;\n &lt;VisualBrush.Visual&gt;\n &lt;TextBlock Text=\"We did't find any matching records for your search...\" FontSize=\"16\" FontWeight=\"SemiBold\" Foreground=\"LightCoral\"/&gt;\n &lt;/VisualBrush.Visual&gt;\n &lt;/VisualBrush&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;/DataTrigger&gt;\n&lt;/Style.Triggers&gt;\n</code></pre>\n" }, { "answer_id": 34925445, "author": "Kylo Ren", "author_id": 4576125, "author_profile": "https://Stackoverflow.com/users/4576125", "pm_score": 5, "selected": false, "text": "<p><strong><em>In WPF <code>RelativeSource</code> binding exposes three <code>properties</code> to set:</em></strong></p>\n\n<p><strong>1. Mode:</strong> This is an <code>enum</code> that could have four values:</p>\n\n<blockquote>\n <p><strong><em>a. PreviousData(<code>value=0</code>):</em></strong> It assigns the previous value of the <code>property</code> to\n the bound one</p>\n \n <p><strong><em>b. TemplatedParent(<code>value=1</code>):</em></strong> This is used when defining the <code>templates</code> of\n any control and want to bind to a value/Property of the <code>control</code>.</p>\n \n <p><strong>For example,</strong> define <code>ControlTemplate</code>:</p>\n</blockquote>\n\n<pre><code> &lt;ControlTemplate&gt;\n &lt;CheckBox IsChecked=\"{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\" /&gt;\n &lt;/ControlTemplate&gt;\n</code></pre>\n\n<blockquote>\n <p><strong><em>c. Self(<code>value=2</code>):</em></strong> When we want to bind from a <code>self</code> or a <code>property</code> of self.</p>\n \n <p><strong>For example:</strong> Send checked state of <code>checkbox</code> as <code>CommandParameter</code> while setting the <code>Command</code> on <code>CheckBox</code></p>\n</blockquote>\n\n<pre><code>&lt;CheckBox ...... CommandParameter=\"{Binding RelativeSource={RelativeSource Self},Path=IsChecked}\" /&gt;\n</code></pre>\n\n<blockquote>\n <p><strong><em>d. FindAncestor(<code>value=3</code>):</em></strong> When want to bind from a parent <code>control</code>\n in <code>Visual Tree</code>.</p>\n \n <p><strong>For example:</strong> Bind a <code>checkbox</code> in <code>records</code> if a <code>grid</code>,if <code>header</code> <code>checkbox</code> is checked</p>\n</blockquote>\n\n<pre><code>&lt;CheckBox IsChecked=\"{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}\" /&gt;\n</code></pre>\n\n<p><strong>2. AncestorType:</strong> when mode is <code>FindAncestor</code> then define what type of ancestor</p>\n\n<pre><code>RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}\n</code></pre>\n\n<p><strong><em>3. AncestorLevel:</em></strong> when mode is <code>FindAncestor</code> then what level of ancestor (if there are two same type of parent in <code>visual tree</code>)</p>\n\n<pre><code>RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}\n</code></pre>\n\n<blockquote>\n <p>Above are all use-cases for <strong><em><code>RelativeSource binding</code></em></strong>.</p>\n</blockquote>\n\n<p><strong><em><a href=\"http://www.nbdtech.com/Free/WpfBinding.pdf\" rel=\"noreferrer\">Here is a reference link</a>.</em></strong></p>\n" }, { "answer_id": 38654107, "author": "Kevin VDF", "author_id": 6653298, "author_profile": "https://Stackoverflow.com/users/6653298", "pm_score": 3, "selected": false, "text": "<p>I didn't read every answer, but I just want to add this information in case of relative source command binding of a button.</p>\n\n<p>When you use a relative source with <code>Mode=FindAncestor</code>, the binding must be like:</p>\n\n<pre><code>Command=\"{Binding Path=DataContext.CommandProperty, RelativeSource={...}}\"\n</code></pre>\n\n<p>If you don't add DataContext in your path, at execution time it can't retrieve the property.</p>\n" }, { "answer_id": 46053079, "author": "Contango", "author_id": 107409, "author_profile": "https://Stackoverflow.com/users/107409", "pm_score": 3, "selected": false, "text": "<p>If an element is not part of the visual tree, then RelativeSource will never work.</p>\n<p>In this case, you need to try a different technique, pioneered by Thomas Levesque.</p>\n<p>He has the solution on his blog under <a href=\"http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/\" rel=\"noreferrer\">[WPF] How to bind to data when the DataContext is not inherited</a>. And it works absolutely brilliantly!</p>\n<p>In the unlikely event that his blog is down, Appendix A contains a mirror copy of <a href=\"http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/\" rel=\"noreferrer\">his article</a>.</p>\n<p><em>Please do not comment here, please <a href=\"http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/\" rel=\"noreferrer\">comment directly on his blog post</a>.</em></p>\n<h1>Appendix A: Mirror of blog post</h1>\n<p>The DataContext property in WPF is extremely handy, because it is automatically inherited by all children of the element where you assign it; therefore you don’t need to set it again on each element you want to bind. However, in some cases the DataContext is not accessible: it happens for elements that are not part of the visual or logical tree. It can be very difficult then to bind a property on those elements…</p>\n<p>Let’s illustrate with a simple example: we want to display a list of products in a DataGrid. In the grid, we want to be able to show or hide the Price column, based on the value of a ShowPrice property exposed by the ViewModel. The obvious approach is to bind the Visibility of the column to the ShowPrice property:</p>\n<pre><code>&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;\n Visibility=&quot;{Binding ShowPrice,\n Converter={StaticResource visibilityConverter}}&quot;/&gt;\n</code></pre>\n<p>Unfortunately, changing the value of ShowPrice has no effect, and the column is always visible… why? If we look at the Output window in Visual Studio, we notice the following line:</p>\n<blockquote>\n<p>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=ShowPrice; DataItem=null; target element is ‘DataGridTextColumn’ (HashCode=32685253); target property is ‘Visibility’ (type ‘Visibility’)</p>\n<p>The message is rather cryptic, but the meaning is actually quite simple: WPF doesn’t know which FrameworkElement to use to get the DataContext, because the column doesn’t belong to the visual or logical tree of the DataGrid.</p>\n</blockquote>\n<p>We can try to tweak the binding to get the desired result, for instance by setting the RelativeSource to the DataGrid itself:</p>\n<pre><code>&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;\n Visibility=&quot;{Binding DataContext.ShowPrice,\n Converter={StaticResource visibilityConverter},\n RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}&quot;/&gt;\n</code></pre>\n<p>Or we can add a CheckBox bound to ShowPrice, and try to bind the column visibility to the IsChecked property by specifying the element name:</p>\n<pre><code>&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;\n Visibility=&quot;{Binding IsChecked,\n Converter={StaticResource visibilityConverter},\n ElementName=chkShowPrice}&quot;/&gt;\n</code></pre>\n<p>But none of these workarounds seems to work, we always get the same result…</p>\n<p>At this point, it seems that the only viable approach would be to change the column visibility in code-behind, which we usually prefer to avoid when using the MVVM pattern… But I’m not going to give up so soon, at least not while there are other options to consider </p>\n<p>The solution to our problem is actually quite simple, and takes advantage of the Freezable class. The primary purpose of this class is to define objects that have a modifiable and a read-only state, but the interesting feature in our case is that Freezable objects can inherit the DataContext even when they’re not in the visual or logical tree. I don’t know the exact mechanism that enables this behavior, but we’re going to take advantage of it to make our binding work…</p>\n<p>The idea is to create a class (I called it BindingProxy for reasons that should become obvious very soon) that inherits Freezable and declares a Data dependency property:</p>\n<pre><code>public class BindingProxy : Freezable\n{\n #region Overrides of Freezable\n \n protected override Freezable CreateInstanceCore()\n {\n return new BindingProxy();\n }\n \n #endregion\n \n public object Data\n {\n get { return (object)GetValue(DataProperty); }\n set { SetValue(DataProperty, value); }\n }\n \n // Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty DataProperty =\n DependencyProperty.Register(&quot;Data&quot;, typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));\n}\n</code></pre>\n<p>We can then declare an instance of this class in the resources of the DataGrid, and bind the Data property to the current DataContext:</p>\n<pre><code>&lt;DataGrid.Resources&gt;\n &lt;local:BindingProxy x:Key=&quot;proxy&quot; Data=&quot;{Binding}&quot; /&gt;\n&lt;/DataGrid.Resources&gt;\n</code></pre>\n<p>The last step is to specify this BindingProxy object (easily accessible with StaticResource) as the Source for the binding:</p>\n<pre><code>&lt;DataGridTextColumn Header=&quot;Price&quot; Binding=&quot;{Binding Price}&quot; IsReadOnly=&quot;False&quot;\n Visibility=&quot;{Binding Data.ShowPrice,\n Converter={StaticResource visibilityConverter},\n Source={StaticResource proxy}}&quot;/&gt;\n</code></pre>\n<p>Note that the binding path has been prefixed with “Data”, since the path is now relative to the BindingProxy object.</p>\n<p>The binding now works correctly, and the column is properly shown or hidden based on the ShowPrice property.</p>\n" }, { "answer_id": 67119194, "author": "james.lee", "author_id": 9438258, "author_profile": "https://Stackoverflow.com/users/9438258", "pm_score": 4, "selected": false, "text": "<p><strong>I am constantly updating my research on Binding.</strong></p>\n<p> Original <a href=\"https://github.com/devncore/wpf-xaml-binding\" rel=\"noreferrer\">Here</a></p>\n<h2>DataContext</h2>\n<p><strong>DataContext is the DependencyProperty included in the FrameworkElement.</strong><br />\n<code>PresentationFramework.dll</code></p>\n<pre class=\"lang-cs prettyprint-override\"><code>namespace System.Windows\n{\n public class FrameworkElement : UIElement\n {\n public static readonly DependencyProperty DataContextProperty;\n public object DataContext { get; set; }\n }\n}\n</code></pre>\n<p>And, all UI Controls in WPF inherit the <code>FrameworkElement</code> class.</p>\n<blockquote>\n<p>At this point in learning Binding or DataContext, you don't have to study FrameworkElement in greater depth.<br />\nHowever, this is to briefly mention the fact that the closest object that can encompass all UI Controls is the FrameworkElement.<br />\n<br /></p>\n</blockquote>\n<h3><em>DataContext is always the reference point for Binding.</em></h3>\n<p>Binding can directly recall values for the DataContext type format starting with the nearest DataContext.</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding}&quot; DataContext=&quot;James&quot;/&gt;\n</code></pre>\n<p>The value bound to <code>Text=&quot;{Binding}&quot;</code> is passed directly from the nearest DataContext, <code>TextBlock</code>.<br />\nTherefore, the Binding result value of <code>Text</code> is 'James'.<br />\n<br /></p>\n<ul>\n<li><p><strong>Type integer</strong><br />\nWhen assigning a value to DataContext directly from Xaml, resource definitions are required first for value types such as Integer and Boolean.\nBecause all strings are recognized as String.</p>\n1. Using System <code>mscrolib</code> in Xaml\n<blockquote>\n<p>Simple type variable type is not supported by standard.<br />\nYou can define it with any word, but mostly use <code>sys</code> words.</p>\n</blockquote>\n<pre class=\"lang-xml prettyprint-override\"><code>xmlns:sys=&quot;clr-namespace:System;assembly=mscorlib&quot;\n</code></pre>\n2. Create <code>YEAR</code> resource key in xaml\n<blockquote>\n<p>Declare the value of the type you want to create in the form of a StaticResource.</p>\n</blockquote>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window.Resources&gt;\n &lt;sys:Int32 x:Key=&quot;YEAR&quot;&gt;2020&lt;/sys:Int32&gt;\n&lt;/Window.Resources&gt;\n...\n&lt;TextBlock Text=&quot;{Binding}&quot; DataContext=&quot;{StaticResource YEAR&quot;/&gt;\n</code></pre>\n</li>\n<li><p><strong>All type of value</strong><br />\nThere are very few cases where Value Type is binding directly into DataContext.<br />\nBecause we're going to bind an object.</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window.Resources&gt;\n &lt;sys:Boolean x:Key=&quot;IsEnabled&quot;&gt;true&lt;/sys:Boolean&gt;\n &lt;sys:double x:Key=&quot;Price&quot;&gt;7.77&lt;/sys:double&gt;\n&lt;/Window.Resources&gt;\n...\n&lt;StackPanel&gt;\n &lt;TextBlock Text=&quot;{Binding}&quot; DataContext=&quot;{StaticResource IsEnabled}&quot;/&gt;\n &lt;TextBlock Text=&quot;{Binding}&quot; DataContext=&quot;{StaticResource Price}&quot;/&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n</li>\n<li><p><strong>Another type</strong><br />\nNot only String but also various types are possible. Because DataContext is an object type.\n<br /></p>\n</li>\n</ul>\n<h3>Finally...</h3>\n<p>In using Binding at WPF, most developers are not fully aware of the existence, function and importance of DataContext.<br />\nIt may mean that Binding is being connected by luck.</p>\n<blockquote>\n<p><strong>Especially if you are responsible for or participating in a large WPF project, you should understand the DataContext hierarchy of the application more clearly. In addition, the introduction of WPF's various popular MVVM Framework systems without this DataContext concept will create even greater limitations in implementing functions freely.</strong>\n<br /></p>\n</blockquote>\n<hr />\n<h2>Binding</h2>\n<ul>\n<li>DataContext Binding</li>\n<li>Element Binding</li>\n<li>MultiBinding</li>\n<li>Self Property Binding</li>\n<li>Find Ancestor Binding</li>\n<li>TemplatedParent Binding</li>\n<li>Static Property Binding<br />\n<br /></li>\n</ul>\n<h3>DataContext Binding</h3>\n<p><code>string property</code></p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBox Text=&quot;{Binding Keywords}&quot;/&gt;\n</code></pre>\n<br />\n<h3>Element Binding</h3>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;CheckBox x:Name=&quot;usingEmail&quot;/&gt;\n&lt;TextBlock Text=&quot;{Binding ElementName=usingEmail, Path=IsChecked}&quot;/&gt;\n</code></pre>\n<br />\n<h3>MultiBinding</h3>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Margin=&quot;5,2&quot; Text=&quot;This disappears as the control gets focus...&quot;&gt;\n &lt;TextBlock.Visibility&gt;\n &lt;MultiBinding Converter=&quot;{StaticResource TextInputToVisibilityConverter}&quot;&gt;\n &lt;Binding ElementName=&quot;txtUserEntry2&quot; Path=&quot;Text.IsEmpty&quot; /&gt;\n &lt;Binding ElementName=&quot;txtUserEntry2&quot; Path=&quot;IsFocused&quot; /&gt;\n &lt;/MultiBinding&gt;\n &lt;/TextBlock.Visibility&gt;\n&lt;/TextBlock&gt;\n</code></pre>\n<br />\n \n### Self Property Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock x:Name=&quot;txt&quot; Text=&quot;{Binding ElementName=txt, Path=Tag}&quot;/&gt;\n</code></pre>\n<p>If you have to bind your own property, you can use <code>Self Property Binding</code>, instead of using <code>Element Binding</code>.<br />\nYou no longer have to declare <code>x:Name</code> to bind your own property.</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource Self}, Path=Tag}&quot;/&gt;\n</code></pre>\n<br />\n \n### Find Ancestor Binding\nImports based on the parent control closest to it.\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Title}&quot;/&gt;\n</code></pre>\n<p>In addition to the properties of the controls found, the properties within the DataContext object can be used if it exists.</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.Email}&quot;/&gt;\n</code></pre>\n<br />\n<h3>TemplatedParent Binding</h3>\n<p>This is a method that can be used within <code>ControlTemplate</code>, and you can import the control that is the owner of the <code>ControlTemplate</code>.</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Style TargetType=&quot;Button&quot;&gt;\n &lt;Setter Property=&quot;Template&quot;&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=&quot;Button&quot;&gt;\n &lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}&quot;/&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n</code></pre>\n<p>You can access to all Property and DataContext.</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}&quot;/&gt;\n</code></pre>\n<br />\n<h3>Static Property Binding</h3>\n<p>You can access binding property value directly.</p>\n1. Declare <code>static</code> property.\n<pre class=\"lang-cs prettyprint-override\"><code>namespace Exam\n{\n public class ExamClass\n {\n public static string ExamText { get; set; }\n }\n} \n</code></pre>\n2. Using static class in XAML.\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window ... xmlns:exam=&quot;clr-namespace:Exam&quot;&gt;\n</code></pre>\n3. Binding property.\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding exam:ExamClass.ExamText}&quot;/&gt;\n</code></pre>\n<p><em>Or, you can set Resource key like using <code>Converter</code>.</em></p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window.Resource&gt;\n &lt;cvt:VisibilityToBooleanConverter x:Key=&quot;VisibilityToBooleanConverter&quot;/&gt;\n &lt;exam:ExamClass x:Key=&quot;ExamClass&quot;&gt;\n&lt;/Window.Resource&gt;\n...\n\n&lt;TextBlock Text=&quot;{Binding Source={StaticResource ExamClass}, Path=ExamText}&quot;/&gt;\n</code></pre>\n<blockquote>\n<p>I have never used the Static Property under normal circumstances. This is because data that deviates from its own DataContext can disrupt the flow of whole WPF applications and impair readability significantly. However, this method is actively used in the development stage to implement fast testing and functions, as well as in the DataContext (or ViewModel).<br />\n<br /></p>\n</blockquote>\n<hr />\n<h2>Bad Binding &amp; Good Binding</h2>\n<h3>✔️ If the property you want to bind is included in Datacontext, <br />       you don't have to use ElementBinding.</h3>\n<p>      <em>Using ElementBinding through connected control is not a functional problem,<br />\n      but it breaks the fundamental pattern of Binding.</em></p>\n Bad Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBox x:Name=&quot;text&quot; Text=&quot;{Binding UserName}&quot;/&gt;\n...\n&lt;TextBlock Text=&quot;{Binding ElementName=text, Path=Text}&quot;/&gt;\n</code></pre>\n Good Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBox Text=&quot;{Binding UserName}&quot;/&gt;\n...\n&lt;TextBlock Text=&quot;{Binding UserName}&quot;/&gt;\n</code></pre>\n<br />\n<h3>✔️ Do not use ElementBinding when using property belonging to higher layers control.</h3>\n Bad Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window x:Name=&quot;win&quot;&gt;\n &lt;TextBlock Text=&quot;{Binding ElementName=win, Path=DataContext.UserName}&quot;/&gt;\n ...\n</code></pre>\n Good Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window&gt;\n &lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.UserName}&quot;/&gt;\n ...\n</code></pre>\n Great!\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Window&gt;\n &lt;TextBlock DataContext=&quot;{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext}&quot; \n Text=&quot;{Binding UserName}&quot;/&gt;\n ...\n</code></pre>\n<br />\n<h3>✔️ Do not use ElementBinding when using your own properties.</h3>\n Bad Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock x:Name=&quot;txt&quot; Text=&quot;{Binding ElementName=txt, Path=Foreground}&quot;/&gt;\n</code></pre>\n Good Binding\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;TextBlock Text=&quot;{Binding RelativeSource={RelativeSource Self}, Path=Foreground}&quot;/&gt;\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4918/" ]
How do I use `RelativeSource` with WPF bindings and what are the different use-cases?
If you want to bind to another property on the object: ``` {Binding Path=PathToProperty, RelativeSource={RelativeSource Self}} ``` If you want to get a property on an ancestor: ``` {Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}} ``` If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate) ``` {Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}} ``` or, shorter (this only works for OneWay bindings): ``` {TemplateBinding Path=PathToProperty} ```
84,290
<p>How do I get a a complete list of all the urls that my rails application could generate? </p> <p>I don't want the routes that I get get form rake routes, instead I want to get the actul URLs corrosponding to all the dynmically generated pages in my application...</p> <p>Is this even possible?</p> <p>(Background: I'm doing this because I want a complete list of URLs for some load testing I want to do, which has to cover the entire breadth of the application)</p>
[ { "answer_id": 84482, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 1, "selected": false, "text": "<p>You could pretty quickly hack together a program that grabs the output of <code>rake routes</code> and then parses the output to put together a list of the URLs.</p>\n\n<p>What I have, typically, done for load testing is to use a tool like <a href=\"http://webload.org\" rel=\"nofollow noreferrer\">WebLOAD</a> and script several different types of user sessions (or different routes users can take). Then I create a mix of user sessions and run them through the website to get something close to an accurate picture of how the site might run.</p>\n\n<p>Typically I will also do this on a total of 4 different machines running about 80 concurrent user sessions to realistically simulate what will be happening through the application. This also makes sure I don't spend overly much time optimizing infrequently visited pages and can, instead, concentrate on overall application performance along the critical paths.</p>\n" }, { "answer_id": 90868, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 4, "selected": true, "text": "<p>I was able to produce useful output with the following command:</p>\n\n<pre><code>$ wget --spider -r -nv -nd -np http://localhost:3209/ 2&gt;&amp;1 | ack -o '(?&lt;=URL:)\\S+'\nhttp://localhost:3209/\nhttp://localhost:3209/robots.txt\nhttp://localhost:3209/agenda/2008/08\nhttp://localhost:3209/agenda/2008/10\nhttp://localhost:3209/agenda/2008/09/01\nhttp://localhost:3209/agenda/2008/09/02\nhttp://localhost:3209/agenda/2008/09/03\n^C\n</code></pre>\n\n<h3>A quick reference of the <code>wget</code> arguments:</h3>\n\n<pre><code># --spider don't download anything.\n# -r, --recursive specify recursive download.\n# -nv, --no-verbose turn off verboseness, without being quiet.\n# -nd, --no-directories don't create directories.\n# -np, --no-parent don't ascend to the parent directory.\n</code></pre>\n\n<h3>About <code>ack</code></h3>\n\n<p><code>ack</code> is like <code>grep</code> but use <code>perl</code> regexps, which are more complete/powerful.</p>\n\n<p><code>-o</code> tells <code>ack</code> to only output the matched substring, and the pattern I used looks for anything non-space preceded by <code>'URL:'</code></p>\n" }, { "answer_id": 9914736, "author": "heavysixer", "author_id": 151430, "author_profile": "https://Stackoverflow.com/users/151430", "pm_score": 0, "selected": false, "text": "<p>Check out the Spider Integration Tests written By Courtnay Gasking</p>\n\n<p><a href=\"http://pronetos.googlecode.com/svn/trunk/vendor/plugins/spider_test/doc/classes/Caboose/SpiderIntegrator.html\" rel=\"nofollow\">http://pronetos.googlecode.com/svn/trunk/vendor/plugins/spider_test/doc/classes/Caboose/SpiderIntegrator.html</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
How do I get a a complete list of all the urls that my rails application could generate? I don't want the routes that I get get form rake routes, instead I want to get the actul URLs corrosponding to all the dynmically generated pages in my application... Is this even possible? (Background: I'm doing this because I want a complete list of URLs for some load testing I want to do, which has to cover the entire breadth of the application)
I was able to produce useful output with the following command: ``` $ wget --spider -r -nv -nd -np http://localhost:3209/ 2>&1 | ack -o '(?<=URL:)\S+' http://localhost:3209/ http://localhost:3209/robots.txt http://localhost:3209/agenda/2008/08 http://localhost:3209/agenda/2008/10 http://localhost:3209/agenda/2008/09/01 http://localhost:3209/agenda/2008/09/02 http://localhost:3209/agenda/2008/09/03 ^C ``` ### A quick reference of the `wget` arguments: ``` # --spider don't download anything. # -r, --recursive specify recursive download. # -nv, --no-verbose turn off verboseness, without being quiet. # -nd, --no-directories don't create directories. # -np, --no-parent don't ascend to the parent directory. ``` ### About `ack` `ack` is like `grep` but use `perl` regexps, which are more complete/powerful. `-o` tells `ack` to only output the matched substring, and the pattern I used looks for anything non-space preceded by `'URL:'`
84,310
<p>I'm connecting to an AS/400 stored procedure layer using the IBM iSeries Access for Windows package. This provides a .NET DLL with classes similar to those in the <code>System.Data</code> namespace. As such we use their implementation of the connection class and provide it with a connection string.</p> <p>Does anyone know how I can amend the connection string to indicate the default library it should use?</p>
[ { "answer_id": 84374, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "<p>Are you using the Catalog Library List parameter for OLE DB? This is what my connection string typically looks like:</p>\n\n<pre><code>&lt;add name=\"AS400ConnectionString\" connectionString=\"Data Source=DEVL820;Initial Catalog=Q1A_DATABASE_SRVR;Persist Security Info=False;User ID=BLAH;Password=BLAHBLAH;Provider=IBMDASQL.DataSource.1;**Catalog Library List=&amp;quot;HTSUTST, HTEUSRJ, HTEDTA&amp;quot;**\" providerName=\"System.Data.OleDb\" /&gt;\n</code></pre>\n" }, { "answer_id": 84854, "author": "CrashCodes", "author_id": 16260, "author_profile": "https://Stackoverflow.com/users/16260", "pm_score": 2, "selected": false, "text": "<p>Snippet from some Delphi source code using the Client Access Express Driver. Probably not exactly what you are looking for, but it may help others that stumble upon this post. <strong>The <code>DBQ</code> part is the default library, and the <code>System</code> part is the AS400/DB2 host name.</strong></p>\n\n<pre><code>ConnectionString :=\n 'Driver={Client Access ODBC Driver (32-bit)};' +\n 'System=' + System + ';' +\n 'DBQ=' + Lib + ';' +\n 'TRANSLATE=1;' +\n 'CMT=0;' +\n //'DESC=Client Access Express ODBC data source;' +\n 'QAQQINILIB=;' +\n 'PKG=QGPL/DEFAULT(IBM),2,0,1,0,512;' + \n 'SORTTABLE=;' +\n 'LANGUAGEID=ENU;' +\n 'XLATEDLL=;' +\n 'DFTPKGLIB=QGPL;';\n</code></pre>\n" }, { "answer_id": 97858, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 2, "selected": false, "text": "<p>If you are connecting <strong>through .NET</strong>:</p>\n\n<pre><code>Provider=IBMDA400;Data Source=as400.com;User Id=user;Password=password;Default Collection=yourLibrary;\n</code></pre>\n\n<p><strong><em>Default Collection</em></strong> is the parameter that sets the library where your programs should start executing.</p>\n\n<p>And if you are connecting <strong>through ODBC from Windows</strong> (like setting up a driver in the control panel):</p>\n\n<pre><code>DRIVER=Client Access ODBC Driver(32-bit);SYSTEM=as400.com;EXTCOLINFO=1;UID=user;PWD=password;LibraryList=yourLibrary\n</code></pre>\n\n<p>In this case <strong><em>LibraryList</em></strong> is the parameter to set, remember this is for ODBC connection.</p>\n\n<p>There are two drivers from IBM to connect to the AS400, the older one uses the above connection string, if you have the newest version of the client software from IBM called \"System i Access for Windows\" then you should use this connection string:</p>\n\n<pre><code>DRIVER=iSeries Access ODBC Driver;SYSTEM=as400.com;EXTCOLINFO=1;UID=user;PWD=password;LibraryList=yourLibrary\n</code></pre>\n\n<p>The last is pretty much the same, only the <strong><em>DRIVER</em></strong> parameter value changes.</p>\n\n<p>If you are using this in a .NET application don't forget to add the <strong><em>providerName</em></strong> parameter to your XML tag and define the API used for connecting which would be OleDb in this case:</p>\n\n<pre><code>providerName=\"System.Data.OleDb\"\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277/" ]
I'm connecting to an AS/400 stored procedure layer using the IBM iSeries Access for Windows package. This provides a .NET DLL with classes similar to those in the `System.Data` namespace. As such we use their implementation of the connection class and provide it with a connection string. Does anyone know how I can amend the connection string to indicate the default library it should use?
Snippet from some Delphi source code using the Client Access Express Driver. Probably not exactly what you are looking for, but it may help others that stumble upon this post. **The `DBQ` part is the default library, and the `System` part is the AS400/DB2 host name.** ``` ConnectionString := 'Driver={Client Access ODBC Driver (32-bit)};' + 'System=' + System + ';' + 'DBQ=' + Lib + ';' + 'TRANSLATE=1;' + 'CMT=0;' + //'DESC=Client Access Express ODBC data source;' + 'QAQQINILIB=;' + 'PKG=QGPL/DEFAULT(IBM),2,0,1,0,512;' + 'SORTTABLE=;' + 'LANGUAGEID=ENU;' + 'XLATEDLL=;' + 'DFTPKGLIB=QGPL;'; ```
84,322
<p>It appears that using perldoc perl gives the list of, e.g. perlre, perlvar, etc.</p> <p>Is this the best place to find the list of what's available as an overview or tutorial or reference manual section? Is there another, better list?</p>
[ { "answer_id": 84367, "author": "szabgab", "author_id": 11827, "author_profile": "https://Stackoverflow.com/users/11827", "pm_score": 1, "selected": false, "text": "<p>See also <a href=\"https://stackoverflow.com/questions/70573/best-online-source-to-learn-perl\">best online source to learn perl</a></p>\n\n<p>Specifically for perldoc, you can also view the content online which might be easier on the eyes: <a href=\"http://perldoc.perl.org/\" rel=\"nofollow noreferrer\">perldoc online</a></p>\n" }, { "answer_id": 84417, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 4, "selected": true, "text": "<pre><code>perldoc perltoc\n</code></pre>\n\n<p>is a bit more verbose about the various documentation files. If you want a list of core modules, try</p>\n\n<pre><code>perldoc perlmodlib\n</code></pre>\n" }, { "answer_id": 84863, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 0, "selected": false, "text": "<p>That should be a good start. You can also find the same information online: <a href=\"http://perldoc.perl.org/perl.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/perl.html</a>. </p>\n\n<p>I'm not sure what you mean by better. There's a ton of good information at <a href=\"http://www.perl.com/\" rel=\"nofollow noreferrer\">http://www.perl.com/</a> as well.</p>\n" }, { "answer_id": 85146, "author": "Offer Kaye", "author_id": 16368, "author_profile": "https://Stackoverflow.com/users/16368", "pm_score": 1, "selected": false, "text": "<p>I think \"perldoc perltoc\" is too verbose for just finding the list of \"perlxxx\" subjects. Instead use \"perldoc perl\". Or <a href=\"http://perldoc.perl.org/perl.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/perl.html</a>, which is the online version.</p>\n" }, { "answer_id": 91327, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 1, "selected": false, "text": "<p>A more friendly starting place, with links to just a select few of the other perlxxx pages, is <a href=\"http://perldoc.perl.org/perlintro.html\" rel=\"nofollow noreferrer\">perldoc perlintro</a>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8763/" ]
It appears that using perldoc perl gives the list of, e.g. perlre, perlvar, etc. Is this the best place to find the list of what's available as an overview or tutorial or reference manual section? Is there another, better list?
``` perldoc perltoc ``` is a bit more verbose about the various documentation files. If you want a list of core modules, try ``` perldoc perlmodlib ```
84,330
<p><strong>Here is the updated question:</strong></p> <p>the current query is doing something like:<br></p> <pre><code>$sql1 = "TRUNCATE TABLE fubar"; $sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu"; </code></pre> <p>The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.</p> <p>Is my only option to do the <code>CREATE TABLE</code>, run the <code>TRUNCATE TABLE</code>, and then fill the table? (3 separate queries)</p> <p><strong>original question was:</strong></p> <p> I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:</p> <pre><code>CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar </code></pre> <p>If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.</p> <p>This code will be executed using PHP.</p>
[ { "answer_id": 84396, "author": "Ben", "author_id": 11522, "author_profile": "https://Stackoverflow.com/users/11522", "pm_score": 2, "selected": false, "text": "<p>how about:</p>\n\n<pre><code>DROP TABLE IF EXISTS fubar;\nCREATE TABLE fubar;\n</code></pre>\n\n<p>Or did you mean you just want to do it with a single query?</p>\n" }, { "answer_id": 84405, "author": "Mark Janssen", "author_id": 15828, "author_profile": "https://Stackoverflow.com/users/15828", "pm_score": 2, "selected": false, "text": "<p>You could do the truncate after the 'create if not exists'.\nThat way it will always exist... and always be empty at that point.</p>\n\n<pre><code>CREATE TABLE fubar IF NOT EXISTS\nTRUNCATE TABLE fubar\n</code></pre>\n" }, { "answer_id": 84508, "author": "shmuel613", "author_id": 16186, "author_profile": "https://Stackoverflow.com/users/16186", "pm_score": 0, "selected": false, "text": "<p>OK then, not bad. To be more specific, the current query is doing something like:</p>\n\n<pre>\n$sql1 = \"TRUNCATE TABLE fubar\";\n$sql2 = \"CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu\";\n</pre>\n\n<p>The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.</p>\n\n<p>Is my only option to do the \"CREATE TABLE\", run the \"TRUNCATE TABLE\", and then fill the table? (3 separate queries)</p>\n\n<p>PS - thanks for responding so quickly!</p>\n" }, { "answer_id": 85475, "author": "mdahlman", "author_id": 8373, "author_profile": "https://Stackoverflow.com/users/8373", "pm_score": 6, "selected": true, "text": "<p>shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.</p>\n\n<p>Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it <strong>doesn't</strong> exist isn't quite right.</p>\n\n<p>You will indeed need multiple statements. Either conditionally create then populate:</p>\n\n<ol>\n<li>CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) )</li>\n<li>TRUNCATE TABLE fubar</li>\n<li>INSERT INTO fubar SELECT * FROM barfu</li>\n</ol>\n\n<p>or just drop and recreate</p>\n\n<ol>\n<li>DROP TABLE IF EXISTS fubar</li>\n<li>CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu</li>\n</ol>\n\n<p>With pure SQL those are your two real classes of solutions. I like the second better.</p>\n\n<p>(With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)</p>\n" }, { "answer_id": 1666567, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>execute any query if table exists.</p>\n\n<p>Usage: <code>call Edit_table(database-name,table-name,query-string);</code></p>\n\n<ul>\n<li>Procedure will check for existence of table-name under database-name and will execute query-string if it exists.\nFollowing is the stored procedure:</li>\n</ul>\n\n<blockquote>\n<pre><code>DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `Edit_table` $$\nCREATE PROCEDURE `Edit_table` (in_db_nm varchar(20), in_tbl_nm varchar(20), in_your_query varchar(200))\nDETERMINISTIC\nBEGIN\n\nDECLARE var_table_count INT;\n\nselect count(*) INTO @var_table_count from information_schema.TABLES where TABLE_NAME=in_tbl_nm and TABLE_SCHEMA=in_db_nm;\nIF (@var_table_count &gt; 0) THEN\n SET @in_your_query = in_your_query;\n #SELECT @in_your_query;\n PREPARE my_query FROM @in_your_query;\n EXECUTE my_query;\n\nELSE\n select \"Table Not Found\";\nEND IF;\n\nEND $$\nDELIMITER ;\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://kedar.nitty-witty.com/miscpages/mysql-linux-articles.html\" rel=\"nofollow noreferrer\">More on Mysql</a></p>\n" }, { "answer_id": 1666605, "author": "Lastnico", "author_id": 201554, "author_profile": "https://Stackoverflow.com/users/201554", "pm_score": 0, "selected": false, "text": "<p>If you're using PHP, use <a href=\"http://www.php.net/manual/en/function.mysql-list-tables.php\" rel=\"nofollow noreferrer\">mysql_list_tables</a> to check that the table exists before TRUNCATE it.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16186/" ]
**Here is the updated question:** the current query is doing something like: ``` $sql1 = "TRUNCATE TABLE fubar"; $sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu"; ``` The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet. Is my only option to do the `CREATE TABLE`, run the `TRUNCATE TABLE`, and then fill the table? (3 separate queries) **original question was:** I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql: ``` CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar ``` If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries. This code will be executed using PHP.
shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion. Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it **doesn't** exist isn't quite right. You will indeed need multiple statements. Either conditionally create then populate: 1. CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) ) 2. TRUNCATE TABLE fubar 3. INSERT INTO fubar SELECT \* FROM barfu or just drop and recreate 1. DROP TABLE IF EXISTS fubar 2. CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu With pure SQL those are your two real classes of solutions. I like the second better. (With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)
84,331
<p>Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003?</p> <p>I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.).</p> <p><strong>Sample data</strong></p> <pre><code>Date - Project - ID - Engineer 8/2/08 - XYZ - T0908-5555 - JS 9/4/08 - ABC - T0908-6666 - DF 9/5/08 - ZZZ - T0908-7777 - TS </code></pre> <p>It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly.</p>
[ { "answer_id": 84430, "author": "RickL", "author_id": 7261, "author_profile": "https://Stackoverflow.com/users/7261", "pm_score": -1, "selected": false, "text": "<p>If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?</p>\n" }, { "answer_id": 84526, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": 0, "selected": false, "text": "<p>This is partially pseudocode, but you will want something like:\n<br><br></p>\n\n<pre><code>rows = ActiveSheet.UsedRange.Rows\nn = 0\n\nwhile n &lt;= rows\n if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value &gt; '8/1/08' AND &lt; '8/30/08' then\n ActiveSheet.Rows(n).CopyTo(DestinationSheet)\n endif\n n = n + 1\nwend\n</code></pre>\n" }, { "answer_id": 84614, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": 3, "selected": false, "text": "<p>This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.</p>\n\n<p>You may want to add logic to sort your monthly data after it's all been copied</p>\n\n<pre><code>Public Sub MoveData(MonthNumber As Integer, SheetName As String)\n\nDim sharePoint As Worksheet\nDim Month As Worksheet\nDim spRange As Range\nDim cell As Range\n\nSet sharePoint = Sheets(\"Sharepoint\")\nSet Month = Sheets(SheetName)\nSet spRange = sharePoint.Range(\"A2\")\nSet spRange = sharePoint.Range(\"A2:\" &amp; spRange.End(xlDown).Address)\nFor Each cell In spRange\n If Format(cell.Value, \"MM\") = MonthNumber Then\n copyRowTo sharePoint.Range(cell.Row &amp; \":\" &amp; cell.Row), Month\n End If\nNext cell\n\nEnd Sub\n\nSub copyRowTo(rng As Range, ws As Worksheet)\n Dim newRange As Range\n Set newRange = ws.Range(\"A1\")\n If newRange.Offset(1).Value &lt;&gt; \"\" Then\n Set newRange = newRange.End(xlDown).Offset(1)\n Else\n Set newRange = newRange.Offset(1)\n End If\n rng.Copy\n newRange.PasteSpecial (xlPasteAll)\nEnd Sub\n</code></pre>\n" }, { "answer_id": 87356, "author": "Jon Fournier", "author_id": 5106, "author_profile": "https://Stackoverflow.com/users/5106", "pm_score": 1, "selected": false, "text": "<p>Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:</p>\n\n<pre><code>Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)\n Const DateCol = \"A\" 'column where dates are store\n Const DestCol = \"A\" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet\n Const FirstRow = 2 'first row where date data is stored\n 'Copy range of values to Dates array\n Dates = FromSheet.Range(DateCol &amp; CStr(FirstRow) &amp; \":\" &amp; DateCol &amp; CStr(FromSheet.Range(DateCol &amp; CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value\n Dim i As Integer\n For i = LBound(Dates) To UBound(Dates)\n If IsDate(Dates(i, 1)) Then\n If Month(CDate(Dates(i, 1))) = MonthNum Then\n Dim CurrRow As Long\n 'get the current row number in the worksheet\n CurrRow = FirstRow + i - 1\n Dim DestRow As Long\n 'get the destination row\n DestRow = ToSheet.Range(DestCol &amp; CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1\n 'copy row CurrRow in FromSheet to row DestRow in ToSheet\n FromSheet.Range(CStr(CurrRow) &amp; \":\" &amp; CStr(CurrRow)).Copy ToSheet.Range(DestCol &amp; CStr(DestRow))\n End If\n End If\n Next i\nEnd Sub\n</code></pre>\n" }, { "answer_id": 94282, "author": "Robert Mearns", "author_id": 5050, "author_profile": "https://Stackoverflow.com/users/5050", "pm_score": 0, "selected": false, "text": "<p>The way I would do this manually is:</p>\n\n<ul>\n<li>Use Data - AutoFilter </li>\n<li>Apply a custom filter based on a date range</li>\n<li>Copy the filtered data to the relevant month sheet</li>\n<li>Repeat for every month</li>\n</ul>\n\n<p>Listed below is code to do this process via VBA. </p>\n\n<p>It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.</p>\n\n<pre><code> Sub SeperateData()\n\n Dim vMonthText As Variant\n Dim ExcelLastCell As Range\n Dim intMonth As Integer\n\n vMonthText = Array(\"January\", \"February\", \"March\", \"April\", \"May\", _\n \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\")\n\n ThisWorkbook.Worksheets(\"Sharepoint\").Select\n Range(\"A1\").Select\n\n RowCount = ThisWorkbook.Worksheets(\"Sharepoint\").UsedRange.Rows.Count\n'Forces excel to determine the last cell, Usually only done on save\n Set ExcelLastCell = ThisWorkbook.Worksheets(\"Sharepoint\"). _\n Cells.SpecialCells(xlLastCell)\n'Determines the last cell with data in it\n\n\n Selection.EntireColumn.Insert\n Range(\"A1\").FormulaR1C1 = \"Month No.\"\n Range(\"A2\").FormulaR1C1 = \"=MONTH(RC[1])\"\n Range(\"A2\").Select\n Selection.Copy\n Range(\"A3:A\" &amp; ExcelLastCell.Row).Select\n ActiveSheet.Paste\n Application.CutCopyMode = False\n Calculate\n 'Insert a helper column to determine the month number for the date\n\n For intMonth = 1 To 12\n Range(\"A1\").CurrentRegion.Select\n Selection.AutoFilter Field:=1, Criteria1:=\"\" &amp; intMonth\n Selection.Copy\n ThisWorkbook.Worksheets(\"\" &amp; vMonthText(intMonth - 1)).Select\n Range(\"A1\").Select\n ActiveSheet.Paste\n Columns(\"A:A\").Delete Shift:=xlToLeft\n Cells.Select\n Cells.EntireColumn.AutoFit\n Range(\"A1\").Select\n ThisWorkbook.Worksheets(\"Sharepoint\").Select\n Range(\"A1\").Select\n Application.CutCopyMode = False\n Next intMonth\n 'Filter the data to a particular month\n 'Convert the month number to text\n 'Copy the filtered data to the month sheet\n 'Delete the helper column\n 'Repeat for each month\n\n Selection.AutoFilter\n Columns(\"A:A\").Delete Shift:=xlToLeft\n 'Get rid of the auto-filter and delete the helper column\n\n End Sub\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003? I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.). **Sample data** ``` Date - Project - ID - Engineer 8/2/08 - XYZ - T0908-5555 - JS 9/4/08 - ABC - T0908-6666 - DF 9/5/08 - ZZZ - T0908-7777 - TS ``` It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly.
This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub. You may want to add logic to sort your monthly data after it's all been copied ``` Public Sub MoveData(MonthNumber As Integer, SheetName As String) Dim sharePoint As Worksheet Dim Month As Worksheet Dim spRange As Range Dim cell As Range Set sharePoint = Sheets("Sharepoint") Set Month = Sheets(SheetName) Set spRange = sharePoint.Range("A2") Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address) For Each cell In spRange If Format(cell.Value, "MM") = MonthNumber Then copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month End If Next cell End Sub Sub copyRowTo(rng As Range, ws As Worksheet) Dim newRange As Range Set newRange = ws.Range("A1") If newRange.Offset(1).Value <> "" Then Set newRange = newRange.End(xlDown).Offset(1) Else Set newRange = newRange.Offset(1) End If rng.Copy newRange.PasteSpecial (xlPasteAll) End Sub ```
84,341
<p>I have a core file generated on a remote system that I don't have direct access to. I also have local copies of the library files from the remote system, and the executable file for the crashing program.</p> <p>I'd like to analyse this core dump in gdb.</p> <p>For example:</p> <pre><code>gdb path/to/executable path/to/corefile </code></pre> <p>My libraries are in the current directory.</p> <p>In the past I've seen debuggers implement this by supplying the option "-p ." or "-p /=."; so my question is:</p> <p>How can I specify that libraries be loaded first from paths relative to my current directory when analysing a corefile in gdb?</p>
[ { "answer_id": 84546, "author": "Drew Frezell", "author_id": 10954, "author_profile": "https://Stackoverflow.com/users/10954", "pm_score": 7, "selected": true, "text": "<p>Start gdb without specifying the executable or core file, then type the following commands:</p>\n\n<pre><code>set solib-absolute-prefix ./usr\nfile path/to/executable\ncore-file path/to/corefile\n</code></pre>\n\n<p>You will need to make sure to mirror your library path exactly from the target system. The above is meant for debugging targets that don't match your host, that is why it's important to replicate your root filesystem structure containing your libraries.</p>\n\n<p>If you are remote debugging a server that is the same architecture and Linux/glibc version as your host, then you can do as <a href=\"https://stackoverflow.com/users/13956/fd\">fd</a> suggested:</p>\n\n<pre><code>set solib-search-path &lt;path&gt;\n</code></pre>\n\n<p>If you are trying to override some of the libraries, but not all then you can copy the target library directory structure into a temporary place and use the <code>solib-absolute-prefix</code> solution described above.</p>\n" }, { "answer_id": 84722, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 2, "selected": false, "text": "<p>I found this excerpt on <a href=\"http://developer.apple.com/documentation/DeveloperTools/gdb/gdb/gdb_16.html\" rel=\"nofollow noreferrer\">developer.apple.com</a></p>\n\n<blockquote>\n<pre><code>set solib-search-path path\n</code></pre>\n \n <p>If this variable is set, path is a\n colon-separated list of directories to\n search for shared libraries.\n <code>solib-search-path' is used after\n </code>solib-absolute-prefix' fails to\n locate the library, or if the path to\n the library is relative instead of\n absolute. If you want to use\n <code>solib-search-path' instead of\n </code>solib-absolute-prefix', be sure to\n set `solib-absolute-prefix' to a\n nonexistant directory to prevent GDB\n from finding your host's libraries.</p>\n</blockquote>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I don't think using the above setting prepends the directories I added, but it does seem to append them, so files missing from my current system are picked up in the paths I added. I guess setting the solib-absolute-prefix to something bogus and adding directories in the solib-search-path in the order I need might be a full solution.</p>\n" }, { "answer_id": 84778, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 2, "selected": false, "text": "<p>I'm not sure this is possible at all within gdb but then I'm no expert.</p>\n\n<p>However I can comment on the <em>Linux</em> dynamic linker. The following should print the path of all resolved shared libraries and the unresolved ones.</p>\n\n<pre><code>ldd path/to/executable\n</code></pre>\n\n<p>We need to know how your shared libraries were linked with your executable. To do this, use the following command:</p>\n\n<pre><code>readelf -d path/to/executable | grep RPATH\n</code></pre>\n\n<ul>\n<li><p>Should the command print nothing, the dynamic linker will use standard locations plus the LD_LIBRARY_PATH environment variable to find the shared libraries.</p></li>\n<li><p>If the command prints some lines, the dynamic linker will ignore LD_LIBRARY_PATH and use the hardcoded rpaths instead.</p>\n<p>If the listed rpaths are absolute, the only solution I know is to copy (or symlink) your libraries to the listed locations.</p>\n<p>If the listed rpaths are relative, they will contain a $ORIGIN which will be replaced at run time by the path of the executable. Move either the executable or the libraries to match.</p>\n</li>\n</ul>\n\n<p>For further informations, you could start with:</p>\n\n<pre><code>man ld.so\n</code></pre>\n" }, { "answer_id": 3293122, "author": "psihodelia", "author_id": 215571, "author_profile": "https://Stackoverflow.com/users/215571", "pm_score": 0, "selected": false, "text": "<p>One important note:</p>\n\n<p>if you're doing a cross compiling and trying to debug with gdb, then\nafter you've done <br><code>file ECECUTABLE_NAME</code> if you see smth. like :</p>\n\n<pre><code>Using host libthread_db library \"/lib/libthread_db.so.1\"\n</code></pre>\n\n<p>then check whether you have libthread_db for your target system. I found a lot of similar problems on the web. Such problem cannot be solved just using \"set solib-\", you has to build libthread_db using your cross-compiler as well.</p>\n" }, { "answer_id": 12693066, "author": "Joseph Garvin", "author_id": 50385, "author_profile": "https://Stackoverflow.com/users/50385", "pm_score": 2, "selected": false, "text": "<p>You can also just set LD_PRELOAD to each of the libraries or LD_LIBRARY_PATH to the current directory when invoking gdb. This will only cause problems if gdb itself tries to use any of the libraries you're preloading.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13956/" ]
I have a core file generated on a remote system that I don't have direct access to. I also have local copies of the library files from the remote system, and the executable file for the crashing program. I'd like to analyse this core dump in gdb. For example: ``` gdb path/to/executable path/to/corefile ``` My libraries are in the current directory. In the past I've seen debuggers implement this by supplying the option "-p ." or "-p /=."; so my question is: How can I specify that libraries be loaded first from paths relative to my current directory when analysing a corefile in gdb?
Start gdb without specifying the executable or core file, then type the following commands: ``` set solib-absolute-prefix ./usr file path/to/executable core-file path/to/corefile ``` You will need to make sure to mirror your library path exactly from the target system. The above is meant for debugging targets that don't match your host, that is why it's important to replicate your root filesystem structure containing your libraries. If you are remote debugging a server that is the same architecture and Linux/glibc version as your host, then you can do as [fd](https://stackoverflow.com/users/13956/fd) suggested: ``` set solib-search-path <path> ``` If you are trying to override some of the libraries, but not all then you can copy the target library directory structure into a temporary place and use the `solib-absolute-prefix` solution described above.
84,421
<p>Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?</p> <p>Something like the opposite of <a href="http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i" rel="noreferrer"><code>String#to_i</code></a>:</p> <pre><code>"0A".to_i(16) #=&gt;10 </code></pre> <p>Like perhaps:</p> <pre><code>"0A".hex #=&gt;10 </code></pre> <p>I know how to roll my own, but it's probably more efficient to use a built in Ruby function.</p>
[ { "answer_id": 84455, "author": "flxkid", "author_id": 13036, "author_profile": "https://Stackoverflow.com/users/13036", "pm_score": 6, "selected": false, "text": "<p>How about using <a href=\"http://ruby-doc.org/core-2.0.0/String.html#method-i-25\" rel=\"noreferrer\"><code>%</code></a>/<a href=\"http://ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf\" rel=\"noreferrer\"><code>sprintf</code></a>:</p>\n\n<pre><code>i = 20\n\"%x\" % i #=&gt; \"14\"\n</code></pre>\n" }, { "answer_id": 84485, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 9, "selected": true, "text": "<p>You can give <a href=\"http://www.ruby-doc.org/core/classes/Integer.html#method-i-to_s\" rel=\"noreferrer\"><code>to_s</code></a> a base other than 10:</p>\n\n<pre><code>10.to_s(16) #=&gt; \"a\"\n</code></pre>\n\n<p>Note that in ruby 2.4 <code>FixNum</code> and <code>BigNum</code> were unified in the <code>Integer</code> class. \nIf you are using an older ruby check the documentation of <a href=\"https://ruby-doc.org/core-2.3.8/Fixnum.html#method-i-to_s\" rel=\"noreferrer\">FixNum#<code>to_s</code></a> and <a href=\"https://ruby-doc.org/core-2.3.8/Bignum.html#method-i-to_s\" rel=\"noreferrer\">BigNum#<code>to_s</code></a></p>\n" }, { "answer_id": 5474985, "author": "Ultrasaurus", "author_id": 682349, "author_profile": "https://Stackoverflow.com/users/682349", "pm_score": 4, "selected": false, "text": "<p>Here's another approach:</p>\n\n<pre><code>sprintf(\"%02x\", 10).upcase\n</code></pre>\n\n<p>see the documentation for <code>sprintf</code> here: <a href=\"http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf\" rel=\"noreferrer\">http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf</a></p>\n" }, { "answer_id": 7882918, "author": "Lri", "author_id": 495470, "author_profile": "https://Stackoverflow.com/users/495470", "pm_score": 6, "selected": false, "text": "<p>To summarize:</p>\n\n<pre><code>p 10.to_s(16) #=&gt; \"a\"\np \"%x\" % 10 #=&gt; \"a\"\np \"%02X\" % 10 #=&gt; \"0A\"\np sprintf(\"%02X\", 10) #=&gt; \"0A\"\np \"#%02X%02X%02X\" % [255, 0, 10] #=&gt; \"#FF000A\"\n</code></pre>\n" }, { "answer_id": 23266744, "author": "tool maker", "author_id": 2895616, "author_profile": "https://Stackoverflow.com/users/2895616", "pm_score": 3, "selected": false, "text": "<p>Just in case you have a preference for how negative numbers are formatted:</p>\n\n<pre><code>p \"%x\" % -1 #=&gt; \"..f\"\np -1.to_s(16) #=&gt; \"-1\"\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6106/" ]
Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent? Something like the opposite of [`String#to_i`](http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i): ``` "0A".to_i(16) #=>10 ``` Like perhaps: ``` "0A".hex #=>10 ``` I know how to roll my own, but it's probably more efficient to use a built in Ruby function.
You can give [`to_s`](http://www.ruby-doc.org/core/classes/Integer.html#method-i-to_s) a base other than 10: ``` 10.to_s(16) #=> "a" ``` Note that in ruby 2.4 `FixNum` and `BigNum` were unified in the `Integer` class. If you are using an older ruby check the documentation of [FixNum#`to_s`](https://ruby-doc.org/core-2.3.8/Fixnum.html#method-i-to_s) and [BigNum#`to_s`](https://ruby-doc.org/core-2.3.8/Bignum.html#method-i-to_s)
84,427
<p>Specifically, is the following legal C++?</p> <pre>class A{}; void foo(A*); void bar(const A&); int main(void) { foo(&A()); // 1 bar(A()); // 2 }</pre> <p>It appears to work correctly, but that doesn't mean it's necessarily legal. Is it?</p> <p><i>Edit - changed <code>A&amp;</code> to <code>const A&amp;</code></i></p>
[ { "answer_id": 84457, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": -1, "selected": false, "text": "<p>Perfectly legal.</p>\n\n<p>The object will exist on the stack during the function call, just like any other local variable as well. </p>\n" }, { "answer_id": 84471, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "<p>It looked lke it would work, but it did not compile with g++ with the Wall option, here is what I get:</p>\n\n<pre>\nmichael@hardy-lenovo:~/Desktop$ g++ -Wall a.cpp\na.cpp: In function ‘int main()’:michael@hardy-lenovo:~/Desktop$ g++ -Wall a.cpp\na.cpp: In function ‘int main()’:\na.cpp:8: warning: taking address of temporary\na.cpp:9: error: invalid initialization of non-const reference of type ‘A&’ from a temporary of type ‘A’\na.cpp:4: error: in passing argument 1 of ‘void bar(A&)’\nmichael@hardy-lenovo:~/Desktop$ \n</pre>\n\n<p>Looks like you will need to use a constant reference.</p>\n" }, { "answer_id": 84475, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>Those A objects will only exist until execution reaches the semicolon. So, the calls are safe, but don't try to save the pointer and use it later. Also, the compiler may require bar take a const reference.</p>\n" }, { "answer_id": 84494, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": -1, "selected": false, "text": "<p>It is legal. We use it sometime to provide a default value which we might want to ignore.</p>\n\n<pre><code>int dosomething(error_code&amp; _e = ignore_errorcode()) {\n //do something\n}\n</code></pre>\n\n<p>In the above case it will construct an empty error code object if no <code>error_code</code> is passed to the function.</p>\n" }, { "answer_id": 84505, "author": "ugasoft", "author_id": 10120, "author_profile": "https://Stackoverflow.com/users/10120", "pm_score": -1, "selected": false, "text": "<p>for //2 you need a const reference</p>\n\n<p>for //1 I think it's legal but useless</p>\n" }, { "answer_id": 84521, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 3, "selected": false, "text": "<p>No, it's against the standard to pass a non-const reference to a temporary object. You can use a const reference:</p>\n\n<pre><code>class A{};\n\nvoid bar(const A&amp;);\n\nint main(void)\n{\n bar(A()); // 2\n}\n</code></pre>\n\n<p>So while some compliers will accept it, and it would work as long as don't use the memory after the semicolon, a conforming compiler will not accept it.</p>\n" }, { "answer_id": 84562, "author": "James Hopkin", "author_id": 11828, "author_profile": "https://Stackoverflow.com/users/11828", "pm_score": 5, "selected": true, "text": "<p>1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default).</p>\n\n<p>2: This is perfectly legal.</p>\n" }, { "answer_id": 89059, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 3, "selected": false, "text": "<p><em>foo</em> is not allowed in fully standard compliant C++, whereas <em>bar</em> is okay. Though chances are, <em>foo</em> will compile with warning, and <em>bar</em> may or may not compile with a warning as well.</p>\n\n<p><em>A()</em> create a temporary object, which unless bound to a reference (as is the case in <em>bar</em>), or used to initialize a named object, is destroyed at the end of the full expression in which it was created. A temporary created to hold a reference initializer persists until the end of its reference's scope. For the case of <em>bar</em>, that's the function call, so you can use <em>A</em> inside <em>bar</em> perfectly safely. It is forbidden to bound a temporary object (which is a rvalue) to a non-const reference. It is similarly forbidden to take the address of a rvalue (to pass as argument to initialize <em>A</em> for <em>foo</em>).</p>\n" }, { "answer_id": 1152218, "author": "CsTamas", "author_id": 140006, "author_profile": "https://Stackoverflow.com/users/140006", "pm_score": 2, "selected": false, "text": "<p>Short answer is yes.</p>\n<p>If the object is received by function as const reference parameter - as you have modified <code>bar(const A&amp;)</code> method, then it's totally legal. The function can operate on the object, but the object will be destructed after the function call (address of temporary can be taken, but shall not be stored and used after the function call - see reason below).</p>\n<p>The <code>foo(A*)</code> is legal too because the temporary object is destroyed at the end of fullexpression. However most of the compiler will emit warning about taking address of temporary.</p>\n<p>The original version of <code>bar(A&amp;)</code> shall not compile, it's against the standard to initialize a non-const reference from a temporary.</p>\n<blockquote>\n<p><strong>C++ standard chapter 12.2</strong></p>\n<p>3 [...] Temporary objects are destroyed as the last step in evaluating the fullexpression (1.9) that (lexically) contains the point where they were created. [...]</p>\n<p>4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object’s initialization is complete. [...]</p>\n<p>5 The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctorinitializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.\nA temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits.</p>\n</blockquote>\n<p>A <strong>fullexpression</strong> is an expression that is not a subexpression of another expression.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9530/" ]
Specifically, is the following legal C++? ``` class A{}; void foo(A*); void bar(const A&); int main(void) { foo(&A()); // 1 bar(A()); // 2 } ``` It appears to work correctly, but that doesn't mean it's necessarily legal. Is it? *Edit - changed `A&` to `const A&`*
1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default). 2: This is perfectly legal.
84,449
<p>The XML Schema Part 2 specifies that an instance of a datatype that is defined as boolean can have the following legal literals {true, false, 1, 0}. The following XML, for example, when deserialized, sets the boolean property "Emulate" to <code>true</code>.</p> <pre><code>&lt;root&gt; &lt;emulate&gt;1&lt;/emulate&gt; &lt;/root&gt; </code></pre> <p>However, when I serialize the object back to the XML, I get <code>true</code> instead of the numerical value. My question is, is there a way that I can control the boolean representation in the XML?</p>
[ { "answer_id": 84514, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>No, not using the default System.Xml.XmlSerializer: you'd need to change the data type to an int to achieve that, or muck around with providing your own serialization code (possible, but not much fun). </p>\n\n<p>However, you can simply post-process the generated XML instead, of course, either using XSLT, or simply using string substitution. A bit of a hack, but pretty quick, both in development time and run time...</p>\n" }, { "answer_id": 84528, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": true, "text": "<p>You can implement IXmlSerializable which will allow you to alter the serialized output of your class however you want. This will entail creating the 3 methods GetSchema(), ReadXml(XmlReader r) and WriteXml(XmlWriter r). When you implement the interface, these methods are called instead of .NET trying to serialize the object itself. </p>\n\n<p>Examples can be found at:</p>\n\n<p><a href=\"http://www.developerfusion.co.uk/show/4639/\" rel=\"nofollow noreferrer\">http://www.developerfusion.co.uk/show/4639/</a> and</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx</a></p>\n" }, { "answer_id": 85468, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 6, "selected": false, "text": "<p>You can also do this by using some XmlSerializer attribute black magic:</p>\n\n<pre><code>[XmlIgnore]\npublic bool MyValue { get; set; }\n\n/// &lt;summary&gt;Get a value purely for serialization purposes&lt;/summary&gt;\n[XmlElement(\"MyValue\")]\npublic string MyValueSerialize\n{\n get { return this.MyValue ? \"1\" : \"0\"; }\n set { this.MyValue = XmlConvert.ToBoolean(value); }\n}\n</code></pre>\n\n<p>You can also use other attributes to hide this member from intellisense if you're offended by it! It's not a perfect solution, but it can be quicker than implementing IXmlSerializable.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8205/" ]
The XML Schema Part 2 specifies that an instance of a datatype that is defined as boolean can have the following legal literals {true, false, 1, 0}. The following XML, for example, when deserialized, sets the boolean property "Emulate" to `true`. ``` <root> <emulate>1</emulate> </root> ``` However, when I serialize the object back to the XML, I get `true` instead of the numerical value. My question is, is there a way that I can control the boolean representation in the XML?
You can implement IXmlSerializable which will allow you to alter the serialized output of your class however you want. This will entail creating the 3 methods GetSchema(), ReadXml(XmlReader r) and WriteXml(XmlWriter r). When you implement the interface, these methods are called instead of .NET trying to serialize the object itself. Examples can be found at: <http://www.developerfusion.co.uk/show/4639/> and <http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx>
84,460
<p>I've been using Destop.open() to launch a .pdf viewer on Windows machines, both Vista and XP, and most of them work just fine. However, on one XP machine the call does not work, simply returning without throwing any exceptions, and the viewer does not launch. On that machine the file association is properly set up as far as I can tell: double-clicking a .pdf works, as does the "start xxx.pdf" command on the command prompt. I'm thinking it must be a Windows configuration issue, but can't put my finger on it.</p> <p>Has anyone else seen this problem?</p>
[ { "answer_id": 84529, "author": "Martin Spamer", "author_id": 15527, "author_profile": "https://Stackoverflow.com/users/15527", "pm_score": 2, "selected": false, "text": "<p>This is a known problem with early versions of XP SP2, the ShellExecute function stopped accepting URIs; bring the XP machines patches up to date.</p>\n\n<p>To view the exceptions make sure the Java Console is turned on:</p>\n\n<pre><code>Control Panel-&gt;Java Control Panel-&gt;Advanced-&gt;Java Console.\n</code></pre>\n" }, { "answer_id": 9693145, "author": "michel.iamit", "author_id": 369060, "author_profile": "https://Stackoverflow.com/users/369060", "pm_score": 0, "selected": false, "text": "<p>I still have this problem with one of my customers, I'll check what version of windows (As far as I remember He uses windows 7, 64-bits). The file association with pdf is OK (checked that). And he uses the latest java version (checked the updates of java), so still an actual problem as far as I Am concerned.....</p>\n\n<p>However i ran in to this bug report:\n<a href=\"http://bugs.sun.com/view_bug.do?bug_id=6764271\" rel=\"nofollow\">sun bug report 6764271</a></p>\n\n<p>There is says it might have something to do with the registration of some of the adobe versions (using READ in stead of OPEN in the windows registry).</p>\n\n<p>Still a shame a bug like this is low on prio and still an open bug (reported in 2008).</p>\n\n<p>I'll check with my customer soon and update my answer here as soon as I got it resolved.</p>\n" }, { "answer_id": 9962004, "author": "Lund Wolfe", "author_id": 1247753, "author_profile": "https://Stackoverflow.com/users/1247753", "pm_score": 1, "selected": false, "text": "<p>I couldn't find the answer anywhere but I have two machines with Windows 7 64 bit that fail the Desktop.getDesktop().open(file) with failed to open file or access is denied error on java 6 and java 7.</p>\n\n<p>Windows Explorer is able to open applications based on the filename with extension:</p>\n\n<pre><code>Runtime rt = Runtime.getRuntime();\nrt.exec(new String[]{\"explorer\", \"C:\\\\myfile.pdf\"});\nrt.exec(new String[]{\"explorer\", \"C:\\\\myfile.wmv\"});\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16213/" ]
I've been using Destop.open() to launch a .pdf viewer on Windows machines, both Vista and XP, and most of them work just fine. However, on one XP machine the call does not work, simply returning without throwing any exceptions, and the viewer does not launch. On that machine the file association is properly set up as far as I can tell: double-clicking a .pdf works, as does the "start xxx.pdf" command on the command prompt. I'm thinking it must be a Windows configuration issue, but can't put my finger on it. Has anyone else seen this problem?
This is a known problem with early versions of XP SP2, the ShellExecute function stopped accepting URIs; bring the XP machines patches up to date. To view the exceptions make sure the Java Console is turned on: ``` Control Panel->Java Control Panel->Advanced->Java Console. ```
84,463
<p>For example I want to be able to programatically hit a line of code like the following where the function name is dynamically assigned without using Evaluate(). The code below of course doesn't work but represents what I would like to do.</p> <pre><code>application.obj[funcName](argumentCollection=params) </code></pre> <p>The only way I can find to call a function dynamically is by using cfinvoke, but as far as I can tell that instantiates the related cfc/function on the fly and can't use a previously instantiated cfc.</p> <p>Thanks</p>
[ { "answer_id": 84836, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 4, "selected": true, "text": "<p>According to the docs, you can do something like this:</p>\n\n<pre><code>&lt;!--- Create the component instance. ---&gt;\n&lt;cfobject component=\"tellTime2\" name=\"tellTimeObj\"&gt;\n&lt;!--- Invoke the methods. ---&gt;\n&lt;cfinvoke component=\"#tellTimeObj#\" method=\"getLocalTime\" returnvariable=\"localTime\"&gt;\n&lt;cfinvoke component=\"#tellTimeObj#\" method=\"getUTCTime\" returnvariable=\"UTCTime\"&gt;\n</code></pre>\n\n<p>You should be able to simply call it with method=\"#myMethod#\" to dynamically call a particular function.</p>\n" }, { "answer_id": 84840, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 2, "selected": false, "text": "<p>You can use cfinvoke. You don't have to specify a component. </p>\n\n<pre><code>&lt;cfinvoke method=\"application.#funcName#\" argumentCollection=\"#params#\"&gt;\n</code></pre>\n" }, { "answer_id": 7802182, "author": "Nick Harvey", "author_id": 788583, "author_profile": "https://Stackoverflow.com/users/788583", "pm_score": 1, "selected": false, "text": "<p>You can also do something very similar, to the way you wanted to use it. You can access the method within the object using the syntax you used, you just can't call it at the same time. However, if you assign it to a temp variable, you can then call it</p>\n\n<pre><code>&lt;!--- get the component (has methods 'sayHi' and a method 'sayHello') ---&gt;\n&lt;cfset myObj = createObject(\"component\", \"test_object\")&gt;\n\n&lt;!--- set the function that we want dynamically then call it (it's a two step process) ---&gt;\n&lt;cfset func = \"sayHi\"&gt;\n&lt;cfset funcInstance = myObj[func]&gt;\n&lt;cfoutput&gt;#funcInstance(\"Dave\")#&lt;/cfoutput&gt;\n\n&lt;cfset func = \"sayHello\"&gt;\n&lt;cfset funcInstance = myObj[func]&gt;\n&lt;cfoutput&gt;#funcInstance(\"Dave\")#&lt;/cfoutput&gt;\n</code></pre>\n" }, { "answer_id": 7805955, "author": "Aaron Greenlee", "author_id": 88813, "author_profile": "https://Stackoverflow.com/users/88813", "pm_score": 1, "selected": false, "text": "<p>In CFML, functions are first-class members of the language. This allows us to pass them around like a variable. In the following example I will copy the function named 'foobar' and rename it \"$fn\" within the same object. Then, we can simply call $fn().</p>\n\n<pre><code>funcName = 'foobar'; \napplication.obj.$fn = application.obj[funcName];\napplication.obj.$fn(argumentCollection=arguments);\n</code></pre>\n\n<p>The context of the function is important, especially if it references any values in the 'variables' or 'this' scope of the object. Note: this is not thread safe for CFC instances in shared scopes!</p>\n\n<p>The fastest method is to use Ben Doom's recommendation. I just wanted to be thorough.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8345/" ]
For example I want to be able to programatically hit a line of code like the following where the function name is dynamically assigned without using Evaluate(). The code below of course doesn't work but represents what I would like to do. ``` application.obj[funcName](argumentCollection=params) ``` The only way I can find to call a function dynamically is by using cfinvoke, but as far as I can tell that instantiates the related cfc/function on the fly and can't use a previously instantiated cfc. Thanks
According to the docs, you can do something like this: ``` <!--- Create the component instance. ---> <cfobject component="tellTime2" name="tellTimeObj"> <!--- Invoke the methods. ---> <cfinvoke component="#tellTimeObj#" method="getLocalTime" returnvariable="localTime"> <cfinvoke component="#tellTimeObj#" method="getUTCTime" returnvariable="UTCTime"> ``` You should be able to simply call it with method="#myMethod#" to dynamically call a particular function.
84,486
<p>I've spent far too much time trying to figure this out. This should be the simplest thing and everyone who distributes Java applications in jars must have to deal with it.</p> <p>I just want to know the proper way to add versioning to my Java app so that I can access the version information when I'm testing, e.g. debugging in Eclipse <strong>and</strong> running from a jar.</p> <p>Here's what I have in my build.xml:</p> <pre><code>&lt;target name="jar" depends = "compile"&gt; &lt;property name="version.num" value="1.0.0"/&gt; &lt;buildnumber file="build.num"/&gt; &lt;tstamp&gt; &lt;format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" /&gt; &lt;/tstamp&gt; &lt;manifest file="${build}/META-INF/MANIFEST.MF"&gt; &lt;attribute name="Built-By" value="${user.name}" /&gt; &lt;attribute name="Built-Date" value="${TODAY}" /&gt; &lt;attribute name="Implementation-Title" value="MyApp" /&gt; &lt;attribute name="Implementation-Vendor" value="MyCompany" /&gt; &lt;attribute name="Implementation-Version" value="${version.num}-b${build.number}"/&gt; &lt;/manifest&gt; &lt;jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" /&gt; &lt;/target&gt; </code></pre> <p>This creates /META-INF/MANIFEST.MF and I can read the values when I'm debugging in Eclipse thusly:</p> <pre><code>public MyClass() { try { InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(stream); Attributes attributes = manifest.getMainAttributes(); String implementationTitle = attributes.getValue("Implementation-Title"); String implementationVersion = attributes.getValue("Implementation-Version"); String builtDate = attributes.getValue("Built-Date"); String builtBy = attributes.getValue("Built-By"); } catch (IOException e) { logger.error("Couldn't read manifest."); } </code></pre> <p>}</p> <p>But, when I create the jar file, it loads the manifest of another jar (presumably the first jar loaded by the application - in my case, activation.jar).</p> <p>Also, the following code doesn't work either although all the proper values are in the manifest file.</p> <pre><code> Package thisPackage = getClass().getPackage(); String implementationVersion = thisPackage.getImplementationVersion(); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 84606, "author": "Juan Pablo Morales", "author_id": 16238, "author_profile": "https://Stackoverflow.com/users/16238", "pm_score": 0, "selected": false, "text": "<p>Just don't use the manifest. Create a foo.properties.original file, with a content such as\nversion=@VERSION@</p>\n\n<p>And in ther same task you are jaring you can do a copy to copu foo.properties.original and then\n</p>\n" }, { "answer_id": 84897, "author": "Javamann", "author_id": 10166, "author_profile": "https://Stackoverflow.com/users/10166", "pm_score": 0, "selected": false, "text": "<p>I will also usually use a version file. I will create one file per jar since each jar could have its own version.</p>\n" }, { "answer_id": 84945, "author": "Martin Spamer", "author_id": 15527, "author_profile": "https://Stackoverflow.com/users/15527", "pm_score": 1, "selected": false, "text": "<p>You can access the manifest (or any other) file within a jar if you use the same class loader to as was used to load the classes.</p>\n\n<pre><code>this.getClass().getClassLoader().getResourceAsStream( ... ) ;\n</code></pre>\n\n<p>If you are multi-threaded use the following:</p>\n\n<pre><code>Thread.currentThread().getContextClassLoader().getResourceAsStream( ... ) ;\n</code></pre>\n\n<p>This is also a realy useful technique for including a default configuration file within the jar.</p>\n" }, { "answer_id": 94325, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 2, "selected": false, "text": "<p>You want to use this:</p>\n\n<pre><code>Enumeration&lt;URL&gt; resources = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/MANIFEST.MF\");\n</code></pre>\n\n<p>You can parse the URL to figure out WHICH jar the manifest if from and then read the URL via getInputStream() to parse the manifest.</p>\n" }, { "answer_id": 149477, "author": "user16216", "author_id": 16216, "author_profile": "https://Stackoverflow.com/users/16216", "pm_score": 1, "selected": false, "text": "<p>Here's what I've found that works: </p>\n\n<p>packageVersion.java:</p>\n\n<pre><code>package com.company.division.project.packageversion;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.jar.Attributes;\nimport java.util.jar.Manifest;\n\npublic class packageVersion\n{\n void printVersion()\n {\n try\n { \n InputStream stream = getClass().getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n\n if (stream == null)\n {\n System.out.println(\"Couldn't find manifest.\");\n System.exit(0);\n }\n\n Manifest manifest = new Manifest(stream);\n\n Attributes attributes = manifest.getMainAttributes();\n\n String impTitle = attributes.getValue(\"Implementation-Title\");\n String impVersion = attributes.getValue(\"Implementation-Version\");\n String impBuildDate = attributes.getValue(\"Built-Date\");\n String impBuiltBy = attributes.getValue(\"Built-By\");\n\n if (impTitle != null)\n {\n System.out.println(\"Implementation-Title: \" + impTitle);\n } \n if (impVersion != null)\n {\n System.out.println(\"Implementation-Version: \" + impVersion);\n }\n if (impBuildDate != null)\n {\n System.out.println(\"Built-Date: \" + impBuildDate);\n }\n if (impBuiltBy != null)\n {\n System.out.println(\"Built-By: \" + impBuiltBy);\n }\n\n System.exit(0);\n }\n catch (IOException e)\n { \n System.out.println(\"Couldn't read manifest.\");\n } \n }\n\n /**\n * @param args\n */\n public static void main(String[] args)\n {\n packageVersion version = new packageVersion();\n version.printVersion(); \n }\n\n}\n</code></pre>\n\n<p>Here's the matching build.xml:</p>\n\n<pre><code>&lt;project name=\"packageVersion\" default=\"run\" basedir=\".\"&gt;\n\n &lt;property name=\"src\" location=\"src\"/&gt;\n &lt;property name=\"build\" location=\"bin\"/&gt;\n &lt;property name=\"dist\" location=\"dist\"/&gt;\n\n &lt;target name=\"init\"&gt;\n &lt;tstamp&gt;\n &lt;format property=\"TIMESTAMP\" pattern=\"yyyy-MM-dd HH:mm:ss\" /&gt;\n &lt;/tstamp&gt;\n &lt;mkdir dir=\"${build}\"/&gt;\n &lt;mkdir dir=\"${build}/META-INF\"/&gt;\n &lt;/target&gt;\n\n &lt;target name=\"compile\" depends=\"init\"&gt;\n &lt;javac debug=\"on\" srcdir=\"${src}\" destdir=\"${build}\"/&gt;\n &lt;/target&gt;\n\n &lt;target name=\"dist\" depends = \"compile\"&gt; \n &lt;mkdir dir=\"${dist}\"/&gt; \n &lt;property name=\"version.num\" value=\"1.0.0\"/&gt;\n &lt;buildnumber file=\"build.num\"/&gt;\n &lt;manifest file=\"${build}/META-INF/MANIFEST.MF\"&gt;\n &lt;attribute name=\"Built-By\" value=\"${user.name}\" /&gt;\n &lt;attribute name=\"Built-Date\" value=\"${TIMESTAMP}\" /&gt; \n &lt;attribute name=\"Implementation-Vendor\" value=\"Company\" /&gt;\n &lt;attribute name=\"Implementation-Title\" value=\"PackageVersion\" /&gt;\n &lt;attribute name=\"Implementation-Version\" value=\"${version.num} (b${build.number})\"/&gt;\n &lt;section name=\"com/company/division/project/packageversion\"&gt;\n &lt;attribute name=\"Sealed\" value=\"false\"/&gt;\n &lt;/section&gt; \n &lt;/manifest&gt; \n &lt;jar destfile=\"${dist}/packageversion-${version.num}.jar\" basedir=\"${build}\" manifest=\"${build}/META-INF/MANIFEST.MF\"/&gt; \n &lt;/target&gt;\n\n &lt;target name=\"clean\"&gt;\n &lt;delete dir=\"${build}\"/&gt;\n &lt;delete dir=\"${dist}\"/&gt;\n &lt;/target&gt;\n\n &lt;target name=\"run\" depends=\"dist\"&gt; \n &lt;java classname=\"com.company.division.project.packageversion.packageVersion\"&gt;\n &lt;arg value=\"-h\"/&gt;\n &lt;classpath&gt;\n &lt;pathelement location=\"${dist}/packageversion-${version.num}.jar\"/&gt;\n &lt;pathelement path=\"${java.class.path}\"/&gt;\n &lt;/classpath&gt;\n &lt;/java&gt;\n &lt;/target&gt;\n\n&lt;/project&gt;\n</code></pre>\n" }, { "answer_id": 615437, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)\" rel=\"nofollow noreferrer\">ClassLoader.getResource(String)</a> will load the first manifest it finds on the classpath, which may be the manifest for some other JAR file. Thus, you can either <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResources(java.lang.String)\" rel=\"nofollow noreferrer\">enumerate all the manifests</a> to find the one you want or use some other mechanism, such as a properties file with a unique name.</p>\n" }, { "answer_id": 3069207, "author": "Glenn Burkhardt", "author_id": 370243, "author_profile": "https://Stackoverflow.com/users/370243", "pm_score": 1, "selected": false, "text": "<p>I've found the comment by McDowell to be true - which MANIFEST.MF file gets picked up depends on the classpath and might not be the one wanted. I use this</p>\n\n<pre><code>String cp = PCAS.class.getResource(PCAS.class.getSimpleName() + \".class\").toString();\ncp = cp.substring(0, cp.indexOf(PCAS.class.getPackage().getName())) \n + \"META-INF/MANIFEST.MF\";\nManifest mf = new Manifest((new URL(cp)).openStream());\n</code></pre>\n\n<p>which I adapted from <a href=\"http://forums.sun.com/thread.jspa?threadID=642761\" rel=\"nofollow noreferrer\">link text</a></p>\n" }, { "answer_id": 3071608, "author": "gibbss", "author_id": 116621, "author_profile": "https://Stackoverflow.com/users/116621", "pm_score": 4, "selected": false, "text": "<p>You can get the manifest for an arbitrary class in an arbitrary jar without parsing the class url (which could be brittle). Just locate a resource that you know is in the jar you want, and then cast the connection to JarURLConnection. </p>\n\n<p>If you want the code to work when the class is not bundled in a jar, add an instanceof check on the type of URL connection returned. Classes in an unpacked class hierarchy will return a internal Sun FileURLConnection instead of the JarUrlConnection. Then you can load the Manifest using one of the InputStream methods described in other answers.</p>\n\n<pre><code>@Test\npublic void testManifest() throws IOException {\n URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + \".class\");\n JarURLConnection conn = (JarURLConnection) res.openConnection();\n Manifest mf = conn.getManifest();\n Attributes atts = mf.getMainAttributes();\n for (Object v : atts.values()) {\n System.out.println(v);\n }\n}\n</code></pre>\n" }, { "answer_id": 14089550, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 0, "selected": false, "text": "<p>You can use a utility class <a href=\"http://manifests.jcabi.com/apidocs-0.7.5/com/jcabi/manifests/Manifests.html\" rel=\"nofollow\"><code>Manifests</code></a> from <a href=\"http://manifests.jcabi.com/index.html\" rel=\"nofollow\">jcabi-manifests</a> that automates finding and parsing of all <code>MANIFEST.MF</code> files available in classpath. Then, you read any attribute with a one liner:</p>\n\n<pre><code>final String name = Manifests.read(\"Build-By\");\nfinal String date = Manifests.read(\"Build-Date\");\n</code></pre>\n\n<p>Also, check this out: <a href=\"http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html\" rel=\"nofollow\">http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16216/" ]
I've spent far too much time trying to figure this out. This should be the simplest thing and everyone who distributes Java applications in jars must have to deal with it. I just want to know the proper way to add versioning to my Java app so that I can access the version information when I'm testing, e.g. debugging in Eclipse **and** running from a jar. Here's what I have in my build.xml: ``` <target name="jar" depends = "compile"> <property name="version.num" value="1.0.0"/> <buildnumber file="build.num"/> <tstamp> <format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" /> </tstamp> <manifest file="${build}/META-INF/MANIFEST.MF"> <attribute name="Built-By" value="${user.name}" /> <attribute name="Built-Date" value="${TODAY}" /> <attribute name="Implementation-Title" value="MyApp" /> <attribute name="Implementation-Vendor" value="MyCompany" /> <attribute name="Implementation-Version" value="${version.num}-b${build.number}"/> </manifest> <jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" /> </target> ``` This creates /META-INF/MANIFEST.MF and I can read the values when I'm debugging in Eclipse thusly: ``` public MyClass() { try { InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF"); Manifest manifest = new Manifest(stream); Attributes attributes = manifest.getMainAttributes(); String implementationTitle = attributes.getValue("Implementation-Title"); String implementationVersion = attributes.getValue("Implementation-Version"); String builtDate = attributes.getValue("Built-Date"); String builtBy = attributes.getValue("Built-By"); } catch (IOException e) { logger.error("Couldn't read manifest."); } ``` } But, when I create the jar file, it loads the manifest of another jar (presumably the first jar loaded by the application - in my case, activation.jar). Also, the following code doesn't work either although all the proper values are in the manifest file. ``` Package thisPackage = getClass().getPackage(); String implementationVersion = thisPackage.getImplementationVersion(); ``` Any ideas?
You can get the manifest for an arbitrary class in an arbitrary jar without parsing the class url (which could be brittle). Just locate a resource that you know is in the jar you want, and then cast the connection to JarURLConnection. If you want the code to work when the class is not bundled in a jar, add an instanceof check on the type of URL connection returned. Classes in an unpacked class hierarchy will return a internal Sun FileURLConnection instead of the JarUrlConnection. Then you can load the Manifest using one of the InputStream methods described in other answers. ``` @Test public void testManifest() throws IOException { URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + ".class"); JarURLConnection conn = (JarURLConnection) res.openConnection(); Manifest mf = conn.getManifest(); Attributes atts = mf.getMainAttributes(); for (Object v : atts.values()) { System.out.println(v); } } ```
84,506
<p>I find from reading perldoc perlvar, about a thousand lines in is help for %ENV. Is there a way to find that from the command line directly?</p> <p>On my Windows machine, I've tried the following</p> <pre><code>perldoc ENV perldoc %ENV perldoc %%ENV perldoc -r ENV (returns info about Use Env) perldoc -r %ENV perldoc -r %%%ENV perldoc -r %%%%ENV (says No documentation found for "%ENV") </code></pre> <p>None actually return information about the %ENV variable.</p> <p>How do I use perldoc to find out about %ENV, if I don't want to have to eye-grep through thousands of line?</p> <p>I've tried the suggested "perldoc perlvar" and then typing /%ENV, but nothing happens. </p> <pre><code>perl -v: This is perl, v5.8.0 built for MSWin32-x86-multi-thread </code></pre> <p>Though I've asked about %ENV, this also applies to any general term, so knowing that %ENV is in perlvar for this one example won't help me next time when I don't know which section.</p> <p>Is there a way to get perldoc to dump everything (ugh) and I can grep the output?</p>
[ { "answer_id": 84741, "author": "amoore", "author_id": 7573, "author_profile": "https://Stackoverflow.com/users/7573", "pm_score": -1, "selected": false, "text": "<p>If you'd like to see the contents of your %ENV, you can use Data::Dumper to print it out in a rather readable format:</p>\n\n<p>perl -MData::Dumper -e 'print Dumper \\%ENV'</p>\n" }, { "answer_id": 84763, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 2, "selected": false, "text": "<p>The searching for %ENV is a feature of the pager named 'less', not of perldoc. So if perldoc uses a different pager, this might not work.</p>\n\n<p>Activestate Perl comes with HTML documentation, you can open perlvar in your browser, hit Ctrl+f and type %ENV, then hit enter.</p>\n" }, { "answer_id": 84773, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": true, "text": "<p>perldoc doesn't have an option to search for a particular entry in perlvar (like -f does for perlfunc). General searching is dependent on your pager (specified in the PAGER environment variable). Personally, I like \"less.\" You can get <a href=\"http://gnuwin32.sourceforge.net/packages/less.htm\" rel=\"nofollow noreferrer\">less for windows</a> from the <a href=\"http://gnuwin32.sourceforge.net/\" rel=\"nofollow noreferrer\">GnuWin32</a> project.</p>\n" }, { "answer_id": 84786, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 0, "selected": false, "text": "<ol>\n<li>Install <a href=\"http://unxutils.sourceforge.net/\" rel=\"nofollow noreferrer\"><code>unixutils</code></a> for Windows </li>\n<li>Call: \n<code>perldoc perlvar | grep -A10 %env</code></li>\n</ol>\n" }, { "answer_id": 84791, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 4, "selected": false, "text": "<p>Check out the latest development version of <a href=\"http://search.cpan.org/~ferreira/Pod-Perldoc-3.14_07/\" rel=\"noreferrer\">Pod::Perldoc</a>. I submitted a patch which lets you do this:</p>\n\n<pre><code>$ perldoc -v '%ENV'\n\n%ENV\n$ENV{expr}\nThe hash %ENV contains your current environment. Setting a value in\n\"ENV\" changes the environment for any child processes you subsequently\nfork() off.\n</code></pre>\n" }, { "answer_id": 91195, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "<pre><code>firefox http://perldoc.perl.org/perlvar.html#%ENV\n</code></pre>\n\n<p>By the way, many many many bugs have been fixed since 5.8.0.</p>\n" }, { "answer_id": 109368, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 1, "selected": false, "text": "<p>I use <a href=\"http://search.cpan.org/dist/Apache-Perldoc\" rel=\"nofollow noreferrer\">Apache::Perldoc</a> (old, but still does its job) on my local machine to browse the local documentation. If I have net access though, I just look at <a href=\"http://perldoc.perl.org\" rel=\"nofollow noreferrer\">perldoc.perl.org</a> and search. However, in this case, search isn't useful for the variables and it's better to use the <a href=\"http://perldoc.perl.org/perlvar.html\" rel=\"nofollow noreferrer\">Special variables</a> link at the left of the page.</p>\n\n<p>As you get more experience with Perl, you'll know where to look for the documentation. For know, you might have to refer to perltoc, but after awhile you'll know to look for functions in <A href=\"http://perldoc.perl.org/perlfunc.html\" rel=\"nofollow noreferrer\">perlfunc</A>, variables in <a href=\"http://perldoc.perl.org/perlvar.html\" rel=\"nofollow noreferrer\">perlvar</a>, and so on. </p>\n\n<p>You might also use my <A href=\"http://www.perlmonks.org/index.pl?node_id=408254\" rel=\"nofollow noreferrer\">Perl documentation documentation</a>.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8763/" ]
I find from reading perldoc perlvar, about a thousand lines in is help for %ENV. Is there a way to find that from the command line directly? On my Windows machine, I've tried the following ``` perldoc ENV perldoc %ENV perldoc %%ENV perldoc -r ENV (returns info about Use Env) perldoc -r %ENV perldoc -r %%%ENV perldoc -r %%%%ENV (says No documentation found for "%ENV") ``` None actually return information about the %ENV variable. How do I use perldoc to find out about %ENV, if I don't want to have to eye-grep through thousands of line? I've tried the suggested "perldoc perlvar" and then typing /%ENV, but nothing happens. ``` perl -v: This is perl, v5.8.0 built for MSWin32-x86-multi-thread ``` Though I've asked about %ENV, this also applies to any general term, so knowing that %ENV is in perlvar for this one example won't help me next time when I don't know which section. Is there a way to get perldoc to dump everything (ugh) and I can grep the output?
perldoc doesn't have an option to search for a particular entry in perlvar (like -f does for perlfunc). General searching is dependent on your pager (specified in the PAGER environment variable). Personally, I like "less." You can get [less for windows](http://gnuwin32.sourceforge.net/packages/less.htm) from the [GnuWin32](http://gnuwin32.sourceforge.net/) project.
84,615
<p>If one wants to paginate results from a data source that supports pagination we have to go to a process of:</p> <ol> <li>defining the page size - that is the number of results to show per page;</li> <li>fetch each page requested by the user using an offset = page number (0 based) * page size</li> <li>show the results of the fetched page.</li> </ol> <p>All this is works just fine not considering the fact that an operation may affect the backend system that screws up the pagination taking place. I am talking about someone inserting data between page fetches or deleting data.</p> <pre><code>page_size = 10; get page 0 -&gt; results from 0 to 9; user inserts a record that due to the query being executed goes to page 0 - the one just shown; get page 1 -&gt; results from 10 to 19 - the first results on the page is the result on the old page 0. </code></pre> <p>The described behavior can cause confusion to the viewer. Do you know any practical solution to workaround this problem.</p>
[ { "answer_id": 84665, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": true, "text": "<p>There are a few schools of thought o this.</p>\n\n<ol>\n<li>data gets updated let it be</li>\n<li>You could implement some sort of caching method that will hold the\nentire result set (This might not be\nan option if working with really\nlarge Datasets)</li>\n<li>You could do a comparison on each page operation and notify the\nuser if the total record count\nchanges</li>\n</ol>\n\n<p>.</p>\n" }, { "answer_id": 84706, "author": "Doug McClean", "author_id": 11173, "author_profile": "https://Stackoverflow.com/users/11173", "pm_score": 0, "selected": false, "text": "<p>If the updates you are concerned with are primarily new insertions (for example, StackOverflow itself seems to suffer from this problem when paging through questions and new questions come in) one way to handle it is to capture a timestamp when you issue the first pagination query, and then limit the results of requests for subsequent pages to items which existed before that timestamp.</p>\n" }, { "answer_id": 85233, "author": "Seun Osewa", "author_id": 6475, "author_profile": "https://Stackoverflow.com/users/6475", "pm_score": 0, "selected": false, "text": "<p>As long as users understand that the underlying data is always changing, they won't be confused. So just do it the straightforward way.</p>\n\n<p>You could cache the first few pages of the result and use that for subsequent views, but then the results will be out of sync with the database, which is even more confusing.</p>\n" }, { "answer_id": 73745867, "author": "Marko Balažic", "author_id": 1857982, "author_profile": "https://Stackoverflow.com/users/1857982", "pm_score": 0, "selected": false, "text": "<p>One option is to exclude new incoming data objects from the result. This could be done with the session start time. You could add this for example to your JWT and then have a similar behavior like Twitter (14 new Twitts).</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
If one wants to paginate results from a data source that supports pagination we have to go to a process of: 1. defining the page size - that is the number of results to show per page; 2. fetch each page requested by the user using an offset = page number (0 based) \* page size 3. show the results of the fetched page. All this is works just fine not considering the fact that an operation may affect the backend system that screws up the pagination taking place. I am talking about someone inserting data between page fetches or deleting data. ``` page_size = 10; get page 0 -> results from 0 to 9; user inserts a record that due to the query being executed goes to page 0 - the one just shown; get page 1 -> results from 10 to 19 - the first results on the page is the result on the old page 0. ``` The described behavior can cause confusion to the viewer. Do you know any practical solution to workaround this problem.
There are a few schools of thought o this. 1. data gets updated let it be 2. You could implement some sort of caching method that will hold the entire result set (This might not be an option if working with really large Datasets) 3. You could do a comparison on each page operation and notify the user if the total record count changes .
84,641
<p>I have the following code:</p> <pre><code>$bind = new COM("LDAP://CN=GroupName,OU=Groups,OU=Division,DC=company,DC=local"); </code></pre> <p>When I execute it from a command-prompt, it runs fine. When it runs under IIS/PHP/ISAPI, it barfs.</p> <pre><code>Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `LDAP://CN=...[cut]...,DC=local': An operations error occurred. ' in index.php Stack trace: #0 index.php: com-&gt;com('LDAP://CN=...') #1 {main} thrown </code></pre> <p>IIS is configured for Windows Authentication (no anonymous, no basic, no digest) and I am connecting as the same user as the command prompt. I cannot find any specific errors in the IIS logfiles or the eventlog.</p> <p>The main purpose of this exercise is to refrain from keeping user credentials in my script and relying on IIS authentication to pass them through to the active directory. I understand that you can use LDAP to accomplish the same thing, but as far as I know credentials cannot be passed through.</p> <p>Perhaps it is in some way related to the error I get when I try to port it to ASP. I get error 80072020 (which I'm currently looking up).</p> <p>The event logs show nothing out of the ordinary. No warnings, no errors. Full security auditing is enabled (success and failure on every item in the security policy), and it shows successful Windows logons for every user I authenticate against the web page (which is expected.)</p>
[ { "answer_id": 84808, "author": "CodeRot", "author_id": 14134, "author_profile": "https://Stackoverflow.com/users/14134", "pm_score": 3, "selected": true, "text": "<p>Since you're using Windows Authentication in IIS, you may have some security events in the Windows Event log. I would check the Event log for Security Events as well as Application Events and see if you're hitting any sort of permissions issues. </p>\n\n<p>Also, since you're basically just communicating to AD via LDAP...you might look into using the a native LDAP library for PHP rather than a COM. </p>\n\n<p>You'll have to enable the extension probably in your php.ini. Worth looking at probably.</p>\n" }, { "answer_id": 84843, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 0, "selected": false, "text": "<p>Well, if you want to use LDAP, let me point you to the LDAP authentication code we use for Maia Mailguard: look for the function named <a href=\"https://www.maiamailguard.com/maia/browser/branches/1.0/php/auth.php\" rel=\"nofollow noreferrer\">lauth_ldap</a></p>\n\n<p>I think it requires ldap version 3, so you have to set that parameter for ldap. To verify the password, we use the ldap bind function to let the ldap server authenticate.</p>\n" }, { "answer_id": 84918, "author": "pobk", "author_id": 7829, "author_profile": "https://Stackoverflow.com/users/7829", "pm_score": 0, "selected": false, "text": "<p>I'm no AD/COM/IIS expert, but it could be a permissions problem. e.g the IUSR_computername user does not have applicable access within the directory, or you're not binding as a specific user?</p>\n\n<p>The alarm bell for me is the fact it runs ok from command line (e.g. running with your permissions) but fails on IIS (e.g. not your permissions).</p>\n" }, { "answer_id": 85664, "author": "Martin", "author_id": 2581, "author_profile": "https://Stackoverflow.com/users/2581", "pm_score": 2, "selected": false, "text": "<p>It seems to be working now.</p>\n\n<p>I enabled \"Trust this computer for delegation\" for the computer object in Active Directory. Normally IIS cannot both authenticate you and then subsequently impersonate you across the network (in my case to a domain controller to query Active Directory) without the delegation trust enabled.</p>\n\n<p>You just have to be sure that it's authenticating using Kerberos and not NTLM or some other digest authentication because the digest is not trusted to use as an impersonation token.</p>\n\n<p>It fixed both my PHP and ASP scripts.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
I have the following code: ``` $bind = new COM("LDAP://CN=GroupName,OU=Groups,OU=Division,DC=company,DC=local"); ``` When I execute it from a command-prompt, it runs fine. When it runs under IIS/PHP/ISAPI, it barfs. ``` Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `LDAP://CN=...[cut]...,DC=local': An operations error occurred. ' in index.php Stack trace: #0 index.php: com->com('LDAP://CN=...') #1 {main} thrown ``` IIS is configured for Windows Authentication (no anonymous, no basic, no digest) and I am connecting as the same user as the command prompt. I cannot find any specific errors in the IIS logfiles or the eventlog. The main purpose of this exercise is to refrain from keeping user credentials in my script and relying on IIS authentication to pass them through to the active directory. I understand that you can use LDAP to accomplish the same thing, but as far as I know credentials cannot be passed through. Perhaps it is in some way related to the error I get when I try to port it to ASP. I get error 80072020 (which I'm currently looking up). The event logs show nothing out of the ordinary. No warnings, no errors. Full security auditing is enabled (success and failure on every item in the security policy), and it shows successful Windows logons for every user I authenticate against the web page (which is expected.)
Since you're using Windows Authentication in IIS, you may have some security events in the Windows Event log. I would check the Event log for Security Events as well as Application Events and see if you're hitting any sort of permissions issues. Also, since you're basically just communicating to AD via LDAP...you might look into using the a native LDAP library for PHP rather than a COM. You'll have to enable the extension probably in your php.ini. Worth looking at probably.
84,644
<p>To make it short: hibernate doesn't support projections and query by example? I found this post:</p> <p>The code is this:</p> <pre><code>User usr = new User(); usr.setCity = 'TEST'; getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Example.create(usr)) </code></pre> <p>Like the other poster said, The generated sql keeps having a where class refering to just <strong>y0_= ? instead of this_.city</strong>. </p> <p>I already tried several approaches, and searched the issue tracker but found nothing about this.</p> <p>I even tried to use Projection alias and Transformers, but it does not work:</p> <pre><code>User usr = new User(); usr.setCity = 'TEST'; getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Example.create(usr)).setResultTransformer(Transformers.aliasToBean(User.class)); </code></pre> <p>Has anyone used projections and query by example ?</p>
[ { "answer_id": 86752, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": 5, "selected": true, "text": "<p>Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).</p>\n\n<pre><code>getCurrentSession().createCriteria(User.class)\n.setProjection( Projections.distinct( Projections.projectionList()\n.add( Projections.property(\"name\"), \"name\")\n.add( Projections.property(\"city\"), \"city\")))\n.add( Restrictions.eq(\"city\", \"TEST\")))\n.setResultTransformer(Transformers.aliasToBean(User.class))\n.list();\n</code></pre>\n\n<p>I've never used the alaistToBean, but I just read about it. You could also just loop over the results..</p>\n\n<pre><code>List&lt;Object&gt; rows = criteria.list();\nfor(Object r: rows){\n Object[] row = (Object[]) r;\n Type t = ((&lt;Type&gt;) row[0]);\n}\n</code></pre>\n\n<p>If you have to you can manually populate User yourself that way.</p>\n\n<p>Its sort of hard to look into the issue without some more information to diagnose the issue.</p>\n" }, { "answer_id": 960278, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 6, "selected": false, "text": "<p>The problem seems to happen when you have an alias the same name as the objects property. Hibernate seems to pick up the alias and use it in the sql. I found this documented <a href=\"http://opensource.atlassian.com/projects/hibernate/browse/HHH-3371;jsessionid=aLJbC8zJhKhanJbr49?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel\" rel=\"noreferrer\">here</a> and <a href=\"https://forum.hibernate.org/viewtopic.php?t=988049\" rel=\"noreferrer\">here</a>, and I believe it to be a bug in Hibernate, although I am not sure that the Hibernate team agrees.</p>\n\n<p>Either way, I have found a simple work around that works in my case. Your mileage may vary. The details are below, I tried to simplify the code for this sample so I apologize for any errors or typo's:</p>\n\n<pre><code>Criteria criteria = session.createCriteria(MyClass.class)\n .setProjection(Projections.projectionList()\n .add(Projections.property(\"sectionHeader\"), \"sectionHeader\")\n .add(Projections.property(\"subSectionHeader\"), \"subSectionHeader\")\n .add(Projections.property(\"sectionNumber\"), \"sectionNumber\"))\n .add(Restrictions.ilike(\"sectionHeader\", sectionHeaderVar)) // &lt;- Problem!\n .setResultTransformer(Transformers.aliasToBean(MyDTO.class));\n</code></pre>\n\n<p>Would produce this sql:</p>\n\n<pre><code>select\n this_.SECTION_HEADER as y1_,\n this_.SUB_SECTION_HEADER as y2_,\n this_.SECTION_NUMBER as y3_,\nfrom\n MY_TABLE this_ \nwhere\n ( lower(y1_) like ? ) \n</code></pre>\n\n<p>Which was causing an error: <em>java.sql.SQLException: ORA-00904: \"Y1_\": invalid identifier</em></p>\n\n<p><strong>But, when I changed my restriction to use \"this\", like so:</strong></p>\n\n<pre><code>Criteria criteria = session.createCriteria(MyClass.class)\n .setProjection(Projections.projectionList()\n .add(Projections.property(\"sectionHeader\"), \"sectionHeader\")\n .add(Projections.property(\"subSectionHeader\"), \"subSectionHeader\")\n .add(Projections.property(\"sectionNumber\"), \"sectionNumber\"))\n .add(Restrictions.ilike(\"this.sectionHeader\", sectionHeaderVar)) // &lt;- Problem Solved!\n .setResultTransformer(Transformers.aliasToBean(MyDTO.class));\n</code></pre>\n\n<p>It produced the following sql and my problem was solved.</p>\n\n<pre><code>select\n this_.SECTION_HEADER as y1_,\n this_.SUB_SECTION_HEADER as y2_,\n this_.SECTION_NUMBER as y3_,\nfrom\n MY_TABLE this_ \nwhere\n ( lower(this_.SECTION_HEADER) like ? ) \n</code></pre>\n\n<p>Thats, it! A pretty simple fix to a painful problem. I don't know how this fix would translate to the query by example problem, but it may get you closer.</p>\n" }, { "answer_id": 976595, "author": "VHristov", "author_id": 120582, "author_profile": "https://Stackoverflow.com/users/120582", "pm_score": 0, "selected": false, "text": "<p>I'm facing a similar problem. I'm using Query by Example and I want to sort the results by a custom field. In SQL I would do something like:</p>\n\n<pre><code>select pageNo, abs(pageNo - 434) as diff\nfrom relA\nwhere year = 2009\norder by diff\n</code></pre>\n\n<p>It works fine without the order-by-clause. What I got is</p>\n\n<pre><code>Criteria crit = getSession().createCriteria(Entity.class);\ncrit.add(exampleObject);\nProjectionList pl = Projections.projectionList();\npl.add( Projections.property(\"id\") );\npl.add(Projections.sqlProjection(\"abs(`pageNo`-\"+pageNo+\") as diff\", new String[] {\"diff\"}, types ));\ncrit.setProjection(pl);\n</code></pre>\n\n<p>But when I add </p>\n\n<pre><code>crit.addOrder(Order.asc(\"diff\"));\n</code></pre>\n\n<p>I get a <em>org.hibernate.QueryException: could not resolve property: diff</em> exception. Workaround with <em>this</em> does not work either. </p>\n\n<p>PS: as I could not find any elaborate documentation on the use of QBE for Hibernate, all the stuff above is mainly trial-and-error approach</p>\n" }, { "answer_id": 3720239, "author": "Dobes Vandermeer", "author_id": 399738, "author_profile": "https://Stackoverflow.com/users/399738", "pm_score": 3, "selected": false, "text": "<p>The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:</p>\n\n<p><a href=\"http://opensource.atlassian.com/projects/hibernate/browse/HHH-817\" rel=\"noreferrer\">http://opensource.atlassian.com/projects/hibernate/browse/HHH-817</a></p>\n\n<p>Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.</p>\n" }, { "answer_id": 6647403, "author": "mustafa", "author_id": 838469, "author_profile": "https://Stackoverflow.com/users/838469", "pm_score": -1, "selected": false, "text": "<p>I do not really think so, what I can find is the word \"this.\" causes the hibernate not to include any restrictions in its query, which means it got all the records lists. About the hibernate bug that was reported, I can see it's reported as fixed but I totally failed to download the Patch.</p>\n" }, { "answer_id": 35381484, "author": "singh", "author_id": 5922685, "author_profile": "https://Stackoverflow.com/users/5922685", "pm_score": 0, "selected": false, "text": "<pre><code>ProjectionList pl = Projections.projectionList();\npl.add(Projections.property(\"id\"));\npl.add(Projections.sqlProjection(\"abs(`pageNo`-\" + pageNo + \") as diff\", new String[] {\"diff\"}, types ), diff); ---- solution\ncrit.addOrder(Order.asc(\"diff\"));\ncrit.setProjection(pl);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To make it short: hibernate doesn't support projections and query by example? I found this post: The code is this: ``` User usr = new User(); usr.setCity = 'TEST'; getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Example.create(usr)) ``` Like the other poster said, The generated sql keeps having a where class refering to just **y0\_= ? instead of this\_.city**. I already tried several approaches, and searched the issue tracker but found nothing about this. I even tried to use Projection alias and Transformers, but it does not work: ``` User usr = new User(); usr.setCity = 'TEST'; getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Example.create(usr)).setResultTransformer(Transformers.aliasToBean(User.class)); ``` Has anyone used projections and query by example ?
Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though). ``` getCurrentSession().createCriteria(User.class) .setProjection( Projections.distinct( Projections.projectionList() .add( Projections.property("name"), "name") .add( Projections.property("city"), "city"))) .add( Restrictions.eq("city", "TEST"))) .setResultTransformer(Transformers.aliasToBean(User.class)) .list(); ``` I've never used the alaistToBean, but I just read about it. You could also just loop over the results.. ``` List<Object> rows = criteria.list(); for(Object r: rows){ Object[] row = (Object[]) r; Type t = ((<Type>) row[0]); } ``` If you have to you can manually populate User yourself that way. Its sort of hard to look into the issue without some more information to diagnose the issue.
84,661
<p>Sometimes, in PL SQL you want to add a parameter to a Package, Function or Procedure in order to prepare future functionality. For example:</p> <pre><code>create or replace function doGetMyAccountMoney( Type_Of_Currency IN char := 'EUR') return number is Result number(12,2); begin Result := 10000; IF char &lt;&gt; 'EUR' THEN -- ERROR NOT IMPLEMENTED YET END IF; return(Result); end doGetMyAccountMoney;also </code></pre> <p>It can lead to lots of warnings like</p> <pre><code>Compilation errors for FUNCTION APPUEMP_PRAC.DOGETMYACCOUNTMONEY Error: Hint: Parameter 'Currency' is declared but never used in 'doGetMyAccountMoney' Line: 1 </code></pre> <p>What would be the best way to avoid those warnings? </p>
[ { "answer_id": 84695, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Well, are you sure you have the name and the right in the correct order in that declaration?</p>\n\n<p>It complains about a parameter named 'Currency', but you aren't actually using it, are you?</p>\n\n<p>On the other hand, you are using something called <em>char</em>, what is that?</p>\n\n<p>Or perhaps my knowledge of PL/SQL is way off, if so, leave a comment and I'll delete this.</p>\n" }, { "answer_id": 84704, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 1, "selected": false, "text": "<p>Well, your example has several errors. Most importantly, you would need to change \"char\" to \"Currency\" in the IF statement; which as far as I can see would avoid the warning as well.</p>\n" }, { "answer_id": 84792, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 3, "selected": true, "text": "<p>I believe that this is controlled by the parameter PLSQL_WARNINGS, documented for 10gR2 here: <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/initparams166.htm#REFRN10249\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/initparams166.htm#REFRN10249</a></p>\n" }, { "answer_id": 88742, "author": "Sergey Stadnik", "author_id": 10557, "author_profile": "https://Stackoverflow.com/users/10557", "pm_score": 1, "selected": false, "text": "<p>Disable non-severe PL/SQL warnings:</p>\n\n<pre><code>ALTER SESSION SET PLSQL_WARNINGS='ENABLE:SEVERE';\n</code></pre>\n" }, { "answer_id": 88781, "author": "abliss", "author_id": 10718, "author_profile": "https://Stackoverflow.com/users/10718", "pm_score": 2, "selected": false, "text": "<p>If you didn't have the ability to alter the warning levels, you could just bind the parameter value to a dummy value and document that they are for future use.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16206/" ]
Sometimes, in PL SQL you want to add a parameter to a Package, Function or Procedure in order to prepare future functionality. For example: ``` create or replace function doGetMyAccountMoney( Type_Of_Currency IN char := 'EUR') return number is Result number(12,2); begin Result := 10000; IF char <> 'EUR' THEN -- ERROR NOT IMPLEMENTED YET END IF; return(Result); end doGetMyAccountMoney;also ``` It can lead to lots of warnings like ``` Compilation errors for FUNCTION APPUEMP_PRAC.DOGETMYACCOUNTMONEY Error: Hint: Parameter 'Currency' is declared but never used in 'doGetMyAccountMoney' Line: 1 ``` What would be the best way to avoid those warnings?
I believe that this is controlled by the parameter PLSQL\_WARNINGS, documented for 10gR2 here: <http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/initparams166.htm#REFRN10249>
84,680
<p>I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server.</p> <p>I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6.</p> <p>If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even <em>trying</em> to connect to the server to begin with.</p> <p>Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly.</p> <p>Here are my security-related beans:</p> <pre><code> &lt;beans:bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider"&gt; &lt;beans:constructor-arg&gt; &lt;beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator"&gt; &lt;beans:constructor-arg ref="initialDirContextFactory" /&gt; &lt;beans:property name="userDnPatterns"&gt; &lt;beans:list&gt; &lt;beans:value&gt;CN={0},OU=SBSUsers,OU=Users,OU=MyBusiness,DC=Acme,DC=com&lt;/beans:value&gt; &lt;/beans:list&gt; &lt;/beans:property&gt; &lt;/beans:bean&gt; &lt;/beans:constructor-arg&gt; &lt;/beans:bean&gt; &lt;beans:bean id="userDetailsService" class="org.springframework.security.userdetails.ldap.LdapUserDetailsManager"&gt; &lt;beans:constructor-arg ref="initialDirContextFactory" /&gt; &lt;/beans:bean&gt; &lt;beans:bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory"&gt; &lt;beans:constructor-arg value="ldap://192.168.123.456:389/DC=Acme,DC=com" /&gt; &lt;/beans:bean&gt; </code></pre>
[ { "answer_id": 86367, "author": "delfuego", "author_id": 16414, "author_profile": "https://Stackoverflow.com/users/16414", "pm_score": 6, "selected": true, "text": "<p>I had the same banging-my-head-against-the-wall experience you did, and ended up writing a custom authentication provider that does an LDAP query against the Active Directory server.</p>\n\n<p>So my security-related beans are:</p>\n\n<pre><code>&lt;beans:bean id=\"contextSource\"\n class=\"org.springframework.security.ldap.DefaultSpringSecurityContextSource\"&gt;\n &lt;beans:constructor-arg value=\"ldap://hostname.queso.com:389/\" /&gt;\n&lt;/beans:bean&gt;\n\n&lt;beans:bean id=\"ldapAuthenticationProvider\"\n class=\"org.queso.ad.service.authentication.LdapAuthenticationProvider\"&gt;\n &lt;beans:property name=\"authenticator\" ref=\"ldapAuthenticator\" /&gt;\n &lt;custom-authentication-provider /&gt;\n&lt;/beans:bean&gt;\n\n&lt;beans:bean id=\"ldapAuthenticator\"\n class=\"org.queso.ad.service.authentication.LdapAuthenticatorImpl\"&gt;\n &lt;beans:property name=\"contextFactory\" ref=\"contextSource\" /&gt;\n &lt;beans:property name=\"principalPrefix\" value=\"QUESO\\\" /&gt;\n&lt;/beans:bean&gt;\n</code></pre>\n\n<p>Then the LdapAuthenticationProvider class:</p>\n\n<pre><code>/**\n * Custom Spring Security authentication provider which tries to bind to an LDAP server with\n * the passed-in credentials; of note, when used with the custom {@link LdapAuthenticatorImpl},\n * does &lt;strong&gt;not&lt;/strong&gt; require an LDAP username and password for initial binding.\n * \n * @author Jason\n */\npublic class LdapAuthenticationProvider implements AuthenticationProvider {\n\n private LdapAuthenticator authenticator;\n\n public Authentication authenticate(Authentication auth) throws AuthenticationException {\n\n // Authenticate, using the passed-in credentials.\n DirContextOperations authAdapter = authenticator.authenticate(auth);\n\n // Creating an LdapAuthenticationToken (rather than using the existing Authentication\n // object) allows us to add the already-created LDAP context for our app to use later.\n LdapAuthenticationToken ldapAuth = new LdapAuthenticationToken(auth, \"ROLE_USER\");\n InitialLdapContext ldapContext = (InitialLdapContext) authAdapter\n .getObjectAttribute(\"ldapContext\");\n if (ldapContext != null) {\n ldapAuth.setContext(ldapContext);\n }\n\n return ldapAuth;\n }\n\n public boolean supports(Class clazz) {\n return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(clazz));\n }\n\n public LdapAuthenticator getAuthenticator() {\n return authenticator;\n }\n\n public void setAuthenticator(LdapAuthenticator authenticator) {\n this.authenticator = authenticator;\n }\n\n}\n</code></pre>\n\n<p>Then the LdapAuthenticatorImpl class:</p>\n\n<pre><code>/**\n * Custom Spring Security LDAP authenticator which tries to bind to an LDAP server using the\n * passed-in credentials; does &lt;strong&gt;not&lt;/strong&gt; require \"master\" credentials for an\n * initial bind prior to searching for the passed-in username.\n * \n * @author Jason\n */\npublic class LdapAuthenticatorImpl implements LdapAuthenticator {\n\n private DefaultSpringSecurityContextSource contextFactory;\n private String principalPrefix = \"\";\n\n public DirContextOperations authenticate(Authentication authentication) {\n\n // Grab the username and password out of the authentication object.\n String principal = principalPrefix + authentication.getName();\n String password = \"\";\n if (authentication.getCredentials() != null) {\n password = authentication.getCredentials().toString();\n }\n\n // If we have a valid username and password, try to authenticate.\n if (!(\"\".equals(principal.trim())) &amp;&amp; !(\"\".equals(password.trim()))) {\n InitialLdapContext ldapContext = (InitialLdapContext) contextFactory\n .getReadWriteContext(principal, password);\n\n // We need to pass the context back out, so that the auth provider can add it to the\n // Authentication object.\n DirContextOperations authAdapter = new DirContextAdapter();\n authAdapter.addAttributeValue(\"ldapContext\", ldapContext);\n\n return authAdapter;\n } else {\n throw new BadCredentialsException(\"Blank username and/or password!\");\n }\n }\n\n /**\n * Since the InitialLdapContext that's stored as a property of an LdapAuthenticationToken is\n * transient (because it isn't Serializable), we need some way to recreate the\n * InitialLdapContext if it's null (e.g., if the LdapAuthenticationToken has been serialized\n * and deserialized). This is that mechanism.\n * \n * @param authenticator\n * the LdapAuthenticator instance from your application's context\n * @param auth\n * the LdapAuthenticationToken in which to recreate the InitialLdapContext\n * @return\n */\n static public InitialLdapContext recreateLdapContext(LdapAuthenticator authenticator,\n LdapAuthenticationToken auth) {\n DirContextOperations authAdapter = authenticator.authenticate(auth);\n InitialLdapContext context = (InitialLdapContext) authAdapter\n .getObjectAttribute(\"ldapContext\");\n auth.setContext(context);\n return context;\n }\n\n public DefaultSpringSecurityContextSource getContextFactory() {\n return contextFactory;\n }\n\n /**\n * Set the context factory to use for generating a new LDAP context.\n * \n * @param contextFactory\n */\n public void setContextFactory(DefaultSpringSecurityContextSource contextFactory) {\n this.contextFactory = contextFactory;\n }\n\n public String getPrincipalPrefix() {\n return principalPrefix;\n }\n\n /**\n * Set the string to be prepended to all principal names prior to attempting authentication\n * against the LDAP server. (For example, if the Active Directory wants the domain-name-plus\n * backslash prepended, use this.)\n * \n * @param principalPrefix\n */\n public void setPrincipalPrefix(String principalPrefix) {\n if (principalPrefix != null) {\n this.principalPrefix = principalPrefix;\n } else {\n this.principalPrefix = \"\";\n }\n }\n\n}\n</code></pre>\n\n<p>And finally, the LdapAuthenticationToken class:</p>\n\n<pre><code>/**\n * &lt;p&gt;\n * Authentication token to use when an app needs further access to the LDAP context used to\n * authenticate the user.\n * &lt;/p&gt;\n * \n * &lt;p&gt;\n * When this is the Authentication object stored in the Spring Security context, an application\n * can retrieve the current LDAP context thusly:\n * &lt;/p&gt;\n * \n * &lt;pre&gt;\n * LdapAuthenticationToken ldapAuth = (LdapAuthenticationToken) SecurityContextHolder\n * .getContext().getAuthentication();\n * InitialLdapContext ldapContext = ldapAuth.getContext();\n * &lt;/pre&gt;\n * \n * @author Jason\n * \n */\npublic class LdapAuthenticationToken extends AbstractAuthenticationToken {\n\n private static final long serialVersionUID = -5040340622950665401L;\n\n private Authentication auth;\n transient private InitialLdapContext context;\n private List&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;GrantedAuthority&gt;();\n\n /**\n * Construct a new LdapAuthenticationToken, using an existing Authentication object and\n * granting all users a default authority.\n * \n * @param auth\n * @param defaultAuthority\n */\n public LdapAuthenticationToken(Authentication auth, GrantedAuthority defaultAuthority) {\n this.auth = auth;\n if (auth.getAuthorities() != null) {\n this.authorities.addAll(Arrays.asList(auth.getAuthorities()));\n }\n if (defaultAuthority != null) {\n this.authorities.add(defaultAuthority);\n }\n super.setAuthenticated(true);\n }\n\n /**\n * Construct a new LdapAuthenticationToken, using an existing Authentication object and\n * granting all users a default authority.\n * \n * @param auth\n * @param defaultAuthority\n */\n public LdapAuthenticationToken(Authentication auth, String defaultAuthority) {\n this(auth, new GrantedAuthorityImpl(defaultAuthority));\n }\n\n public GrantedAuthority[] getAuthorities() {\n GrantedAuthority[] authoritiesArray = this.authorities.toArray(new GrantedAuthority[0]);\n return authoritiesArray;\n }\n\n public void addAuthority(GrantedAuthority authority) {\n this.authorities.add(authority);\n }\n\n public Object getCredentials() {\n return auth.getCredentials();\n }\n\n public Object getPrincipal() {\n return auth.getPrincipal();\n }\n\n /**\n * Retrieve the LDAP context attached to this user's authentication object.\n * \n * @return the LDAP context\n */\n public InitialLdapContext getContext() {\n return context;\n }\n\n /**\n * Attach an LDAP context to this user's authentication object.\n * \n * @param context\n * the LDAP context\n */\n public void setContext(InitialLdapContext context) {\n this.context = context;\n }\n\n}\n</code></pre>\n\n<p>You'll notice that there are a few bits in there that you might not need.</p>\n\n<p>For example, my app needed to retain the successfully-logged-in LDAP context for further use by the user once logged in -- the app's purpose is to let users log in via their AD credentials and then perform further AD-related functions. So because of that, I have a custom authentication token, LdapAuthenticationToken, that I pass around (rather than Spring's default Authentication token) which allows me to attach the LDAP context. In LdapAuthenticationProvider.authenticate(), I create that token and pass it back out; in LdapAuthenticatorImpl.authenticate(), I attach the logged-in context to the return object so that it can be added to the user's Spring authentication object.</p>\n\n<p>Also, in LdapAuthenticationProvider.authenticate(), I assign all logged-in users the ROLE_USER role -- that's what lets me then test for that role in my intercept-url elements. You'll want to make this match whatever role you want to test for, or even assign roles based on Active Directory groups or whatever.</p>\n\n<p>Finally, and a corollary to that, the way I implemented LdapAuthenticationProvider.authenticate() gives all users with valid AD accounts the same ROLE_USER role. Obviously, in that method, you can perform further tests on the user (i.e., is the user in a specific AD group?) and assign roles that way, or even test for some condition before even granting the user access at <em>all</em>.</p>\n" }, { "answer_id": 215276, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I was able to authenticate against active directory using spring security 2.0.4. </p>\n\n<p>I documented the settings</p>\n\n<p><a href=\"http://maniezhilan.blogspot.com/2008/10/spring-security-204-with-active.html/&quot;here&quot;\" rel=\"nofollow noreferrer\">http://maniezhilan.blogspot.com/2008/10/spring-security-204-with-active.html</a></p>\n" }, { "answer_id": 2370550, "author": "er4z0r", "author_id": 202020, "author_profile": "https://Stackoverflow.com/users/202020", "pm_score": 2, "selected": false, "text": "<p>Just to bring this to an up-to-date status.\nSpring Security 3.0 has a <a href=\"http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/ldap/authentication/package-summary.html\" rel=\"nofollow noreferrer\">complete package</a> with default implementations devoted to ldap-bind as well as query and compare authentication.</p>\n" }, { "answer_id": 8145899, "author": "Gaurav", "author_id": 1046818, "author_profile": "https://Stackoverflow.com/users/1046818", "pm_score": 0, "selected": false, "text": "<p>LDAP authentication without SSL is not safe anyone can see the user credential when those are transffered to LDAP server. I suggest using LDAPS:\\ protocol for authentication. It doesn't require any major change on spring part but you may ran with some issues related to certificates. See <a href=\"http://javarevisited.blogspot.com/2011/11/ldap-authentication-active-directory.html\" rel=\"nofollow\">LDAP Active Directory authentication in Spring with SSL</a> for more details</p>\n" }, { "answer_id": 8734935, "author": "Shaun the Sheep", "author_id": 241990, "author_profile": "https://Stackoverflow.com/users/241990", "pm_score": 4, "selected": false, "text": "<p>For reference, Spring Security 3.1 has an authentication provider <a href=\"http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory\" rel=\"noreferrer\">specifically for Active Directory</a>.</p>\n" }, { "answer_id": 12468450, "author": "rjc730", "author_id": 714366, "author_profile": "https://Stackoverflow.com/users/714366", "pm_score": 0, "selected": false, "text": "<p>From Luke's answer above:</p>\n\n<blockquote>\n <p>For reference, Spring Security 3.1 has an authentication provider\n [specifically for Active Directory][1].</p>\n \n <p>[1]:\n <a href=\"http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory\" rel=\"nofollow\">http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory</a></p>\n</blockquote>\n\n<p>I tried the above with Spring Security 3.1.1: there are some slight changes from ldap - the active directory groups the user is a member of come through as original case.</p>\n\n<p>Previously under ldap the groups were capitalized and prefixed with \"ROLE_\", which made them easy to find with a text search in a project but obviously might case problems in a unix group if for some strange reason had 2 separate groups only differentiated by case(ie accounts and Accounts).</p>\n\n<p>Also the syntax requires manual specification of the domain controller name and port, which makes it a bit scary for redundancy. Surely there is a way of looking up the SRV DNS record for the domain in java, ie equivalent of(from Samba 4 howto):</p>\n\n<pre><code>$ host -t SRV _ldap._tcp.samdom.example.com.\n_ldap._tcp.samdom.example.com has SRV record 0 100 389 samba.samdom.example.com.\n</code></pre>\n\n<p>followed by regular A lookup:</p>\n\n<pre><code>$ host -t A samba.samdom.example.com.\nsamba.samdom.example.com has address 10.0.0.1\n</code></pre>\n\n<p>(Actually might need to lookup _kerberos SRV record too...)</p>\n\n<p>The above was with Samba4.0rc1, we are progressively upgrading from Samba 3.x LDAP environment to Samba AD one.</p>\n" }, { "answer_id": 26425976, "author": "Cookalino", "author_id": 1069027, "author_profile": "https://Stackoverflow.com/users/1069027", "pm_score": 1, "selected": false, "text": "<p>As in Luke's answer above:</p>\n\n<blockquote>\n <p>Spring Security 3.1 has an authentication provider specifically for Active Directory.</p>\n</blockquote>\n\n<p>Here is the detail of how this can be easily done using ActiveDirectoryLdapAuthenticationProvider.</p>\n\n<p>In resources.groovy:</p>\n\n<pre><code>ldapAuthProvider1(ActiveDirectoryLdapAuthenticationProvider,\n \"mydomain.com\",\n \"ldap://mydomain.com/\"\n)\n</code></pre>\n\n<p>In Config.groovy:</p>\n\n<pre><code>grails.plugin.springsecurity.providerNames = ['ldapAuthProvider1']\n</code></pre>\n\n<p>This is all the code you need. You can pretty much remove all other grails.plugin.springsecurity.ldap.* settings in Config.groovy as they don't apply to this AD setup.</p>\n\n<p>For documentation, see:\n<a href=\"http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory\" rel=\"nofollow\">http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap-active-directory</a></p>\n" }, { "answer_id": 36738996, "author": "Riddhi Gohil", "author_id": 5947458, "author_profile": "https://Stackoverflow.com/users/5947458", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>If you are using Spring <strong>security 4</strong> you can also implement same using\n given class</p>\n \n <ul>\n <li>SecurityConfig.java</li>\n </ul>\n</blockquote>\n\n<pre><code>@Configuration\n@EnableWebSecurity\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\n\n\nstatic final Logger LOGGER = LoggerFactory.getLogger(SecurityConfig.class);\n\n@Autowired\nprotected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {\n auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider());\n}\n\n@Override\nprotected void configure(HttpSecurity http) throws Exception {\n http\n .authorizeRequests()\n .antMatchers(\"/\").permitAll()\n .anyRequest().authenticated();\n .and()\n .formLogin()\n .and()\n .logout();\n}\n\n@Bean\npublic AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {\n ActiveDirectoryLdapAuthenticationProvider authenticationProvider = \n new ActiveDirectoryLdapAuthenticationProvider(\"&lt;domain&gt;\", \"&lt;url&gt;\");\n\n authenticationProvider.setConvertSubErrorCodesToExceptions(true);\n authenticationProvider.setUseAuthenticationRequestCredentials(true);\n\n return authenticationProvider;\n}\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13379/" ]
I'm writing a Spring web application that requires users to login. My company has an Active Directory server that I'd like to make use of for this purpose. However, I'm having trouble using Spring Security to connect to the server. I'm using Spring 2.5.5 and Spring Security 2.0.3, along with Java 1.6. If I change the LDAP URL to the wrong IP address, it doesn't throw an exception or anything, so I'm wondering if it's even *trying* to connect to the server to begin with. Although the web application starts up just fine, any information I enter into the login page is rejected. I had previously used an InMemoryDaoImpl, which worked fine, so the rest of my application seems to be configured correctly. Here are my security-related beans: ``` <beans:bean id="ldapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider"> <beans:constructor-arg> <beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator"> <beans:constructor-arg ref="initialDirContextFactory" /> <beans:property name="userDnPatterns"> <beans:list> <beans:value>CN={0},OU=SBSUsers,OU=Users,OU=MyBusiness,DC=Acme,DC=com</beans:value> </beans:list> </beans:property> </beans:bean> </beans:constructor-arg> </beans:bean> <beans:bean id="userDetailsService" class="org.springframework.security.userdetails.ldap.LdapUserDetailsManager"> <beans:constructor-arg ref="initialDirContextFactory" /> </beans:bean> <beans:bean id="initialDirContextFactory" class="org.springframework.security.ldap.DefaultInitialDirContextFactory"> <beans:constructor-arg value="ldap://192.168.123.456:389/DC=Acme,DC=com" /> </beans:bean> ```
I had the same banging-my-head-against-the-wall experience you did, and ended up writing a custom authentication provider that does an LDAP query against the Active Directory server. So my security-related beans are: ``` <beans:bean id="contextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource"> <beans:constructor-arg value="ldap://hostname.queso.com:389/" /> </beans:bean> <beans:bean id="ldapAuthenticationProvider" class="org.queso.ad.service.authentication.LdapAuthenticationProvider"> <beans:property name="authenticator" ref="ldapAuthenticator" /> <custom-authentication-provider /> </beans:bean> <beans:bean id="ldapAuthenticator" class="org.queso.ad.service.authentication.LdapAuthenticatorImpl"> <beans:property name="contextFactory" ref="contextSource" /> <beans:property name="principalPrefix" value="QUESO\" /> </beans:bean> ``` Then the LdapAuthenticationProvider class: ``` /** * Custom Spring Security authentication provider which tries to bind to an LDAP server with * the passed-in credentials; of note, when used with the custom {@link LdapAuthenticatorImpl}, * does <strong>not</strong> require an LDAP username and password for initial binding. * * @author Jason */ public class LdapAuthenticationProvider implements AuthenticationProvider { private LdapAuthenticator authenticator; public Authentication authenticate(Authentication auth) throws AuthenticationException { // Authenticate, using the passed-in credentials. DirContextOperations authAdapter = authenticator.authenticate(auth); // Creating an LdapAuthenticationToken (rather than using the existing Authentication // object) allows us to add the already-created LDAP context for our app to use later. LdapAuthenticationToken ldapAuth = new LdapAuthenticationToken(auth, "ROLE_USER"); InitialLdapContext ldapContext = (InitialLdapContext) authAdapter .getObjectAttribute("ldapContext"); if (ldapContext != null) { ldapAuth.setContext(ldapContext); } return ldapAuth; } public boolean supports(Class clazz) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(clazz)); } public LdapAuthenticator getAuthenticator() { return authenticator; } public void setAuthenticator(LdapAuthenticator authenticator) { this.authenticator = authenticator; } } ``` Then the LdapAuthenticatorImpl class: ``` /** * Custom Spring Security LDAP authenticator which tries to bind to an LDAP server using the * passed-in credentials; does <strong>not</strong> require "master" credentials for an * initial bind prior to searching for the passed-in username. * * @author Jason */ public class LdapAuthenticatorImpl implements LdapAuthenticator { private DefaultSpringSecurityContextSource contextFactory; private String principalPrefix = ""; public DirContextOperations authenticate(Authentication authentication) { // Grab the username and password out of the authentication object. String principal = principalPrefix + authentication.getName(); String password = ""; if (authentication.getCredentials() != null) { password = authentication.getCredentials().toString(); } // If we have a valid username and password, try to authenticate. if (!("".equals(principal.trim())) && !("".equals(password.trim()))) { InitialLdapContext ldapContext = (InitialLdapContext) contextFactory .getReadWriteContext(principal, password); // We need to pass the context back out, so that the auth provider can add it to the // Authentication object. DirContextOperations authAdapter = new DirContextAdapter(); authAdapter.addAttributeValue("ldapContext", ldapContext); return authAdapter; } else { throw new BadCredentialsException("Blank username and/or password!"); } } /** * Since the InitialLdapContext that's stored as a property of an LdapAuthenticationToken is * transient (because it isn't Serializable), we need some way to recreate the * InitialLdapContext if it's null (e.g., if the LdapAuthenticationToken has been serialized * and deserialized). This is that mechanism. * * @param authenticator * the LdapAuthenticator instance from your application's context * @param auth * the LdapAuthenticationToken in which to recreate the InitialLdapContext * @return */ static public InitialLdapContext recreateLdapContext(LdapAuthenticator authenticator, LdapAuthenticationToken auth) { DirContextOperations authAdapter = authenticator.authenticate(auth); InitialLdapContext context = (InitialLdapContext) authAdapter .getObjectAttribute("ldapContext"); auth.setContext(context); return context; } public DefaultSpringSecurityContextSource getContextFactory() { return contextFactory; } /** * Set the context factory to use for generating a new LDAP context. * * @param contextFactory */ public void setContextFactory(DefaultSpringSecurityContextSource contextFactory) { this.contextFactory = contextFactory; } public String getPrincipalPrefix() { return principalPrefix; } /** * Set the string to be prepended to all principal names prior to attempting authentication * against the LDAP server. (For example, if the Active Directory wants the domain-name-plus * backslash prepended, use this.) * * @param principalPrefix */ public void setPrincipalPrefix(String principalPrefix) { if (principalPrefix != null) { this.principalPrefix = principalPrefix; } else { this.principalPrefix = ""; } } } ``` And finally, the LdapAuthenticationToken class: ``` /** * <p> * Authentication token to use when an app needs further access to the LDAP context used to * authenticate the user. * </p> * * <p> * When this is the Authentication object stored in the Spring Security context, an application * can retrieve the current LDAP context thusly: * </p> * * <pre> * LdapAuthenticationToken ldapAuth = (LdapAuthenticationToken) SecurityContextHolder * .getContext().getAuthentication(); * InitialLdapContext ldapContext = ldapAuth.getContext(); * </pre> * * @author Jason * */ public class LdapAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = -5040340622950665401L; private Authentication auth; transient private InitialLdapContext context; private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); /** * Construct a new LdapAuthenticationToken, using an existing Authentication object and * granting all users a default authority. * * @param auth * @param defaultAuthority */ public LdapAuthenticationToken(Authentication auth, GrantedAuthority defaultAuthority) { this.auth = auth; if (auth.getAuthorities() != null) { this.authorities.addAll(Arrays.asList(auth.getAuthorities())); } if (defaultAuthority != null) { this.authorities.add(defaultAuthority); } super.setAuthenticated(true); } /** * Construct a new LdapAuthenticationToken, using an existing Authentication object and * granting all users a default authority. * * @param auth * @param defaultAuthority */ public LdapAuthenticationToken(Authentication auth, String defaultAuthority) { this(auth, new GrantedAuthorityImpl(defaultAuthority)); } public GrantedAuthority[] getAuthorities() { GrantedAuthority[] authoritiesArray = this.authorities.toArray(new GrantedAuthority[0]); return authoritiesArray; } public void addAuthority(GrantedAuthority authority) { this.authorities.add(authority); } public Object getCredentials() { return auth.getCredentials(); } public Object getPrincipal() { return auth.getPrincipal(); } /** * Retrieve the LDAP context attached to this user's authentication object. * * @return the LDAP context */ public InitialLdapContext getContext() { return context; } /** * Attach an LDAP context to this user's authentication object. * * @param context * the LDAP context */ public void setContext(InitialLdapContext context) { this.context = context; } } ``` You'll notice that there are a few bits in there that you might not need. For example, my app needed to retain the successfully-logged-in LDAP context for further use by the user once logged in -- the app's purpose is to let users log in via their AD credentials and then perform further AD-related functions. So because of that, I have a custom authentication token, LdapAuthenticationToken, that I pass around (rather than Spring's default Authentication token) which allows me to attach the LDAP context. In LdapAuthenticationProvider.authenticate(), I create that token and pass it back out; in LdapAuthenticatorImpl.authenticate(), I attach the logged-in context to the return object so that it can be added to the user's Spring authentication object. Also, in LdapAuthenticationProvider.authenticate(), I assign all logged-in users the ROLE\_USER role -- that's what lets me then test for that role in my intercept-url elements. You'll want to make this match whatever role you want to test for, or even assign roles based on Active Directory groups or whatever. Finally, and a corollary to that, the way I implemented LdapAuthenticationProvider.authenticate() gives all users with valid AD accounts the same ROLE\_USER role. Obviously, in that method, you can perform further tests on the user (i.e., is the user in a specific AD group?) and assign roles that way, or even test for some condition before even granting the user access at *all*.
84,716
<p>I use the jQuery <a href="http://docs.jquery.com/Utilities/jQuery.extend" rel="nofollow noreferrer">extend</a> function to extend a class prototype.</p> <p>For example:</p> <pre><code>MyWidget = function(name_var) { this.init(name_var); } $.extend(MyWidget.prototype, { // object variables widget_name: '', init: function(widget_name) { // do initialization here this.widget_name = widget_name; }, doSomething: function() { // an example object method alert('my name is '+this.widget_name); } }); // example of using the class built above var widget1 = new MyWidget('widget one'); widget1.doSomething(); </code></pre> <p>Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two?</p>
[ { "answer_id": 84824, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "<p>I quite like John Resig's <a href=\"http://ejohn.org/blog/simple-javascript-inheritance/\" rel=\"noreferrer\">Simple JavaScript Inheritance</a>.</p>\n\n<pre><code>var MyWidget = Class.extend({\n init: function(widget_name){\n this.widget_name = widget_name;\n },\n\n doSomething: function() {\n alert('my name is ' + this.widget_name);\n }\n});\n</code></pre>\n\n<p>NB: The \"Class\" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above.</p>\n" }, { "answer_id": 85367, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 2, "selected": false, "text": "<p>jQuery doesn't offer that. But <a href=\"http://www.prototypejs.org\" rel=\"nofollow noreferrer\">Prototype</a> does, via <a href=\"http://www.prototypejs.org/api/class/create\" rel=\"nofollow noreferrer\">Class.create</a>.</p>\n" }, { "answer_id": 88452, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 4, "selected": false, "text": "<p>To summarise what I have learned so far:</p>\n\n<p>Here is the Base function that makes Class.extend() work in jQuery (Copied from <a href=\"http://ejohn.org/blog/simple-javascript-inheritance/\" rel=\"nofollow noreferrer\">Simple JavaScript Inheritance</a> by John Resig):</p>\n\n<pre><code>// Inspired by base2 and Prototype\n(function(){\n var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\\b_super\\b/ : /.*/;\n\n // The base Class implementation (does nothing)\n this.Class = function(){};\n\n // Create a new Class that inherits from this class\n Class.extend = function(prop) {\n var _super = this.prototype;\n\n // Instantiate a base class (but only create the instance,\n // don't run the init constructor)\n initializing = true;\n var prototype = new this();\n initializing = false;\n\n // Copy the properties over onto the new prototype\n for (var name in prop) {\n // Check if we're overwriting an existing function\n prototype[name] = typeof prop[name] == \"function\" &amp;&amp;\n typeof _super[name] == \"function\" &amp;&amp; fnTest.test(prop[name]) ?\n (function(name, fn){\n return function() {\n var tmp = this._super;\n\n // Add a new ._super() method that is the same method\n // but on the super-class\n this._super = _super[name];\n\n // The method only need to be bound temporarily, so we\n // remove it when we're done executing\n var ret = fn.apply(this, arguments); \n this._super = tmp;\n\n return ret;\n };\n })(name, prop[name]) :\n prop[name];\n }\n\n // The dummy class constructor\n function Class() {\n // All construction is actually done in the init method\n if ( !initializing &amp;&amp; this.init )\n this.init.apply(this, arguments);\n }\n\n // Populate our constructed prototype object\n Class.prototype = prototype;\n\n // Enforce the constructor to be what we expect\n Class.constructor = Class;\n\n // And make this class extendable\n Class.extend = arguments.callee;\n\n return Class;\n };\n})();\n</code></pre>\n\n<p>Once you have run executed this code, then that makes the following code from <a href=\"https://stackoverflow.com/questions/84716/is-there-a-better-way-to-create-an-object-oriented-class-with-jquery#84824\">insin's answer</a> possible:</p>\n\n<pre><code>var MyWidget = Class.extend({\n init: function(widget_name){\n this.widget_name = widget_name;\n },\n\n doSomething: function() {\n alert('my name is ' + this.widget_name);\n }\n});\n</code></pre>\n\n<p>This is a nice, clean solution. But I'm interested to see if anyone has a solution that doesn't require adding anything to jquery.</p>\n" }, { "answer_id": 2917004, "author": "ola l martins", "author_id": 351415, "author_profile": "https://Stackoverflow.com/users/351415", "pm_score": 0, "selected": false, "text": "<p>This is long gone dead, but if anyone else searches for jQuery creating class - check this plugin:\n<a href=\"http://plugins.jquery.com/project/HJS\" rel=\"nofollow noreferrer\">http://plugins.jquery.com/project/HJS</a></p>\n" }, { "answer_id": 14007970, "author": "Paul Allsopp", "author_id": 1620987, "author_profile": "https://Stackoverflow.com/users/1620987", "pm_score": 5, "selected": false, "text": "<p>Why not just use the simple OOP that JavaScript itself provides...long before jQuery?</p>\n\n<pre><code>var myClass = function(){};\nmyClass.prototype = {\n some_property: null,\n some_other_property: 0,\n\n doSomething: function(msg) {\n this.some_property = msg;\n alert(this.some_property);\n }\n};\n</code></pre>\n\n<p>Then you just create an instance of the class:</p>\n\n<pre><code>var myClassObject = new myClass();\nmyClassObject.doSomething(\"Hello Worlds\");\n</code></pre>\n\n<p>Simple!</p>\n" }, { "answer_id": 14426704, "author": "Sam Arul Raj T", "author_id": 493662, "author_profile": "https://Stackoverflow.com/users/493662", "pm_score": 0, "selected": false, "text": "<p>I found this website a impressive one for oops in javascript <a href=\"http://jsperf.com/jquery-class-create-vs-pure-js-function/3\" rel=\"nofollow\">Here</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850/" ]
I use the jQuery [extend](http://docs.jquery.com/Utilities/jQuery.extend) function to extend a class prototype. For example: ``` MyWidget = function(name_var) { this.init(name_var); } $.extend(MyWidget.prototype, { // object variables widget_name: '', init: function(widget_name) { // do initialization here this.widget_name = widget_name; }, doSomething: function() { // an example object method alert('my name is '+this.widget_name); } }); // example of using the class built above var widget1 = new MyWidget('widget one'); widget1.doSomething(); ``` Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two?
I quite like John Resig's [Simple JavaScript Inheritance](http://ejohn.org/blog/simple-javascript-inheritance/). ``` var MyWidget = Class.extend({ init: function(widget_name){ this.widget_name = widget_name; }, doSomething: function() { alert('my name is ' + this.widget_name); } }); ``` NB: The "Class" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above.
84,717
<p>What are the best conventions of naming testing-assemblies in .NET (or any other language or platform)?</p> <p>What I'm mainly split between are these options (please provide others!):</p> <ul> <li><strong>Company.Website</strong> - <em>the project</em></li> <li><strong>Company.Website.Tests</strong></li> </ul> <p><em>or</em></p> <ul> <li><strong>Company.Website</strong></li> <li><strong>Company.WebsiteTests</strong></li> </ul> <p>The problem with the first solution is that it looks like .Tests are a sub-namespace to the site, while they really are more parallel in my mind. What happens when a new sub-namespace comes into play, like <strong>Company.Website.Controls</strong>, where should I put the tests for that namespace, for instance?</p> <p>Maybe it should even be: <strong>Tests.Company.Website</strong> and <strong>Tests.Company.Website.Controls</strong>, and so on.</p>
[ { "answer_id": 84742, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 4, "selected": false, "text": "<p>I personally would go with</p>\n\n<p>Company.Tests.Website</p>\n\n<p>That way you have a common tests namespace and projects inside it, following the same structure as the actual project.</p>\n" }, { "answer_id": 84750, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 3, "selected": false, "text": "<p>I actually have an alternate parallel root.</p>\n\n<p>Tests.Company.Website</p>\n\n<p>It works nicely for disambiguating things when you have new sub namespaces.</p>\n" }, { "answer_id": 84751, "author": "Dario Solera", "author_id": 16026, "author_profile": "https://Stackoverflow.com/users/16026", "pm_score": 0, "selected": false, "text": "<p>I usually name test projects <em>Project-Tests</em> for brevity in Solution Explorer, and I use <em>Company.Namespace.Tests</em> for namespaces.</p>\n" }, { "answer_id": 84762, "author": "Wheelie", "author_id": 1131, "author_profile": "https://Stackoverflow.com/users/1131", "pm_score": 3, "selected": false, "text": "<p>I'm a big fan of structuring the test namespace like this:</p>\n\n<p><strong>Company.Tests.Website.xxx</strong></p>\n\n<p><strong>Company.Tests.Website.Controls</strong></p>\n\n<p>Like you, I think of the tests as a parallel namespace structure to the main code and this provides you with that. It also has the advantage that, since the namespace still starts with your company name you shouldn't have any naming collisions with 3rd party libraries</p>\n" }, { "answer_id": 84779, "author": "skb", "author_id": 14101, "author_profile": "https://Stackoverflow.com/users/14101", "pm_score": 0, "selected": false, "text": "<p>I prefer to go with:</p>\n\n<p>Company.Website.Tests</p>\n\n<p>I don't care about any sub-namespaces like Company.Website.Controls, all of the tests go into the same namespace: Company.Website.Tests. You don't want your test namespaces to HAVE to be in parrallel with the rest of your code because it just makes refactoring namespaces take twice as long.</p>\n" }, { "answer_id": 84801, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 0, "selected": false, "text": "<p>I prefer Company.Website.Spec and usually have one test project per solution</p>\n" }, { "answer_id": 84809, "author": "Tom Carr", "author_id": 14954, "author_profile": "https://Stackoverflow.com/users/14954", "pm_score": 1, "selected": false, "text": "<p>We follow an embedded approach:</p>\n\n<pre><code>Company.Namespace.Test\nCompany.Namespace.Data.Test\n</code></pre>\n\n<p>This way the tests are close to the code that is being tested, without having to toggle back and forth between projects or hunt down references to ensure there is a test covering a particular method. We also don't have to maintain two separate, but identical, hierarchies.</p>\n\n<p>We can also test distinct parts of the code as we enhance and develop.</p>\n\n<p>Seems a little weird at first, but over the long term it has worked really well for us.</p>\n" }, { "answer_id": 84972, "author": "Claus Thomsen", "author_id": 15555, "author_profile": "https://Stackoverflow.com/users/15555", "pm_score": 6, "selected": true, "text": "<p>I will go with </p>\n\n<pre><code>* Company.Website - the project\n* Company.Website.Tests\n</code></pre>\n\n<p>The short reason and answer is simple, testing and project are linked in code, therefore it should share namespace.</p>\n\n<p>If you want splitting of code and testing in a solution you have that option anyway. e.g. you can set up a solution with </p>\n\n<p>-Code Folder</p>\n\n<ul>\n<li>Company.Website</li>\n</ul>\n\n<p>-Tests Folder</p>\n\n<ul>\n<li>Company.Website.Tests</li>\n</ul>\n" }, { "answer_id": 85160, "author": "Brad Osterloo", "author_id": 9162, "author_profile": "https://Stackoverflow.com/users/9162", "pm_score": 1, "selected": false, "text": "<p>I too prefer \"Tests\" prefixing the actual name of the assembly so that its easy to see all of my unit test assemblies listed alphabetically together when I mass-select them to pull into NUNit or whatever test harness you are using.</p>\n\n<p>So if Website were the name of my solution (and assemblies), I suggest -</p>\n\n<p><strong>Tests.Website.dll</strong> to go along with the actual code assembly <strong>Website.Dll</strong></p>\n" }, { "answer_id": 90168, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 0, "selected": false, "text": "<p>With MVC starting to become a reality in the .net web development world, I would start thinking along those lines. Remember that M, V and C are distinct components, so:</p>\n\n<ul>\n<li>Company.Namespace.Website</li>\n<li>Company.Namespace.Website.Core</li>\n<li>Company.Namspance.Website.Core.Tests</li>\n<li>Company.Namespace.Website.Model</li>\n<li>Company.Namespace.Website.Model.Tests</li>\n</ul>\n\n<p>Website is your lightweight view. \nCore contains controllers, helpers, the view interfaces, etc. Core.Tests are your tests for said Core.\nModel is for your data model. The cool thing here is that your model tests can automate your database specific tests.</p>\n\n<p>This may be overkill for some people, but I find that it allows me to separate concerns fairly easily.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
What are the best conventions of naming testing-assemblies in .NET (or any other language or platform)? What I'm mainly split between are these options (please provide others!): * **Company.Website** - *the project* * **Company.Website.Tests** *or* * **Company.Website** * **Company.WebsiteTests** The problem with the first solution is that it looks like .Tests are a sub-namespace to the site, while they really are more parallel in my mind. What happens when a new sub-namespace comes into play, like **Company.Website.Controls**, where should I put the tests for that namespace, for instance? Maybe it should even be: **Tests.Company.Website** and **Tests.Company.Website.Controls**, and so on.
I will go with ``` * Company.Website - the project * Company.Website.Tests ``` The short reason and answer is simple, testing and project are linked in code, therefore it should share namespace. If you want splitting of code and testing in a solution you have that option anyway. e.g. you can set up a solution with -Code Folder * Company.Website -Tests Folder * Company.Website.Tests
84,759
<p>This is an Eclipse question, and you can assume the Java package for all these Eclipse classes is <code>org.eclipse.core.resources</code>. </p> <p>I want to get an <code>IFile</code> corresponding to a location <code>String</code> I have:</p> <pre><code> "platform:/resource/Tracbility_All_Supported_lib/processes/gastuff/globalht/GlobalHTInterface.wsdl" </code></pre> <p>I have the enclosing <code>IWorkspace</code> and <code>IWorkspaceRoot</code>. If I had the <code>IPath</code> corresponding to the location above, I could simply call <code>IWorkspaceRoot.getFileForLocation(IPath)</code>.</p> <p>How do I get the corresponding <code>IPath</code> from the location <code>String</code>? Or is there some other way to get the corresponding <code>IFile</code>?</p>
[ { "answer_id": 85074, "author": "Paul Reiners", "author_id": 7648, "author_profile": "https://Stackoverflow.com/users/7648", "pm_score": 2, "selected": false, "text": "<pre><code>String platformLocationString = portTypeContainer\n .getLocation();\nString locationString = platformLocationString\n .substring(\"platform:/resource/\".length());\nIWorkspace workspace = ResourcesPlugin.getWorkspace();\nIWorkspaceRoot workspaceRoot = workspace.getRoot();\nIFile wSDLFile = (IFile) workspaceRoot\n .findMember(locationString);\n</code></pre>\n" }, { "answer_id": 85128, "author": "Tirno", "author_id": 9886, "author_profile": "https://Stackoverflow.com/users/9886", "pm_score": 3, "selected": true, "text": "<p>org.eclipse.core.runtime.Path implements IPath.</p>\n\n<pre><code>IPath p = new Path(locationString);\nIWorkspaceRoot.getFileForLocation(p);\n</code></pre>\n\n<p>This would have worked had the location string not been a URL of type \"platform:\"</p>\n\n<p>For this particular case, notes in org.eclipse.core.runtime.Platform javadoc indicate that the \"correct\" solution is something like</p>\n\n<pre><code>fileUrl = FileLocator.toFileURL(new URL(locationString)); \nIWorkspaceRoot.getFileForLocation(fileUrl.getPath());\n</code></pre>\n\n<p>@[Paul Reiners] your solution apparently assumes that the workspace root is going to be in the \"resources\" folder</p>\n" }, { "answer_id": 85502, "author": "Roel Spilker", "author_id": 12634, "author_profile": "https://Stackoverflow.com/users/12634", "pm_score": 2, "selected": false, "text": "<p>Since IWorkspaceRoot is an IContainer, can't you just use <code>workspaceRoot.findMember(String name)</code> and cast the resulting IResource to IFile?</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7648/" ]
This is an Eclipse question, and you can assume the Java package for all these Eclipse classes is `org.eclipse.core.resources`. I want to get an `IFile` corresponding to a location `String` I have: ``` "platform:/resource/Tracbility_All_Supported_lib/processes/gastuff/globalht/GlobalHTInterface.wsdl" ``` I have the enclosing `IWorkspace` and `IWorkspaceRoot`. If I had the `IPath` corresponding to the location above, I could simply call `IWorkspaceRoot.getFileForLocation(IPath)`. How do I get the corresponding `IPath` from the location `String`? Or is there some other way to get the corresponding `IFile`?
org.eclipse.core.runtime.Path implements IPath. ``` IPath p = new Path(locationString); IWorkspaceRoot.getFileForLocation(p); ``` This would have worked had the location string not been a URL of type "platform:" For this particular case, notes in org.eclipse.core.runtime.Platform javadoc indicate that the "correct" solution is something like ``` fileUrl = FileLocator.toFileURL(new URL(locationString)); IWorkspaceRoot.getFileForLocation(fileUrl.getPath()); ``` @[Paul Reiners] your solution apparently assumes that the workspace root is going to be in the "resources" folder
84,782
<p>I am writting JAVA programme using JDBC for database conntectivity , I am calling one stored procedure in that which is returning ORACLE REF CURSOR , IS there any way I can handle that without importing ORACLE PACKAGES ?</p>
[ { "answer_id": 85766, "author": "jwiklund", "author_id": 4208, "author_profile": "https://Stackoverflow.com/users/4208", "pm_score": 2, "selected": true, "text": "<p>I think I tried to do this a while ago and kind of gave up (I guess you could figure out what int value the OracleTypes.REF_CURSOR is and then use that int value, but that's a hack). If you got the patience you could define a record (or object) type and define the the cursor as a cursor with type since that can be cast using table to a value that is selectable like regular tables, ie</p>\n\n<pre><code>select * from table( sp_returning( ? ) )\n</code></pre>\n\n<p>I did a quick google on ref cursor and jdbc and it looks like it might be an oracle extension which would explain why there is no standard way to access the data.</p>\n" }, { "answer_id": 411052, "author": "tuinstoel", "author_id": 43901, "author_profile": "https://Stackoverflow.com/users/43901", "pm_score": -1, "selected": false, "text": "<p>Doing </p>\n\n<pre><code>select * from table( sp_returning( ? ) )\n</code></pre>\n\n<p>is slower than returning a ref cursor. </p>\n\n<p>I can use a ref cursor in combination with C#, why can't you do it with Java? I'm sure there are plenty examples. </p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14299/" ]
I am writting JAVA programme using JDBC for database conntectivity , I am calling one stored procedure in that which is returning ORACLE REF CURSOR , IS there any way I can handle that without importing ORACLE PACKAGES ?
I think I tried to do this a while ago and kind of gave up (I guess you could figure out what int value the OracleTypes.REF\_CURSOR is and then use that int value, but that's a hack). If you got the patience you could define a record (or object) type and define the the cursor as a cursor with type since that can be cast using table to a value that is selectable like regular tables, ie ``` select * from table( sp_returning( ? ) ) ``` I did a quick google on ref cursor and jdbc and it looks like it might be an oracle extension which would explain why there is no standard way to access the data.
84,795
<p>How can I optimize the following code, which currently takes over 2 minutes to retrieve and loop through 800+ records from a pool of over 100K records, returning 6 fields per record (adds approximately 20 seconds per additional field):</p> <pre><code>&lt;cfset dllPath="C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.DirectoryServices.dll" /&gt; &lt;cfset LDAPPath="LDAP://" &amp; arguments.searchPath /&gt; &lt;cfset theLookUp=CreateObject(".NET","System.DirectoryServices.DirectoryEntry", dllPath).init(LDAPPath) /&gt; &lt;cfset theSearch=CreateObject(".NET","System.DirectoryServices.DirectorySearcher", dllPath).init(theLookUp) /&gt; &lt;cfset theSearch.Set_Filter(arguments.theFilter) /&gt; &lt;cfset theObject = theSearch.FindAll() /&gt; &lt;cfloop index="row" from="#startRow#" to="#endRow#"&gt; &lt;cfset QueryAddRow(theQuery) /&gt; &lt;cfloop list="#columnList#" index="col"&gt; &lt;cfloop from="0" to="#theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Count()-1#" index="item"&gt; &lt;cftry&gt; &lt;cfset theQuery[col][theQuery.recordCount]=ListAppend(theQuery[col][theQuery.recordCount],theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Item(item),"|") /&gt; &lt;cfcatch type="any"&gt; &lt;/cfcatch&gt; &lt;/cftry&gt; &lt;/cfloop&gt; &lt;/cfloop&gt; &lt;/cfloop&gt; </code></pre>
[ { "answer_id": 85077, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 2, "selected": false, "text": "<p>It's been a long time since I touched CF, but I can give some hints in pseudo-code. For one thing, this expression is extremely inefficent:</p>\n\n<p>#theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Count()-1#</p>\n\n<p>Take the first part for example, Get_Item(row) - your code causes CF to go retrieve the row and its properties for each iteration of the #columnList# loop; and to top it all, you're doing that TWICE per iteration of columnlist (once for loop and again for the inner cfset). If you think about it, it only needs to retrieve the row for each iteration of the outer loop (from #sfstart# to #cfend). So, in pseudo-code do this:</p>\n\n<blockquote>\n <p>for each row between start and end</p>\n \n <blockquote>\n <p>cfset props = #theobject.get_item(row).get_properties()#</p>\n \n <p>for each col in #columnlist#</p>\n \n <blockquote>\n <p>cfset currentcol = #props.getitem(col)#</p>\n \n <p>cfset count = #currentcol.getcount() - 1#</p>\n \n <p>foreach item from 0 to #count#</p>\n \n <blockquote>\n <p>cfset #currentcol.getItem(item)# etc...</p>\n </blockquote>\n </blockquote>\n </blockquote>\n</blockquote>\n\n<p>Make sense? Every time you enter a loop, cache objects that will be reused in that scope (or child scopes) in a variable. That means you are only grabbing the column object once per iteration of the column loop. All variables defined in outer scopes are available in the inner scopes, as you can see in what I've done above. I know its tempting to cut and paste from previous lines, but don't. It only hurts you in the end.</p>\n\n<p>hope this helps,</p>\n\n<p>Oisin</p>\n" }, { "answer_id": 85877, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 1, "selected": false, "text": "<p>Additionally, using a cftry block in each loop is likely slowing this down quite a bit. Unless you are expecting individual rows to fail (and you need to continue from that point), I would suggest a single try/catch block for the entire process. Try/catch is an expensive operation.</p>\n" }, { "answer_id": 85913, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 3, "selected": true, "text": "<p>How large is the list of items for the inner loop?</p>\n\n<p>Switching to an array <em>might</em> be faster if there is a significantly large number of items.</p>\n\n<p>I have implemented this alongside x0n's suggestions...</p>\n\n<pre><code>&lt;cfset dllPath=\"C:\\WINDOWS\\Microsoft.NET\\Framework\\v1.1.4322\\System.DirectoryServices.dll\" /&gt;\n&lt;cfset LDAPPath=\"LDAP://\" &amp; arguments.searchPath /&gt;\n&lt;cfset theLookUp=CreateObject(\".NET\",\"System.DirectoryServices.DirectoryEntry\", dllPath).init(LDAPPath) /&gt;\n&lt;cfset theSearch=CreateObject(\".NET\",\"System.DirectoryServices.DirectorySearcher\", dllPath).init(theLookUp) /&gt;\n&lt;cfset theSearch.Set_Filter(arguments.theFilter) /&gt;\n&lt;cfset theObject = theSearch.FindAll() /&gt;\n\n&lt;cfloop index=\"row\" from=\"#startRow#\" to=\"#endRow#\"&gt;\n\n &lt;cfset Props = theObject.get_item(row).get_properties() /&gt;\n\n &lt;cfset QueryAddRow(theQuery) /&gt;\n\n &lt;cfloop list=\"#columnList#\" index=\"col\"&gt;\n\n &lt;cfset CurrentCol = Props.getItem(col) /&gt;\n\n &lt;cfset ItemArray = ArrayNew(1)/&gt;\n &lt;cfloop from=\"0\" to=\"#CurrentCol.getcount() - 1#\" index=\"item\"&gt;\n &lt;cftry&gt;\n &lt;cfset ArrayAppend( ItemArray , CurrentCol.Get_Item(item) )/&gt;\n &lt;cfcatch type=\"any\"&gt;\n &lt;/cfcatch&gt;\n &lt;/cftry&gt;\n &lt;/cfloop&gt;\n &lt;cfset theQuery[col][theQuery.recordCount] = ArrayToList( ItemArray , '|' )/&gt;\n\n &lt;/cfloop&gt;\n\n&lt;/cfloop&gt;\n</code></pre>\n" }, { "answer_id": 85944, "author": "kooshmoose", "author_id": 7436, "author_profile": "https://Stackoverflow.com/users/7436", "pm_score": 0, "selected": false, "text": "<p>I would think that you'd want to stop doing so many evaluations inside of your loops and instead use variables to hold counts, pointers to the col object and to hold your pipe-delim string until you're ready to commit to the query object. If I've done the refactoring correctly, you should notice an improvement if you use the code below:</p>\n\n<pre><code>&lt;cfloop index=\"row\" from=\"#startRow#\" to=\"#endRow#\"&gt;\n&lt;cfset QueryAddRow(theQuery) /&gt;\n&lt;cfloop list=\"#columnList#\" index=\"col\"&gt;\n &lt;cfset PipedVals = \"\"&gt;\n &lt;cfset theItem = theObject.Get_Item(row).Get_Properties().Get_Item(col)&gt;\n &lt;cfset ColCount = theItem.Get_Count()-1&gt;\n &lt;cfloop from=\"0\" to=\"#ColCount#\" index=\"item\"&gt;\n &lt;cftry&gt;\n &lt;cfset PipedVals = ListAppend(PipedVals,theItem.Get_Item(item),\"|\")&gt;\n &lt;cfcatch type=\"any\"&gt;&lt;/cfcatch&gt;\n &lt;/cftry&gt;\n &lt;/cfloop&gt;\n &lt;cfset QuerySetCell(theQuery,col) = PipedVals&gt;\n&lt;/cfloop&gt;\n</code></pre>\n\n<p></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16289/" ]
How can I optimize the following code, which currently takes over 2 minutes to retrieve and loop through 800+ records from a pool of over 100K records, returning 6 fields per record (adds approximately 20 seconds per additional field): ``` <cfset dllPath="C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.DirectoryServices.dll" /> <cfset LDAPPath="LDAP://" & arguments.searchPath /> <cfset theLookUp=CreateObject(".NET","System.DirectoryServices.DirectoryEntry", dllPath).init(LDAPPath) /> <cfset theSearch=CreateObject(".NET","System.DirectoryServices.DirectorySearcher", dllPath).init(theLookUp) /> <cfset theSearch.Set_Filter(arguments.theFilter) /> <cfset theObject = theSearch.FindAll() /> <cfloop index="row" from="#startRow#" to="#endRow#"> <cfset QueryAddRow(theQuery) /> <cfloop list="#columnList#" index="col"> <cfloop from="0" to="#theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Count()-1#" index="item"> <cftry> <cfset theQuery[col][theQuery.recordCount]=ListAppend(theQuery[col][theQuery.recordCount],theObject.Get_Item(row).Get_Properties().Get_Item(col).Get_Item(item),"|") /> <cfcatch type="any"> </cfcatch> </cftry> </cfloop> </cfloop> </cfloop> ```
How large is the list of items for the inner loop? Switching to an array *might* be faster if there is a significantly large number of items. I have implemented this alongside x0n's suggestions... ``` <cfset dllPath="C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.DirectoryServices.dll" /> <cfset LDAPPath="LDAP://" & arguments.searchPath /> <cfset theLookUp=CreateObject(".NET","System.DirectoryServices.DirectoryEntry", dllPath).init(LDAPPath) /> <cfset theSearch=CreateObject(".NET","System.DirectoryServices.DirectorySearcher", dllPath).init(theLookUp) /> <cfset theSearch.Set_Filter(arguments.theFilter) /> <cfset theObject = theSearch.FindAll() /> <cfloop index="row" from="#startRow#" to="#endRow#"> <cfset Props = theObject.get_item(row).get_properties() /> <cfset QueryAddRow(theQuery) /> <cfloop list="#columnList#" index="col"> <cfset CurrentCol = Props.getItem(col) /> <cfset ItemArray = ArrayNew(1)/> <cfloop from="0" to="#CurrentCol.getcount() - 1#" index="item"> <cftry> <cfset ArrayAppend( ItemArray , CurrentCol.Get_Item(item) )/> <cfcatch type="any"> </cfcatch> </cftry> </cfloop> <cfset theQuery[col][theQuery.recordCount] = ArrayToList( ItemArray , '|' )/> </cfloop> </cfloop> ```
84,800
<p>I am looking for an efficient way to pull the data I want out of an array called $submission_info so I can easily auto-fill my form fields. The array size is about 120.</p> <p>I want to find the field name and extract the content. In this case, the field name is <strong>loanOfficer</strong> and the content is <strong>John Doe</strong>.</p> <pre><code>Output of Print_r($submission_info[1]): Array ( [field_id] =&gt; 2399 [form_id] =&gt; 4 [field_name] =&gt; loanOfficer [field_test_value] =&gt; ABCDEFGHIJKLMNOPQRSTUVWXYZ [field_size] =&gt; medium [field_type] =&gt; other [data_type] =&gt; string [field_title] =&gt; LoanOfficer [col_name] =&gt; loanOfficer [list_order] =&gt; 2 [admin_display] =&gt; yes [is_sortable] =&gt; yes [include_on_redirect] =&gt; yes [option_orientation] =&gt; vertical [file_upload_dir] =&gt; [file_upload_url] =&gt; [file_upload_max_size] =&gt; 1000000 [file_upload_types] =&gt; [content] =&gt; John Doe ) </code></pre> <p>I want to find the field name and extract the content. In this case, the field name is <strong>loanOfficer</strong> and the content is <strong>John Doe</strong>.</p>
[ { "answer_id": 85069, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 0, "selected": false, "text": "<p>I'm assuming that php has an associative array (commonly called dictionary or hashtable). The most efficient routine would be to run over the array once and put the fields into a dictionary keyed on the field name.</p>\n\n<p>Then instead of having to search through the original array when you want to find a specific field (an O(n)) operation. You just used the dictionary to retrieve it by the name of the field in an O(1) (or constant) operation. Of course the first pass over the array to populate the dictionary would be O(n) but that's a one time cost rather than paying that same penalty for every lookup. </p>\n" }, { "answer_id": 85117, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 3, "selected": true, "text": "<p>You're probably best off going through each entry and creating a new associative array out of it.</p>\n\n<pre><code>foreach($submission_info as $elem) {\n $newarray[$elem[\"field_name\"]] = $elem[\"content\"];\n}\n</code></pre>\n\n<p>Then you can just find the form fields by getting the value from $newarray[<em>&lt;field you're filling in&gt;</em>]. Otherwise, you're going to have to search $submission_info each time for the correct field.</p>\n" }, { "answer_id": 85199, "author": "Matthew Encinas", "author_id": 14433, "author_profile": "https://Stackoverflow.com/users/14433", "pm_score": 1, "selected": false, "text": "<p>Not sure if this is the optimal solution:</p>\n\n<pre><code>foreach($submission_info as $info){\n if($info['field_name'] == 'loanOfficer'){ //check the field name\n $content = $info['content']; //store the desired value\n continue; //this will stop the loop after the desired item is found\n }\n}\n</code></pre>\n\n<p>Next time:\nQuestions are more helpful to you and others if you generalize them such that they cover some overarching topic that you and maybe others don't understand. Seems like you could use an array refresher course...</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16292/" ]
I am looking for an efficient way to pull the data I want out of an array called $submission\_info so I can easily auto-fill my form fields. The array size is about 120. I want to find the field name and extract the content. In this case, the field name is **loanOfficer** and the content is **John Doe**. ``` Output of Print_r($submission_info[1]): Array ( [field_id] => 2399 [form_id] => 4 [field_name] => loanOfficer [field_test_value] => ABCDEFGHIJKLMNOPQRSTUVWXYZ [field_size] => medium [field_type] => other [data_type] => string [field_title] => LoanOfficer [col_name] => loanOfficer [list_order] => 2 [admin_display] => yes [is_sortable] => yes [include_on_redirect] => yes [option_orientation] => vertical [file_upload_dir] => [file_upload_url] => [file_upload_max_size] => 1000000 [file_upload_types] => [content] => John Doe ) ``` I want to find the field name and extract the content. In this case, the field name is **loanOfficer** and the content is **John Doe**.
You're probably best off going through each entry and creating a new associative array out of it. ``` foreach($submission_info as $elem) { $newarray[$elem["field_name"]] = $elem["content"]; } ``` Then you can just find the form fields by getting the value from $newarray[*<field you're filling in>*]. Otherwise, you're going to have to search $submission\_info each time for the correct field.
84,842
<p>I'm programmatically adding ToolStripButton items to a context menu.</p> <p>That part is easy.</p> <pre><code>this.tsmiDelete.DropDownItems.Add("The text on the item."); </code></pre> <p>However, I also need to wire up the events so that when the user clicks the item something actually happens!</p> <p>How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.</p>
[ { "answer_id": 84909, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 3, "selected": true, "text": "<p>Couldn't you just subscribe to the Click event? Something like this:</p>\n\n<pre><code>ToolStripButton btn = new ToolStripButton(\"The text on the item.\");\nthis.tsmiDelete.DropDownItems.Add(btn);\nbtn.Click += new EventHandler(OnBtnClicked);\n</code></pre>\n\n<p>And OnBtnClicked would be declared like this:</p>\n\n<pre><code>private void OnBtnClicked(object sender, EventArgs e)\n{\n ToolStripButton btn = sender as ToolStripButton;\n\n // handle the button click\n}\n</code></pre>\n\n<p>The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.</p>\n" }, { "answer_id": 85066, "author": "James", "author_id": 7837, "author_profile": "https://Stackoverflow.com/users/7837", "pm_score": 0, "selected": false, "text": "<p>Thanks for your help with that Andy. My only problem now is that the AutoSize is not working on the ToolStripButtons that I'm adding! They're all too narrow. </p>\n\n<p>It's rather odd because it was working earlier.</p>\n\n<hr>\n\n<p>Update: There's definitely something wrong with AutoSize for programmatically created ToolStripButtons. However, I found a solution:</p>\n\n<ol>\n<li>Create the ToolStripButton.</li>\n<li>Create a label control and set the font properties to match your button.</li>\n<li>Set the text of the label to match your button.</li>\n<li>Set the label to AutoSize.</li>\n<li>Read the width of the label and use that to set the width of the ToolStripButton.</li>\n</ol>\n\n<p>It's hacky, but it works.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7837/" ]
I'm programmatically adding ToolStripButton items to a context menu. That part is easy. ``` this.tsmiDelete.DropDownItems.Add("The text on the item."); ``` However, I also need to wire up the events so that when the user clicks the item something actually happens! How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.
Couldn't you just subscribe to the Click event? Something like this: ``` ToolStripButton btn = new ToolStripButton("The text on the item."); this.tsmiDelete.DropDownItems.Add(btn); btn.Click += new EventHandler(OnBtnClicked); ``` And OnBtnClicked would be declared like this: ``` private void OnBtnClicked(object sender, EventArgs e) { ToolStripButton btn = sender as ToolStripButton; // handle the button click } ``` The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.
84,847
<p>How do I create a self-signed certificate for code signing using tools from the Windows SDK?</p>
[ { "answer_id": 201277, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 10, "selected": true, "text": "<h2>Updated Answer</h2>\n<p>If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa386968(v=vs.85).aspx\" rel=\"noreferrer\">MakeCert is now deprecated</a>, and Microsoft recommends using <a href=\"https://learn.microsoft.com/en-us/powershell/module/pki/new-selfsignedcertificate\" rel=\"noreferrer\">the PowerShell Cmdlet <strong>New-SelfSignedCertificate</strong></a>.</p>\n<p>If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people <a href=\"https://www.reddit.com/r/PowerShell/comments/3190yr/powershell_40_but_no_newselfsignedcertificate/\" rel=\"noreferrer\">suggest</a> the <a href=\"https://github.com/PKISolutions/PSPKI\" rel=\"noreferrer\">Public Key Infrastructure Powershell (PSPKI) Module</a>.</p>\n<h2>Original Answer</h2>\n<p>While you can create a self-signed code-signing certificate (SPC - <a href=\"http://msdn.microsoft.com/en-us/library/8s9b9yaz.aspx\" rel=\"noreferrer\">Software Publisher Certificate</a>) in one go, I prefer to do the following:</p>\n<h3>Creating a self-signed certificate authority (CA)</h3>\n<pre><code>makecert -r -pe -n &quot;CN=My CA&quot; -ss CA -sr CurrentUser ^\n -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer\n</code></pre>\n<p>(^ = allow batch command-line to wrap line)</p>\n<p>This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named &quot;My CA&quot;, and should be put in the CA store for the current user. We're using the <a href=\"http://en.wikipedia.org/wiki/SHA-2\" rel=\"noreferrer\">SHA-256</a> algorithm. The key is meant for signing (-sky).</p>\n<p>The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.</p>\n<h3>Importing the CA certificate</h3>\n<p>Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You <em>can</em> use the Certificates MMC snapin, but from the command line:</p>\n<pre><code>certutil -user -addstore Root MyCA.cer\n</code></pre>\n<h3>Creating a code-signing certificate (SPC)</h3>\n<pre><code>makecert -pe -n &quot;CN=My SPC&quot; -a sha256 -cy end ^\n -sky signature ^\n -ic MyCA.cer -iv MyCA.pvk ^\n -sv MySPC.pvk MySPC.cer\n</code></pre>\n<p>It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).</p>\n<p>We'll also want to convert the certificate and key into a PFX file:</p>\n<pre><code>pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx\n</code></pre>\n<p>If you are using a password please use the below</p>\n<pre><code>pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx -po fess\n</code></pre>\n<p>If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.</p>\n<h3>Using the certificate for signing code</h3>\n<pre><code>signtool sign /v /f MySPC.pfx ^\n /t http://timestamp.url MyExecutable.exe\n</code></pre>\n<p>(<a href=\"https://stackoverflow.com/a/4417466/57611\">See why timestamps may matter</a>)</p>\n<p>If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:</p>\n<pre><code>signtool sign /v /n &quot;Me&quot; /s SPC ^\n /t http://timestamp.url MyExecutable.exe\n</code></pre>\n<p>Some possible timestamp URLs for <code>signtool /t</code> are:</p>\n<ul>\n<li><code>http://timestamp.verisign.com/scripts/timstamp.dll</code></li>\n<li><code>http://timestamp.globalsign.com/scripts/timstamp.dll</code></li>\n<li><code>http://timestamp.comodoca.com/authenticode</code></li>\n<li><code>http://timestamp.digicert.com</code></li>\n</ul>\n<h3>Full Microsoft documentation</h3>\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/8s9b9yaz.aspx\" rel=\"noreferrer\">signtool</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/bfsktky3.aspx\" rel=\"noreferrer\">makecert</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff550672(v=vs.85).aspx\" rel=\"noreferrer\">pvk2pfx</a></li>\n</ul>\n<h3>Downloads</h3>\nFor those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: [SDK & .NET][5] (which installs makecert in `C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1`). Your mileage may vary.\n<p>MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under &quot;Developer Command Prompt for VS 2015&quot; or &quot;VS2015 x64 Native Tools Command Prompt&quot; (probably all of them in the same folder).</p>\n" }, { "answer_id": 16027204, "author": "Dan Kegel", "author_id": 1539692, "author_profile": "https://Stackoverflow.com/users/1539692", "pm_score": 5, "selected": false, "text": "<p>Roger's answer was very helpful.</p>\n\n<p>I had a little trouble using it, though, and kept getting the red \"Windows can't verify the publisher of this driver software\" error dialog. The key was to install the test root certificate with</p>\n\n<pre><code>certutil -addstore Root Demo_CA.cer\n</code></pre>\n\n<p>which Roger's answer didn't quite cover.</p>\n\n<p>Here is a batch file that worked for me (with my .inf file, not included).\nIt shows how to do it all from start to finish, with no GUI tools at all\n(except for a few password prompts).</p>\n\n<pre><code>REM Demo of signing a printer driver with a self-signed test certificate.\nREM Run as administrator (else devcon won't be able to try installing the driver)\nREM Use a single 'x' as the password for all certificates for simplicity.\n\nPATH %PATH%;\"c:\\Program Files\\Microsoft SDKs\\Windows\\v7.1\\Bin\";\"c:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Bin\";c:\\WinDDK\\7600.16385.1\\bin\\selfsign;c:\\WinDDK\\7600.16385.1\\Tools\\devcon\\amd64\n\nmakecert -r -pe -n \"CN=Demo_CA\" -ss CA -sr CurrentUser ^\n -a sha256 -cy authority -sky signature ^\n -sv Demo_CA.pvk Demo_CA.cer\n\nmakecert -pe -n \"CN=Demo_SPC\" -a sha256 -cy end ^\n -sky signature ^\n -ic Demo_CA.cer -iv Demo_CA.pvk ^\n -sv Demo_SPC.pvk Demo_SPC.cer\n\npvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^\n -pfx Demo_SPC.pfx ^\n -po x\n\ninf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v\n\nsigntool sign /d \"description\" /du \"www.yoyodyne.com\" ^\n /f Demo_SPC.pfx ^\n /p x ^\n /v driver\\demoprinter.cat\n\ncertutil -addstore Root Demo_CA.cer\n\nrem Needs administrator. If this command works, the driver is properly signed.\ndevcon install driver\\demoprinter.inf LPTENUM\\Yoyodyne_IndustriesDemoPrinter_F84F\n\nrem Now uninstall the test driver and certificate.\ndevcon remove driver\\demoprinter.inf LPTENUM\\Yoyodyne_IndustriesDemoPrinter_F84F\n\ncertutil -delstore Root Demo_CA\n</code></pre>\n" }, { "answer_id": 35684904, "author": "Yishai", "author_id": 77779, "author_profile": "https://Stackoverflow.com/users/77779", "pm_score": 4, "selected": false, "text": "<p>As of PowerShell 4.0 (Windows 8.1/<a href=\"https://en.wikipedia.org/wiki/Windows_Server_2012\" rel=\"nofollow noreferrer\">Server 2012</a> R2) it is possible to make a certificate in Windows without <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa386968%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">makecert.exe</a>.</p>\n<p>The commands you need are <a href=\"https://technet.microsoft.com/library/hh848633\" rel=\"nofollow noreferrer\">New-SelfSignedCertificate</a> and <a href=\"https://technet.microsoft.com/en-us/library/hh848635.aspx\" rel=\"nofollow noreferrer\">Export-PfxCertificate</a>.</p>\n<p>Instructions are in <em><a href=\"https://www.itprotoday.com/blog/creating-self-signed-certificates-powershell\" rel=\"nofollow noreferrer\">Creating Self Signed Certificates with PowerShell</a></em>.</p>\n" }, { "answer_id": 47144138, "author": "GorvGoyl", "author_id": 3073272, "author_profile": "https://Stackoverflow.com/users/3073272", "pm_score": 5, "selected": false, "text": "<p>It's fairly easy using the <a href=\"https://learn.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps\" rel=\"noreferrer\">New-SelfSignedCertificate</a> command in Powershell.\nOpen powershell and run these 3 commands.</p>\n<blockquote>\n<ol>\n<li><p><strong>Create certificate</strong>:<br />\n$cert = New-SelfSignedCertificate -DnsName <a href=\"http://www.yourwebsite.com\" rel=\"noreferrer\">www.yourwebsite.com</a>\n-Type CodeSigning -CertStoreLocation Cert:\\CurrentUser\\My</p>\n</li>\n<li><p><strong>set the password for it</strong>:<br />\n$CertPassword = ConvertTo-SecureString\n-String &quot;my_passowrd&quot; -Force -AsPlainText</p>\n</li>\n<li><p><strong>Export it</strong>:<br />\nExport-PfxCertificate -Cert &quot;cert:\\CurrentUser\\My$($cert.Thumbprint)&quot;\n-FilePath &quot;d:\\selfsigncert.pfx&quot; -Password $CertPassword</p>\n</li>\n</ol>\n</blockquote>\n<p>Your certificate <strong>selfsigncert.pfx</strong> will be located @ <code>D:/</code></p>\n<hr />\n<p><strong>Optional step:</strong> You would also require to add certificate password to system environment variables. do so by entering below in cmd: <code>setx CSC_KEY_PASSWORD &quot;my_password&quot;</code></p>\n" }, { "answer_id": 51443366, "author": "chaami", "author_id": 2647222, "author_profile": "https://Stackoverflow.com/users/2647222", "pm_score": 7, "selected": false, "text": "<p>As stated in the answer, in order to use a non deprecated way to sign your own script, one should use <a href=\"https://learn.microsoft.com/en-us/powershell/module/pki/new-selfsignedcertificate?view=windowsserver2022-ps\" rel=\"nofollow noreferrer\">New-SelfSignedCertificate</a>.</p>\n<ol>\n<li>Generate the key:</li>\n</ol>\n<pre><code>New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\\CurrentUser\\My\n</code></pre>\n<ol start=\"2\">\n<li>Export the certificate without the private key:</li>\n</ol>\n<pre><code>Export-Certificate -Cert (Get-ChildItem Cert:\\CurrentUser\\My -CodeSigningCert)[0] -FilePath code_signing.crt\n</code></pre>\n<p>The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).</p>\n<ol start=\"3\">\n<li>Import it as Trusted Publisher</li>\n</ol>\n<pre><code>Import-Certificate -FilePath .\\code_signing.crt -Cert Cert:\\CurrentUser\\TrustedPublisher\n</code></pre>\n<ol start=\"4\">\n<li>Import it as a Root certificate authority.</li>\n</ol>\n<pre><code>Import-Certificate -FilePath .\\code_signing.crt -Cert Cert:\\CurrentUser\\Root\n</code></pre>\n<ol start=\"5\">\n<li>Sign the script (assuming here it's named script.ps1, fix the path accordingly).</li>\n</ol>\n<pre><code>Set-AuthenticodeSignature .\\script.ps1 -Certificate (Get-ChildItem Cert:\\CurrentUser\\My -CodeSigningCert)\n</code></pre>\n<p>Obviously once you have setup the key, you can simply sign any other scripts with it.<br />\nYou can get more detailed information and some troubleshooting help in <a href=\"https://sid-500.com/2017/10/26/how-to-digitally-sign-powershell-scripts/\" rel=\"nofollow noreferrer\">this article</a>.</p>\n" }, { "answer_id": 69534070, "author": "trindflo", "author_id": 3285233, "author_profile": "https://Stackoverflow.com/users/3285233", "pm_score": 1, "selected": false, "text": "<p>You can generate one in Visual Studio 2019, in the project properties. In the Driver Signing section, the Test Certificate field has a drop-down. Generating a test certificate is one of the options. The certificate will be in a file with the 'cer' extension typically in the same output directory as your executable or driver.</p>\n" }, { "answer_id": 71770052, "author": "Server Overflow", "author_id": 46207, "author_profile": "https://Stackoverflow.com/users/46207", "pm_score": 0, "selected": false, "text": "<p>This post will only answer the &quot;how to sign an EXE file if you have the crtificate&quot; part:</p>\n<p>To sign the exe file, I used MS &quot;signtool.exe&quot;. For this you will need to download the bloated MS Windows SDK which has a whooping 1GB. FORTUNATELY, you don't have to install it. Just open the ISO and extract &quot;Windows SDK Signing Tools-x86_en-us.msi&quot;. It has a merely 400 KB.</p>\n<p>Then I built this tiny script file:</p>\n<pre><code>prompt $\necho off\ncls\n\ncopy &quot;my.exe&quot; &quot;my.bak.exe&quot;\n\n&quot;c:\\Program Files (x86)\\Windows Kits\\10\\bin\\10.0.22000.0\\x64\\signtool.exe&quot; sign /fd SHA256 /f MyCertificate.pfx /p MyPassword My.exe\n\npause \n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/252226/signing-a-windows-exe-file\">Details</a></p>\n<p>__</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8446/" ]
How do I create a self-signed certificate for code signing using tools from the Windows SDK?
Updated Answer -------------- If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then [MakeCert is now deprecated](https://msdn.microsoft.com/en-us/library/windows/desktop/aa386968(v=vs.85).aspx), and Microsoft recommends using [the PowerShell Cmdlet **New-SelfSignedCertificate**](https://learn.microsoft.com/en-us/powershell/module/pki/new-selfsignedcertificate). If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people [suggest](https://www.reddit.com/r/PowerShell/comments/3190yr/powershell_40_but_no_newselfsignedcertificate/) the [Public Key Infrastructure Powershell (PSPKI) Module](https://github.com/PKISolutions/PSPKI). Original Answer --------------- While you can create a self-signed code-signing certificate (SPC - [Software Publisher Certificate](http://msdn.microsoft.com/en-us/library/8s9b9yaz.aspx)) in one go, I prefer to do the following: ### Creating a self-signed certificate authority (CA) ``` makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^ -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer ``` (^ = allow batch command-line to wrap line) This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the [SHA-256](http://en.wikipedia.org/wiki/SHA-2) algorithm. The key is meant for signing (-sky). The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file. ### Importing the CA certificate Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You *can* use the Certificates MMC snapin, but from the command line: ``` certutil -user -addstore Root MyCA.cer ``` ### Creating a code-signing certificate (SPC) ``` makecert -pe -n "CN=My SPC" -a sha256 -cy end ^ -sky signature ^ -ic MyCA.cer -iv MyCA.pvk ^ -sv MySPC.pvk MySPC.cer ``` It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches). We'll also want to convert the certificate and key into a PFX file: ``` pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx ``` If you are using a password please use the below ``` pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx -po fess ``` If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase. ### Using the certificate for signing code ``` signtool sign /v /f MySPC.pfx ^ /t http://timestamp.url MyExecutable.exe ``` ([See why timestamps may matter](https://stackoverflow.com/a/4417466/57611)) If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows: ``` signtool sign /v /n "Me" /s SPC ^ /t http://timestamp.url MyExecutable.exe ``` Some possible timestamp URLs for `signtool /t` are: * `http://timestamp.verisign.com/scripts/timstamp.dll` * `http://timestamp.globalsign.com/scripts/timstamp.dll` * `http://timestamp.comodoca.com/authenticode` * `http://timestamp.digicert.com` ### Full Microsoft documentation * [signtool](http://msdn.microsoft.com/en-us/library/8s9b9yaz.aspx) * [makecert](http://msdn.microsoft.com/en-us/library/bfsktky3.aspx) * [pvk2pfx](http://msdn.microsoft.com/en-us/library/windows/hardware/ff550672(v=vs.85).aspx) ### Downloads For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: [SDK & .NET][5] (which installs makecert in `C:\Program Files\Microsoft SDKs\Windows\v7.1`). Your mileage may vary. MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).
84,882
<p>This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.</p> <p>There are a lot of times when I just want to append something to <code>/etc/hosts</code> or a similar file but end up not being able to because both <code>&gt;</code> and <code>&gt;&gt;</code> are not allowed, even with root.</p> <p>Is there someway to make this work without having to <code>su</code> or <code>sudo su</code> into root?</p>
[ { "answer_id": 84898, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<pre><code>sudo sh -c \"echo 127.0.0.1 localhost &gt;&gt; /etc/hosts\"\n</code></pre>\n" }, { "answer_id": 84899, "author": "Matt P", "author_id": 14230, "author_profile": "https://Stackoverflow.com/users/14230", "pm_score": 8, "selected": false, "text": "<p>The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.</p>\n\n<p>Try the following code snippet:</p>\n\n<pre><code>sudo sh -c \"echo 'something' &gt;&gt; /etc/privilegedfile\"\n</code></pre>\n" }, { "answer_id": 84914, "author": "Incident", "author_id": 11613, "author_profile": "https://Stackoverflow.com/users/11613", "pm_score": 5, "selected": false, "text": "<p>The issue is that it's your shell that handles redirection; it's trying to open the file with <em>your</em> permissions not those of the process you're running under sudo.</p>\n\n<p>Use something like this, perhaps:</p>\n\n<pre><code>sudo sh -c \"echo 'something' &gt;&gt; /etc/privilegedFile\"\n</code></pre>\n" }, { "answer_id": 84921, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 4, "selected": false, "text": "<p>Doing </p>\n\n<pre><code>sudo sh -c \"echo &gt;&gt; somefile\"\n</code></pre>\n\n<p>should work. The problem is that > and >> are handled by your shell, not by the \"sudoed\" command, so the permissions are your ones, not the ones of the user you are \"sudoing\" into.</p>\n" }, { "answer_id": 550808, "author": "Yoo", "author_id": 37664, "author_profile": "https://Stackoverflow.com/users/37664", "pm_score": 11, "selected": true, "text": "<p>Use <code>tee --append</code> or <code>tee -a</code>.</p>\n\n<pre><code>echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list\n</code></pre>\n\n<p>Make sure to avoid quotes inside quotes.</p>\n\n<p>To avoid printing data back to the console, redirect the output to /dev/null.</p>\n\n<pre><code>echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list &gt; /dev/null\n</code></pre>\n\n<p>Remember about the (<code>-a</code>/<code>--append</code>) flag! \nJust <code>tee</code> works like <code>&gt;</code> and will overwrite your file. <code>tee -a</code> works like <code>&gt;&gt;</code> and will write at the end of the file.</p>\n" }, { "answer_id": 21764479, "author": "msanford", "author_id": 114900, "author_profile": "https://Stackoverflow.com/users/114900", "pm_score": 4, "selected": false, "text": "<p>I would note, for the curious, that you can also quote a heredoc (for large blocks):</p>\n\n<pre><code>sudo bash -c \"cat &lt;&lt;EOIPFW &gt;&gt; /etc/ipfw.conf\n&lt;?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?&gt;\n\n&lt;plist version=\\\"1.0\\\"&gt;\n &lt;dict&gt;\n &lt;key&gt;Label&lt;/key&gt;\n &lt;string&gt;com.company.ipfw&lt;/string&gt;\n &lt;key&gt;Program&lt;/key&gt;\n &lt;string&gt;/sbin/ipfw&lt;/string&gt;\n &lt;key&gt;ProgramArguments&lt;/key&gt;\n &lt;array&gt;\n &lt;string&gt;/sbin/ipfw&lt;/string&gt;\n &lt;string&gt;-q&lt;/string&gt;\n &lt;string&gt;/etc/ipfw.conf&lt;/string&gt;\n &lt;/array&gt;\n &lt;key&gt;RunAtLoad&lt;/key&gt;\n &lt;true&gt;&lt;/true&gt;\n &lt;/dict&gt;\n&lt;/plist&gt;\nEOIPFW\"\n</code></pre>\n" }, { "answer_id": 22517844, "author": "Vytenis Bivainis", "author_id": 815741, "author_profile": "https://Stackoverflow.com/users/815741", "pm_score": 3, "selected": false, "text": "<p>In bash you can use <code>tee</code> in combination with <code>&gt; /dev/null</code> to keep stdout clean.</p>\n\n<pre><code> echo \"# comment\" | sudo tee -a /etc/hosts &gt; /dev/null\n</code></pre>\n" }, { "answer_id": 26023336, "author": "hololeap", "author_id": 983883, "author_profile": "https://Stackoverflow.com/users/983883", "pm_score": 3, "selected": false, "text": "<p>Using <a href=\"https://stackoverflow.com/a/550808/983883\">Yoo's answer</a>, put this in your <code>~/.bashrc</code>:</p>\n\n<pre><code>sudoe() {\n [[ \"$#\" -ne 2 ]] &amp;&amp; echo \"Usage: sudoe &lt;text&gt; &lt;file&gt;\" &amp;&amp; return 1\n echo \"$1\" | sudo tee --append \"$2\" &gt; /dev/null\n}\n</code></pre>\n\n<p>Now you can run <code>sudoe 'deb blah # blah' /etc/apt/sources.list</code></p>\n\n<hr>\n\n<p><strong>Edit:</strong></p>\n\n<p>A more complete version which allows you to pipe input in or redirect from a file and includes a <code>-a</code> switch to turn off appending (which is on by default):</p>\n\n<pre><code>sudoe() {\n if ([[ \"$1\" == \"-a\" ]] || [[ \"$1\" == \"--no-append\" ]]); then\n shift &amp;&gt;/dev/null || local failed=1\n else\n local append=\"--append\"\n fi\n\n while [[ $failed -ne 1 ]]; do\n if [[ -t 0 ]]; then\n text=\"$1\"; shift &amp;&gt;/dev/null || break\n else\n text=\"$(cat &lt;&amp;0)\"\n fi\n\n [[ -z \"$1\" ]] &amp;&amp; break\n echo \"$text\" | sudo tee $append \"$1\" &gt;/dev/null; return $?\n done\n\n echo \"Usage: $0 [-a|--no-append] [text] &lt;file&gt;\"; return 1\n}\n</code></pre>\n" }, { "answer_id": 41785490, "author": "pixistix", "author_id": 7451883, "author_profile": "https://Stackoverflow.com/users/7451883", "pm_score": -1, "selected": false, "text": "<p>Can you change the ownership of the file then change it back after using <code>cat &gt;&gt;</code> to append?</p>\n\n<pre><code>sudo chown youruser /etc/hosts \nsudo cat /downloaded/hostsadditions &gt;&gt; /etc/hosts \nsudo chown root /etc/hosts \n</code></pre>\n\n<p>Something like this work for you? </p>\n" }, { "answer_id": 46251017, "author": "Fthi.a.Abadi", "author_id": 3135632, "author_profile": "https://Stackoverflow.com/users/3135632", "pm_score": -1, "selected": false, "text": "<p>This worked for me:\noriginal command</p>\n\n<pre><code>echo \"export CATALINA_HOME=\"/opt/tomcat9\"\" &gt;&gt; /etc/environment\n</code></pre>\n\n<p>Working command </p>\n\n<pre><code>echo \"export CATALINA_HOME=\"/opt/tomcat9\"\" |sudo tee /etc/environment\n</code></pre>\n" }, { "answer_id": 50003244, "author": "Noam Manos", "author_id": 658497, "author_profile": "https://Stackoverflow.com/users/658497", "pm_score": 2, "selected": false, "text": "<p>By using <strong>sed -i <em></strong> with <strong></em>$ a</strong> , you can append text, containing both variables and special characters, after the last line.</p>\n\n<p>For example, adding $NEW_HOST with $NEW_IP to /etc/hosts:</p>\n\n<pre><code>sudo sed -i \"\\$ a $NEW_IP\\t\\t$NEW_HOST.domain.local\\t$NEW_HOST\" /etc/hosts\n</code></pre>\n\n<p>sed options explained:</p>\n\n<ul>\n<li><strong><em>-i</em></strong> for in-place</li>\n<li><strong><em>$</em></strong> for last line</li>\n<li><strong><em>a</em></strong> for append</li>\n</ul>\n" }, { "answer_id": 51053054, "author": "Michael Goldshteyn", "author_id": 473798, "author_profile": "https://Stackoverflow.com/users/473798", "pm_score": 2, "selected": false, "text": "<p>You can also use <code>sponge</code> from the <code>moreutils</code> package and not need to redirect the output (i.e., no <code>tee</code> noise to hide):</p>\n\n<pre><code>echo 'Add this line' | sudo sponge -a privfile\n</code></pre>\n" }, { "answer_id": 52867362, "author": "Sudev Shetty", "author_id": 10522075, "author_profile": "https://Stackoverflow.com/users/10522075", "pm_score": 0, "selected": false, "text": "<p>echo 'Hello World' | (sudo tee -a /etc/apt/sources.list)</p>\n" }, { "answer_id": 57633818, "author": "Marcelo Pacheco", "author_id": 9199127, "author_profile": "https://Stackoverflow.com/users/9199127", "pm_score": 0, "selected": false, "text": "<p>How about:<br>\necho text | sudo dd status=none of=privilegedfile<br>\nI want to change /proc/sys/net/ipv4/tcp_rmem.<br>\nI did:<br>\n sudo dd status=none of=/proc/sys/net/ipv4/tcp_rmem &lt;&lt;&lt;\"4096 131072 1024000\"<br>\neliminates the echo with a single line document</p>\n" }, { "answer_id": 64048847, "author": "abkrim", "author_id": 736872, "author_profile": "https://Stackoverflow.com/users/736872", "pm_score": 3, "selected": false, "text": "<p>Some user not know solution when using multiples lines.</p>\n<pre><code>sudo tee -a /path/file/to/create_with_text &gt; /dev/null &lt;&lt;EOT \nline 1\nline 2\nline 3\nEOT\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908/" ]
This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux. There are a lot of times when I just want to append something to `/etc/hosts` or a similar file but end up not being able to because both `>` and `>>` are not allowed, even with root. Is there someway to make this work without having to `su` or `sudo su` into root?
Use `tee --append` or `tee -a`. ``` echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list ``` Make sure to avoid quotes inside quotes. To avoid printing data back to the console, redirect the output to /dev/null. ``` echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null ``` Remember about the (`-a`/`--append`) flag! Just `tee` works like `>` and will overwrite your file. `tee -a` works like `>>` and will write at the end of the file.
84,885
<p>Wondering if anybody out there has any success in using the JDEdwards XMLInterop functionality. I've been using it for a while (with a simple PInvoke, will post code later). I'm looking to see if there's a better and/or more robust way.</p> <p>Thanks.</p>
[ { "answer_id": 154634, "author": "Jon Dewees", "author_id": 1365, "author_profile": "https://Stackoverflow.com/users/1365", "pm_score": 4, "selected": true, "text": "<p>As promised, here is the code for integrating with JDEdewards using XML. It's a webservice, but could be used as you see fit.</p>\n\n<pre><code>namespace YourNameSpace\n</code></pre>\n\n<p>{</p>\n\n<pre><code>/// &lt;summary&gt;\n/// This webservice allows you to submit JDE XML CallObject requests via a c# webservice\n/// &lt;/summary&gt;\n[WebService(Namespace = \"http://WebSite.com/\")]\n[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\npublic class JdeBFService : System.Web.Services.WebService\n{\n private string _strServerName;\n private UInt16 _intServerPort;\n private Int16 _intServerTimeout;\n\n public JdeBFService()\n {\n // Load JDE ServerName, Port, &amp; Connection Timeout from the Web.config file.\n _strServerName = ConfigurationManager.AppSettings[\"JdeServerName\"];\n _intServerPort = Convert.ToUInt16(ConfigurationManager.AppSettings[\"JdePort\"], CultureInfo.InvariantCulture);\n _intServerTimeout = Convert.ToInt16(ConfigurationManager.AppSettings[\"JdeTimeout\"], CultureInfo.InvariantCulture);\n\n }\n\n /// &lt;summary&gt;\n /// This webmethod allows you to submit an XML formatted jdeRequest document\n /// that will call any Master Business Function referenced in the XML document\n /// and return a response.\n /// &lt;/summary&gt;\n /// &lt;param name=\"Xml\"&gt; The jdeRequest XML document &lt;/param&gt;\n [WebMethod]\n public XmlDocument JdeXmlRequest(XmlDocument xmlInput)\n {\n try\n {\n string outputXml = string.Empty;\n outputXml = NativeMethods.JdeXmlRequest(xmlInput, _strServerName, _intServerPort, _intServerTimeout);\n\n XmlDocument outputXmlDoc = new XmlDocument();\n outputXmlDoc.LoadXml(outputXml);\n return outputXmlDoc;\n }\n catch (Exception ex)\n {\n ErrorReporting.SendEmail(ex);\n throw;\n }\n }\n}\n\n/// &lt;summary&gt;\n/// This interop class uses pinvoke to call the JDE C++ dll. It only has one static function.\n/// &lt;/summary&gt;\n/// &lt;remarks&gt;\n/// This class calls the xmlinterop.dll which can be found in the B9/system/bin32 directory. \n/// Copy the dll to the webservice project's /bin directory before running the project.\n/// &lt;/remarks&gt;\ninternal static class NativeMethods\n{\n [DllImport(\"xmlinterop.dll\",\n EntryPoint = \"_jdeXMLRequest@20\",\n CharSet = CharSet.Auto,\n ExactSpelling = false,\n CallingConvention = CallingConvention.StdCall,\n SetLastError = true)]\n private static extern IntPtr jdeXMLRequest([MarshalAs(UnmanagedType.LPWStr)] StringBuilder server, UInt16 port, Int32 timeout, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, Int32 length);\n\n public static string JdeXmlRequest(XmlDocument xmlInput, string strServerName, UInt16 intPort, Int32 intTimeout)\n {\n StringBuilder sbServerName = new StringBuilder(strServerName);\n StringBuilder sbXML = new StringBuilder();\n XmlWriter xWriter = XmlWriter.Create(sbXML);\n xmlInput.WriteTo(xWriter);\n xWriter.Close();\n\n string result = Marshal.PtrToStringAnsi(jdeXMLRequest(sbServerName, intPort, intTimeout, sbXML, sbXML.Length));\n\n return result;\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>You have to send it messages like the following one:</p>\n\n<pre><code>&lt;jdeRequest type='callmethod' user='USER' pwd='PWD' environment='ENV'&gt;\n &lt;callMethod name='GetEffectiveAddress' app='JdeWebRequest' runOnError='no'&gt;\n &lt;params&gt;\n &lt;param name='mnAddressNumber'&gt;10000&lt;/param&gt;\n &lt;/params&gt;\n &lt;/callMethod&gt;\n&lt;/jdeRequest&gt;\n</code></pre>\n" }, { "answer_id": 1231389, "author": "Sam", "author_id": 47636, "author_profile": "https://Stackoverflow.com/users/47636", "pm_score": 0, "selected": false, "text": "<p>I changed our JDE web service to use XML Interop after seeing this code, and we haven't had any stability problems since. Previously we were using the COM Connector, which exhibited regular communication failures (possibly a connection pooling issue?) and was a pain to install and configure correctly.</p>\n\n<p>We did have issues when we attempted to use transactions, but if you're doing simple single business function calls this shouldn't be an problem.</p>\n\n<p><strong>Update:</strong> To elaborate on the transaction issues - if you're attempting to keep a transaction alive over multiple calls, AND the JDE application server is handling a modest number of concurrent calls, the xmlinterop calls start returning an 'XML response failed' message and the DB transaction is left open with no way to commit or rollback. It's possible tweaking the number of kernels might solve this, but personally, I'd always try to complete the transaction in a single call.</p>\n" }, { "answer_id": 19598192, "author": "nkuebelbeck", "author_id": 411490, "author_profile": "https://Stackoverflow.com/users/411490", "pm_score": 1, "selected": false, "text": "<p>To anyone trying to do this, there are some dependencies to xmlinterop.dll. </p>\n\n<p>you'll find these files on the fat client here ->c:\\E910\\system\\bin32</p>\n\n<p>this will create a 'thin client'</p>\n\n<pre><code>PSThread.dll\nicudt32.dll\nicui18n.dll\nicuuc.dll\njdel.dll\njdeunicode.dll\nlibeay32.dll\nmsvcp71.dll\nssleay32.dll\nustdio.dll\nxmlinterop.dll\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1365/" ]
Wondering if anybody out there has any success in using the JDEdwards XMLInterop functionality. I've been using it for a while (with a simple PInvoke, will post code later). I'm looking to see if there's a better and/or more robust way. Thanks.
As promised, here is the code for integrating with JDEdewards using XML. It's a webservice, but could be used as you see fit. ``` namespace YourNameSpace ``` { ``` /// <summary> /// This webservice allows you to submit JDE XML CallObject requests via a c# webservice /// </summary> [WebService(Namespace = "http://WebSite.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class JdeBFService : System.Web.Services.WebService { private string _strServerName; private UInt16 _intServerPort; private Int16 _intServerTimeout; public JdeBFService() { // Load JDE ServerName, Port, & Connection Timeout from the Web.config file. _strServerName = ConfigurationManager.AppSettings["JdeServerName"]; _intServerPort = Convert.ToUInt16(ConfigurationManager.AppSettings["JdePort"], CultureInfo.InvariantCulture); _intServerTimeout = Convert.ToInt16(ConfigurationManager.AppSettings["JdeTimeout"], CultureInfo.InvariantCulture); } /// <summary> /// This webmethod allows you to submit an XML formatted jdeRequest document /// that will call any Master Business Function referenced in the XML document /// and return a response. /// </summary> /// <param name="Xml"> The jdeRequest XML document </param> [WebMethod] public XmlDocument JdeXmlRequest(XmlDocument xmlInput) { try { string outputXml = string.Empty; outputXml = NativeMethods.JdeXmlRequest(xmlInput, _strServerName, _intServerPort, _intServerTimeout); XmlDocument outputXmlDoc = new XmlDocument(); outputXmlDoc.LoadXml(outputXml); return outputXmlDoc; } catch (Exception ex) { ErrorReporting.SendEmail(ex); throw; } } } /// <summary> /// This interop class uses pinvoke to call the JDE C++ dll. It only has one static function. /// </summary> /// <remarks> /// This class calls the xmlinterop.dll which can be found in the B9/system/bin32 directory. /// Copy the dll to the webservice project's /bin directory before running the project. /// </remarks> internal static class NativeMethods { [DllImport("xmlinterop.dll", EntryPoint = "_jdeXMLRequest@20", CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern IntPtr jdeXMLRequest([MarshalAs(UnmanagedType.LPWStr)] StringBuilder server, UInt16 port, Int32 timeout, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, Int32 length); public static string JdeXmlRequest(XmlDocument xmlInput, string strServerName, UInt16 intPort, Int32 intTimeout) { StringBuilder sbServerName = new StringBuilder(strServerName); StringBuilder sbXML = new StringBuilder(); XmlWriter xWriter = XmlWriter.Create(sbXML); xmlInput.WriteTo(xWriter); xWriter.Close(); string result = Marshal.PtrToStringAnsi(jdeXMLRequest(sbServerName, intPort, intTimeout, sbXML, sbXML.Length)); return result; } } ``` } You have to send it messages like the following one: ``` <jdeRequest type='callmethod' user='USER' pwd='PWD' environment='ENV'> <callMethod name='GetEffectiveAddress' app='JdeWebRequest' runOnError='no'> <params> <param name='mnAddressNumber'>10000</param> </params> </callMethod> </jdeRequest> ```
84,932
<p>I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script <code>$0</code> varies and sometimes contains the <code>fullpath+filename</code> and sometimes just <code>filename</code>. Because the working directory can vary as well I can't think of a way to reliably get the <code>fullpath+filename</code> of the script.</p> <p>Anyone got a solution?</p>
[ { "answer_id": 84952, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": -1, "selected": false, "text": "<p>On *nix, you likely have the \"whereis\" command, which searches your $PATH looking for a binary with a given name. If $0 doesn't contain the full path name, running whereis $scriptname and saving the result into a variable should tell you where the script is located.</p>\n" }, { "answer_id": 84959, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 7, "selected": false, "text": "<p>$0 is typically the name of your program, so how about this?</p>\n\n<pre><code>use Cwd 'abs_path';\nprint abs_path($0);\n</code></pre>\n\n<p>Seems to me that this should work as abs_path knows if you are using a relative or absolute path.</p>\n\n<p><strong>Update</strong> For anyone reading this years later, you should read <a href=\"https://stackoverflow.com/a/90721/2877364\">Drew's answer</a>. It's much better than mine.</p>\n" }, { "answer_id": 84973, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 3, "selected": false, "text": "<p>Have you tried:</p>\n\n<pre><code>$ENV{'SCRIPT_NAME'}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>use FindBin '$Bin';\nprint \"The script is located in $Bin.\\n\";\n</code></pre>\n\n<p>It really depends on how it's being called and if it's CGI or being run from a normal shell, etc.</p>\n" }, { "answer_id": 84982, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 4, "selected": false, "text": "<p>I think the module you're looking for is FindBin:</p>\n\n<pre><code>#!/usr/bin/perl\nuse FindBin;\n\n$0 = \"stealth\";\nprint \"The actual path to this is: $FindBin::Bin/$FindBin::Script\\n\";\n</code></pre>\n" }, { "answer_id": 85037, "author": "Benjamin W. Smith", "author_id": 1068060, "author_profile": "https://Stackoverflow.com/users/1068060", "pm_score": 4, "selected": false, "text": "<p>You could use <a href=\"http://search.cpan.org/~tty/kurila-1.13_0/lib/FindBin.pm\" rel=\"noreferrer\">FindBin</a>, <a href=\"http://perldoc.perl.org/Cwd.html\" rel=\"noreferrer\">Cwd</a>, <a href=\"http://perldoc.perl.org/File/Basename.html\" rel=\"noreferrer\">File::Basename</a>, or a combination of them. They're all in the base distribution of Perl IIRC.</p>\n\n<p>I used Cwd in the past:</p>\n\n<p>Cwd:</p>\n\n<pre><code>use Cwd qw(abs_path);\nmy $path = abs_path($0);\nprint \"$path\\n\";\n</code></pre>\n" }, { "answer_id": 85070, "author": "Mark", "author_id": 16363, "author_profile": "https://Stackoverflow.com/users/16363", "pm_score": 5, "selected": false, "text": "<pre><code>use File::Spec;\nFile::Spec-&gt;rel2abs( __FILE__ );\n</code></pre>\n<p><a href=\"http://perldoc.perl.org/File/Spec/Unix.html\" rel=\"nofollow noreferrer\">http://perldoc.perl.org/File/Spec/Unix.html</a></p>\n" }, { "answer_id": 85098, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://perldoc.perl.org/perlfaq8.html\" rel=\"nofollow noreferrer\">perlfaq8</a> answers a very similar question with using the <code>rel2abs()</code> function on <code>$0</code>. That function can be found in File::Spec.</p>\n" }, { "answer_id": 85264, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 3, "selected": false, "text": "<p>Some short background:</p>\n\n<p>Unfortunately the Unix API doesn't provide a running program with the full path to the executable. In fact, the program executing yours can provide whatever it wants in the field that normally tells your program what it is. There are, as all the answers point out, various heuristics for finding likely candidates. But nothing short of searching the entire filesystem will always work, and even that will fail if the executable is moved or removed.</p>\n\n<p>But you don't want the Perl executable, which is what's actually running, but the script it is executing. And Perl needs to know where the script is to find it. It stores this in <code>__FILE__</code>, while <code>$0</code> is from the Unix API. This can still be a relative path, so take Mark's suggestion and canonize it with <code>File::Spec-&gt;rel2abs( __FILE__ );</code></p>\n" }, { "answer_id": 90721, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 9, "selected": true, "text": "<p>There are a few ways:</p>\n\n<ul>\n<li><a href=\"http://perldoc.perl.org/perlvar.html#$0\" rel=\"noreferrer\"><code>$0</code></a> is the currently executing script as provided by POSIX, relative to the current working directory if the script is at or below the CWD</li>\n<li>Additionally, <code>cwd()</code>, <code>getcwd()</code> and <code>abs_path()</code> are provided by the <a href=\"http://perldoc.perl.org/Cwd.html\" rel=\"noreferrer\"><code>Cwd</code></a> module and tell you where the script is being run from</li>\n<li>The module <a href=\"http://perldoc.perl.org/FindBin.html\" rel=\"noreferrer\"><code>FindBin</code></a> provides the <code>$Bin</code> &amp; <code>$RealBin</code> variables that <em>usually</em> are the path to the executing script; this module also provides <code>$Script</code> &amp; <code>$RealScript</code> that are the name of the script</li>\n<li><a href=\"http://perldoc.perl.org/perldata.html#Special-Literals\" rel=\"noreferrer\"><code>__FILE__</code></a> is the actual file that the Perl interpreter deals with during compilation, including its full path.</li>\n</ul>\n\n<p>I've seen the first three (<a href=\"http://perldoc.perl.org/perlvar.html#$0\" rel=\"noreferrer\"><code>$0</code></a>, the <a href=\"http://perldoc.perl.org/Cwd.html\" rel=\"noreferrer\"><code>Cwd</code></a> module and the <a href=\"http://perldoc.perl.org/FindBin.html\" rel=\"noreferrer\"><code>FindBin</code></a> module) fail under <code>mod_perl</code> spectacularly, producing worthless output such as <code>'.'</code> or an empty string. In such environments, I use <a href=\"http://perldoc.perl.org/perldata.html#Special-Literals\" rel=\"noreferrer\"><code>__FILE__</code></a> and get the path from that using the <a href=\"http://perldoc.perl.org/File/Basename.html\" rel=\"noreferrer\"><code>File::Basename</code></a> module:</p>\n\n<pre><code>use File::Basename;\nmy $dirname = dirname(__FILE__);\n</code></pre>\n" }, { "answer_id": 90769, "author": "Eric Wilhelm", "author_id": 11580, "author_profile": "https://Stackoverflow.com/users/11580", "pm_score": 3, "selected": false, "text": "<p>Getting the absolute path to <code>$0</code> or <code>__FILE__</code> is what you want. The only trouble is if someone did a <code>chdir()</code> and the <code>$0</code> was relative -- then you need to get the absolute path in a <code>BEGIN{}</code> to prevent any surprises.</p>\n\n<p><code>FindBin</code> tries to go one better and grovel around in the <code>$PATH</code> for something matching the <code>basename($0)</code>, but there are times when that does far-too-surprising things (specifically: when the file is \"right in front of you\" in the cwd.)</p>\n\n<p><code>File::Fu</code> has <code>File::Fu-&gt;program_name</code> and <code>File::Fu-&gt;program_dir</code> for this.</p>\n" }, { "answer_id": 5516160, "author": "Yong Li", "author_id": 687946, "author_profile": "https://Stackoverflow.com/users/687946", "pm_score": 1, "selected": false, "text": "<p>Are you looking for this?:</p>\n\n<pre><code>my $thisfile = $1 if $0 =~\n/\\\\([^\\\\]*)$|\\/([^\\/]*)$/;\n\nprint \"You are running $thisfile\nnow.\\n\";\n</code></pre>\n\n<p>The output will look like this:</p>\n\n<pre><code>You are running MyFileName.pl now.\n</code></pre>\n\n<p>It works on both Windows and Unix.</p>\n" }, { "answer_id": 6997006, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "<pre><code>use strict ; use warnings ; use Cwd 'abs_path';\n sub ResolveMyProductBaseDir { \n\n # Start - Resolve the ProductBaseDir\n #resolve the run dir where this scripts is placed\n my $ScriptAbsolutPath = abs_path($0) ; \n #debug print \"\\$ScriptAbsolutPath is $ScriptAbsolutPath \\n\" ;\n $ScriptAbsolutPath =~ m/^(.*)(\\\\|\\/)(.*)\\.([a-z]*)/; \n $RunDir = $1 ; \n #debug print \"\\$1 is $1 \\n\" ;\n #change the \\'s to /'s if we are on Windows\n $RunDir =~s/\\\\/\\//gi ; \n my @DirParts = split ('/' , $RunDir) ; \n for (my $count=0; $count &lt; 4; $count++) { pop @DirParts ; }\n my $ProductBaseDir = join ( '/' , @DirParts ) ; \n # Stop - Resolve the ProductBaseDir\n #debug print \"ResolveMyProductBaseDir $ProductBaseDir is $ProductBaseDir \\n\" ; \n return $ProductBaseDir ; \n } #eof sub \n</code></pre>\n" }, { "answer_id": 13566423, "author": "mkc", "author_id": 1853620, "author_profile": "https://Stackoverflow.com/users/1853620", "pm_score": 1, "selected": false, "text": "<pre><code>#!/usr/bin/perl -w\nuse strict;\n\n\nmy $path = $0;\n$path =~ s/\\.\\///g;\nif ($path =~ /\\//){\n if ($path =~ /^\\//){\n $path =~ /^((\\/[^\\/]+){1,}\\/)[^\\/]+$/;\n $path = $1;\n }\n else {\n $path =~ /^(([^\\/]+\\/){1,})[^\\/]+$/;\n my $path_b = $1;\n my $path_a = `pwd`;\n chop($path_a);\n $path = $path_a.\"/\".$path_b;\n }\n }\nelse{\n $path = `pwd`;\n chop($path);\n $path.=\"/\";\n }\n$path =~ s/\\/\\//\\//g;\n\n\n\nprint \"\\n$path\\n\";\n</code></pre>\n\n<p>:DD</p>\n" }, { "answer_id": 17735548, "author": "Matt", "author_id": 2597514, "author_profile": "https://Stackoverflow.com/users/2597514", "pm_score": 3, "selected": false, "text": "<p>In order to get the path to the directory containing my script I used a combination of answers given already.</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\nuse File::Spec;\nuse File::Basename;\n\nmy $dir = dirname(File::Spec-&gt;rel2abs(__FILE__));\n</code></pre>\n" }, { "answer_id": 20349041, "author": "user3061015", "author_id": 3061015, "author_profile": "https://Stackoverflow.com/users/3061015", "pm_score": -1, "selected": false, "text": "<p>What's wrong with <code>$^X</code> ?</p>\n\n<pre><code>#!/usr/bin/env perl&lt;br&gt;\nprint \"This is executed by $^X\\n\";\n</code></pre>\n\n<p>Would give you the full path to the Perl binary being used.</p>\n\n<p>Evert</p>\n" }, { "answer_id": 20565937, "author": "Jonathan", "author_id": 271450, "author_profile": "https://Stackoverflow.com/users/271450", "pm_score": 0, "selected": false, "text": "<p>The problem with <code>__FILE__</code> is that it will print the core module \".pm\" path not necessarily the \".cgi\" or \".pl\" script path that is running. I guess it depends on what your goal is.</p>\n\n<p>It seems to me that <a href=\"http://search.cpan.org/~smueller/PathTools-3.40/\" rel=\"nofollow\"><code>Cwd</code></a> just needs to be updated for mod_perl. Here is my suggestion:</p>\n\n<pre><code>my $path;\n\nuse File::Basename;\nmy $file = basename($ENV{SCRIPT_NAME});\n\nif (exists $ENV{MOD_PERL} &amp;&amp; ($ENV{MOD_PERL_API_VERSION} &lt; 2)) {\n if ($^O =~/Win/) {\n $path = `echo %cd%`;\n chop $path;\n $path =~ s!\\\\!/!g;\n $path .= $ENV{SCRIPT_NAME};\n }\n else {\n $path = `pwd`;\n $path .= \"/$file\";\n }\n # add support for other operating systems\n}\nelse {\n require Cwd;\n $path = Cwd::getcwd().\"/$file\";\n}\nprint $path;\n</code></pre>\n\n<p>Please add any suggestions.</p>\n" }, { "answer_id": 21605869, "author": "Putnik", "author_id": 1013183, "author_profile": "https://Stackoverflow.com/users/1013183", "pm_score": 0, "selected": false, "text": "<p>Without any external modules, valid for shell, works well even with '../':</p>\n\n<pre><code>my $self = `pwd`;\nchomp $self;\n$self .='/'.$1 if $0 =~/([^\\/]*)$/; #keep the filename only\nprint \"self=$self\\n\";\n</code></pre>\n\n<p>test:</p>\n\n<pre><code>$ /my/temp/Host$ perl ./host-mod.pl \nself=/my/temp/Host/host-mod.pl\n\n$ /my/temp/Host$ ./host-mod.pl \nself=/my/temp/Host/host-mod.pl\n\n$ /my/temp/Host$ ../Host/./host-mod.pl \nself=/my/temp/Host/host-mod.pl\n</code></pre>\n" }, { "answer_id": 23149908, "author": "DavidGamba", "author_id": 1601989, "author_profile": "https://Stackoverflow.com/users/1601989", "pm_score": 1, "selected": false, "text": "<p>The problem with just using <code>dirname(__FILE__)</code> is that it doesn't follow symlinks. I had to use this for my script to follow the symlink to the actual file location.</p>\n\n<pre><code>use File::Basename;\nmy $script_dir = undef;\nif(-l __FILE__) {\n $script_dir = dirname(readlink(__FILE__));\n}\nelse {\n $script_dir = dirname(__FILE__);\n}\n</code></pre>\n" }, { "answer_id": 24515046, "author": "daniel souza", "author_id": 1226168, "author_profile": "https://Stackoverflow.com/users/1226168", "pm_score": 2, "selected": false, "text": "<p>There's no need to use external modules, with just one line you can have the file name and relative path. If you are using modules and need to apply a path relative to the script directory, the relative path is enough.</p>\n\n<pre><code>$0 =~ m/(.+)[\\/\\\\](.+)$/;\nprint \"full path: $1, file name: $2\\n\";\n</code></pre>\n" }, { "answer_id": 25663214, "author": "Elmar", "author_id": 4007562, "author_profile": "https://Stackoverflow.com/users/4007562", "pm_score": 0, "selected": false, "text": "<p>All the library-free solutions don't actually work for more than a few ways to write a path (think ../ or /bla/x/../bin/./x/../ etc. My solution looks like below. I have one quirk: I don't have the faintest idea why I have to run the replacements twice. If I don't, I get a spurious \"./\" or \"../\". Apart from that, it seems quite robust to me.</p>\n\n<pre><code> my $callpath = $0;\n my $pwd = `pwd`; chomp($pwd);\n\n # if called relative -&gt; add pwd in front\n if ($callpath !~ /^\\//) { $callpath = $pwd.\"/\".$callpath; } \n\n # do the cleanup\n $callpath =~ s!^\\./!!; # starts with ./ -&gt; drop\n $callpath =~ s!/\\./!/!g; # /./ -&gt; /\n $callpath =~ s!/\\./!/!g; # /./ -&gt; / (twice)\n\n $callpath =~ s!/[^/]+/\\.\\./!/!g; # /xxx/../ -&gt; /\n $callpath =~ s!/[^/]+/\\.\\./!/!g; # /xxx/../ -&gt; / (twice)\n\n my $calldir = $callpath;\n $calldir =~ s/(.*)\\/([^\\/]+)/$1/;\n</code></pre>\n" }, { "answer_id": 52944919, "author": "drjumper", "author_id": 5116399, "author_profile": "https://Stackoverflow.com/users/5116399", "pm_score": 0, "selected": false, "text": "<p>None of the \"top\" answers were right for me. The problem with using FindBin '$Bin' or Cwd is that they return absolute path with all symbolic links resolved. In my case I needed the exact path with symbolic links present - the same as returns Unix command \"pwd\" and not \"pwd -P\". The following function provides the solution:</p>\n\n<pre><code>sub get_script_full_path {\n use File::Basename;\n use File::Spec;\n use Cwd qw(chdir cwd);\n my $curr_dir = cwd();\n chdir(dirname($0));\n my $dir = $ENV{PWD};\n chdir( $curr_dir);\n return File::Spec-&gt;catfile($dir, basename($0));\n}\n</code></pre>\n" }, { "answer_id": 58417063, "author": "user3228609", "author_id": 3228609, "author_profile": "https://Stackoverflow.com/users/3228609", "pm_score": 0, "selected": false, "text": "<p>On Windows using <code>dirname</code> and <code>abs_path</code> together worked best for me.</p>\n\n<pre><code>use File::Basename;\nuse Cwd qw(abs_path);\n\n# absolute path of the directory containing the executing script\nmy $abs_dirname = dirname(abs_path($0));\nprint \"\\ndirname(abs_path(\\$0)) -&gt; $abs_dirname\\n\";\n</code></pre>\n\n<p>here's why:</p>\n\n<pre><code># this gives the answer I want in relative path form, not absolute\nmy $rel_dirname = dirname(__FILE__); \nprint \"dirname(__FILE__) -&gt; $rel_dirname\\n\"; \n\n# this gives the slightly wrong answer, but in the form I want \nmy $full_filepath = abs_path($0);\nprint \"abs_path(\\$0) -&gt; $full_filepath\\n\";\n</code></pre>\n" }, { "answer_id": 63550144, "author": "user3673", "author_id": 871821, "author_profile": "https://Stackoverflow.com/users/871821", "pm_score": 0, "selected": false, "text": "<pre><code>use File::Basename;\nuse Cwd 'abs_path';\nprint dirname(abs_path(__FILE__)) ;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/a/90721/871821\">Drew's answer</a> gave me:</p>\n<p>'.'</p>\n<pre><code>$ cat &gt;testdirname\nuse File::Basename;\nprint dirname(__FILE__);\n$ perl testdirname\n.$ perl -v\n\nThis is perl 5, version 28, subversion 1 (v5.28.1) built for x86_64-linux-gnu-thread-multi][1]\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16331/" ]
I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script `$0` varies and sometimes contains the `fullpath+filename` and sometimes just `filename`. Because the working directory can vary as well I can't think of a way to reliably get the `fullpath+filename` of the script. Anyone got a solution?
There are a few ways: * [`$0`](http://perldoc.perl.org/perlvar.html#$0) is the currently executing script as provided by POSIX, relative to the current working directory if the script is at or below the CWD * Additionally, `cwd()`, `getcwd()` and `abs_path()` are provided by the [`Cwd`](http://perldoc.perl.org/Cwd.html) module and tell you where the script is being run from * The module [`FindBin`](http://perldoc.perl.org/FindBin.html) provides the `$Bin` & `$RealBin` variables that *usually* are the path to the executing script; this module also provides `$Script` & `$RealScript` that are the name of the script * [`__FILE__`](http://perldoc.perl.org/perldata.html#Special-Literals) is the actual file that the Perl interpreter deals with during compilation, including its full path. I've seen the first three ([`$0`](http://perldoc.perl.org/perlvar.html#$0), the [`Cwd`](http://perldoc.perl.org/Cwd.html) module and the [`FindBin`](http://perldoc.perl.org/FindBin.html) module) fail under `mod_perl` spectacularly, producing worthless output such as `'.'` or an empty string. In such environments, I use [`__FILE__`](http://perldoc.perl.org/perldata.html#Special-Literals) and get the path from that using the [`File::Basename`](http://perldoc.perl.org/File/Basename.html) module: ``` use File::Basename; my $dirname = dirname(__FILE__); ```
84,978
<p>Excel usually treats Conditional Formatting formulas as if they are array formulas, <strong>except</strong> when loading them from an Excel 2002/2003 XML Spreadsheet file.</p> <p>This is only an issue with the Excel 2002/2003 XML Spreadsheet format... the native Excel format works fine, as does the newer Excel 2007 XML format (xlsx).</p> <p>After loading the spreadsheet, it is possible to make it work correctly by selecting the formatted range, going to the Conditional Formatting dialog, and clicking OK--but this only fixes the problem for the session.</p> <p><strong>Test case:</strong></p> <p>Enter the following into a new sheet:</p> <pre><code> A B C 1 N N N 2 x x x 3 x x x</code></pre> <p>Create this conditional format formula on cells A1:C1 (your choice of pretty colors for the format):</p> <pre><code>=(SUM(($A1:$C1="N")*($A$2:$C$2=A$3))>0)</code></pre> <p>This is an array formula that activates for A1, B1, and C1 whenever any of them has an "N" and the cell in row 2 below the "N" is equal to the cell in row 3 of the current column. </p> <p>(This has been simplified from a real-world business spreadsheet. Sorry for the complexity of the test case, I am trying to find an easier test case to present here.)</p> <p>And it works... you can alter the N's or the x's in any way you want and the formatting works just fine.</p> <p>Save this as an XML Spreadsheet. Close Excel, and re-open the file. Formatting is now broken. Now, you can only activate conditional formatting if A1 is an "N" and A2 is the same as A3, B3, or C3. The values of B1, B2, C1, and C2 have no effect on the formatting.</p> <p>Now, select A1:C1 and look at the conditional formatting formula. Exactly the same as before. Hit OK. Conditional formatting starts working again, and will work during the entire session the file is open.</p> <p><strong>Workarounds considered:</strong></p> <ol> <li><p>Providing the file in native (BIFF) Excel format. Not an option, these spreadsheets are generated on the fly by a web server and this is only one of dozens of types of workbooks generated dynamically by our system.</p></li> <li><p>Providing the file in the Excel 2007 native XML format (xlsx). Not an option, current user base does not have Office 2007 or the compatibility plug-in.</p></li> <li><p>Asking users to select the range, enter the Conditional Formatting dialog, and hitting ok. Not an option in this case, unsophisticated users.</p></li> <li><p>Asking users to open the XML spreadsheet, save as native XLS, close, and re-open the XLS file. <strong>This does not work!</strong> Formatting remains broken in the native XLS format if it was loaded broken from an XML file. If (3) above is performed before saving, the XLS file will work properly.</p></li> </ol> <p><strong>I ended up rewriting the conditional formatting to not use array formulas. So I guess this is "answered" to some degree, but it's still an undocumented, if obscure, bug in Excel 2002/2003's handling of XML files.</strong></p>
[ { "answer_id": 86251, "author": "TMarshall", "author_id": 8847, "author_profile": "https://Stackoverflow.com/users/8847", "pm_score": 2, "selected": true, "text": "<p>I tried to recreate the problem you describe. Here is what I found.</p>\n\n<ul>\n<li><p>Could consistently recreate the\nproblem using Excel 2003 on Windows\nXP when saving as an XML\nspreadsheet.</p></li>\n<li><p>Could <strong>not</strong> reproduce the problem\nusing Excel 2003 on Windows XP when\nsaving as a standard xls\nspreadsheet.</p></li>\n<li><p>Could <strong>not</strong> reproduce the problem\nusing Excel 2007 on Windows Vista\nwhen saving the file in the native\nxlsx format.</p></li>\n<li><p>Could <strong>not</strong> reproduce the problem\nusing Excel 2007 on Windows Vista\nwhen saving the file in the Excel\n97-2003 xls format.</p>\n\n<p>(Note: <em>All instances of Excel and Windows are current with all Windows updates.</em>)</p></li>\n</ul>\n\n<p>I also added a simple conditional formatting formula to each test. In every case, it worked as expected after saving the file, closing Excel, and reopening the file.</p>\n\n<p>So the answer seems to be to use the standard Excel 2003 file format when saving the file.</p>\n\n<p>BTW, this is a very odd formatting formula. It is difficult to imagine how you would use it. It must be a very specific &amp; unusual business case. I also have the feeling something is missing in your post. (I'm not accusing you of being dishonest – just wondering if you may have shortened the formula for readability.) If this is not the <em>exact</em> formula you are using, please edit your original post with the complete formula and I will be happy to revisit this issue.</p>\n" }, { "answer_id": 411005, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can find some tutorial videos for self studying the conditional formatting issue over the following pages:\n<a href=\"http://www.free-training-tutorial.com/conditional-formatting.html\" rel=\"nofollow noreferrer\">conditional formatting</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/84978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16306/" ]
Excel usually treats Conditional Formatting formulas as if they are array formulas, **except** when loading them from an Excel 2002/2003 XML Spreadsheet file. This is only an issue with the Excel 2002/2003 XML Spreadsheet format... the native Excel format works fine, as does the newer Excel 2007 XML format (xlsx). After loading the spreadsheet, it is possible to make it work correctly by selecting the formatted range, going to the Conditional Formatting dialog, and clicking OK--but this only fixes the problem for the session. **Test case:** Enter the following into a new sheet: ``` A B C 1 N N N 2 x x x 3 x x x ``` Create this conditional format formula on cells A1:C1 (your choice of pretty colors for the format): ``` =(SUM(($A1:$C1="N")*($A$2:$C$2=A$3))>0) ``` This is an array formula that activates for A1, B1, and C1 whenever any of them has an "N" and the cell in row 2 below the "N" is equal to the cell in row 3 of the current column. (This has been simplified from a real-world business spreadsheet. Sorry for the complexity of the test case, I am trying to find an easier test case to present here.) And it works... you can alter the N's or the x's in any way you want and the formatting works just fine. Save this as an XML Spreadsheet. Close Excel, and re-open the file. Formatting is now broken. Now, you can only activate conditional formatting if A1 is an "N" and A2 is the same as A3, B3, or C3. The values of B1, B2, C1, and C2 have no effect on the formatting. Now, select A1:C1 and look at the conditional formatting formula. Exactly the same as before. Hit OK. Conditional formatting starts working again, and will work during the entire session the file is open. **Workarounds considered:** 1. Providing the file in native (BIFF) Excel format. Not an option, these spreadsheets are generated on the fly by a web server and this is only one of dozens of types of workbooks generated dynamically by our system. 2. Providing the file in the Excel 2007 native XML format (xlsx). Not an option, current user base does not have Office 2007 or the compatibility plug-in. 3. Asking users to select the range, enter the Conditional Formatting dialog, and hitting ok. Not an option in this case, unsophisticated users. 4. Asking users to open the XML spreadsheet, save as native XLS, close, and re-open the XLS file. **This does not work!** Formatting remains broken in the native XLS format if it was loaded broken from an XML file. If (3) above is performed before saving, the XLS file will work properly. **I ended up rewriting the conditional formatting to not use array formulas. So I guess this is "answered" to some degree, but it's still an undocumented, if obscure, bug in Excel 2002/2003's handling of XML files.**
I tried to recreate the problem you describe. Here is what I found. * Could consistently recreate the problem using Excel 2003 on Windows XP when saving as an XML spreadsheet. * Could **not** reproduce the problem using Excel 2003 on Windows XP when saving as a standard xls spreadsheet. * Could **not** reproduce the problem using Excel 2007 on Windows Vista when saving the file in the native xlsx format. * Could **not** reproduce the problem using Excel 2007 on Windows Vista when saving the file in the Excel 97-2003 xls format. (Note: *All instances of Excel and Windows are current with all Windows updates.*) I also added a simple conditional formatting formula to each test. In every case, it worked as expected after saving the file, closing Excel, and reopening the file. So the answer seems to be to use the standard Excel 2003 file format when saving the file. BTW, this is a very odd formatting formula. It is difficult to imagine how you would use it. It must be a very specific & unusual business case. I also have the feeling something is missing in your post. (I'm not accusing you of being dishonest – just wondering if you may have shortened the formula for readability.) If this is not the *exact* formula you are using, please edit your original post with the complete formula and I will be happy to revisit this issue.
85,006
<p>I have loaded image into a new, initialized Oracle ORDImage object and am processing it by PL/SQL. I can read its properties, but cannot process it with the process() method. </p> <pre><code>vLocalImage ORDImage := ORDImage.init(); ... vLocalImage.source.localdata := PORTAL.wwdoc_admin.get_document_blob_content(pFile); vLocalImage.setProperties(); ... if vLocalImage.width &gt; lMaxWidth then vLocalImage.process('maxScale 534 401'); end if; </code></pre> <p>This should scale the image down, conserving aspect ratio, so that it is no more than 534 px wide and no more than 401 px high. </p> <p>However, I get the following error stack:</p> <pre><code>Internal error: ORA-29400: data cartridge error IMG-00710: unable to write to destination image ORA-01031: insufficient privileges </code></pre> <p>Trying other operations (like 'rotate 90') gives same errors.</p>
[ { "answer_id": 91876, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 0, "selected": false, "text": "<p>Can you please show the select statement you use to get l_ordimage? The main cause of this error seems to be if you don't have \"for update\" in your select statement, but I can't get intermedia going at the moment to test.</p>\n" }, { "answer_id": 253114, "author": "Sten Vesterli", "author_id": 9363, "author_profile": "https://Stackoverflow.com/users/9363", "pm_score": 3, "selected": true, "text": "<p>Even though the documentation states that it should be possible to edit an ORDImage \"in-place\", I was unable to make it work. </p>\n\n<p>Instead, I created a new ORDImage object and used processCopy:</p>\n\n<pre><code> vNewImage ORDImage;\n...\n vLocalImage.processCopy('maxScale 534 401', vNewImage);\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363/" ]
I have loaded image into a new, initialized Oracle ORDImage object and am processing it by PL/SQL. I can read its properties, but cannot process it with the process() method. ``` vLocalImage ORDImage := ORDImage.init(); ... vLocalImage.source.localdata := PORTAL.wwdoc_admin.get_document_blob_content(pFile); vLocalImage.setProperties(); ... if vLocalImage.width > lMaxWidth then vLocalImage.process('maxScale 534 401'); end if; ``` This should scale the image down, conserving aspect ratio, so that it is no more than 534 px wide and no more than 401 px high. However, I get the following error stack: ``` Internal error: ORA-29400: data cartridge error IMG-00710: unable to write to destination image ORA-01031: insufficient privileges ``` Trying other operations (like 'rotate 90') gives same errors.
Even though the documentation states that it should be possible to edit an ORDImage "in-place", I was unable to make it work. Instead, I created a new ORDImage object and used processCopy: ``` vNewImage ORDImage; ... vLocalImage.processCopy('maxScale 534 401', vNewImage); ```
85,019
<p>Google Maps used to do this bit where when you hit the &quot;Print&quot; link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information.</p> <p>It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a &quot;print version&quot; of things like articles and so forth.</p> <p>But if you wanted to make a webpage such that a &quot;printer friendly&quot; version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that?</p>
[ { "answer_id": 85026, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>You can do this with the css when you specify media as print.</p>\n" }, { "answer_id": 85039, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>Use a <a href=\"http://alistapart.com/stories/goingtoprint/\" rel=\"nofollow noreferrer\">print stylesheet</a>.</p>\n\n<p><strong>Edit:</strong> Regarding the followup, you can't, in general, add things to a page with CSS.</p>\n\n<p>One option is to include your print-only content in the page, and hide it for screen stylesheets. You should make sure that the page still makes sense without CSS though.</p>\n\n<p>Another option is to use generated content, but this isn't supported by Internet Explorer 7 and below, and can be quite limited.</p>\n\n<p>If the print-only content is an image, you can swap that out using one of the popular image replacement techniques.</p>\n" }, { "answer_id": 85052, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>Another way, if desired, is to have the 'print' button on the page change the page in some way that you decide, then perform a javascript 'window.print();' to bring up the browser's print dialog.</p>\n" }, { "answer_id": 85055, "author": "Sean McMains", "author_id": 2041950, "author_profile": "https://Stackoverflow.com/users/2041950", "pm_score": 0, "selected": false, "text": "<p>The easiest way is to use CSS media types. For each CSS file you include, you can specify where it ought to be used: on-screen, when printing, for handhelds, for screen-readers, or various combinations of these.</p>\n\n<p>Example: <em>&lt;link rel=\"stylesheet\" type=\"text/css\" media=\"print, handheld\" href=\"foo.css\"&gt;</em></p>\n\n<p>This has been a standard since CSS2, and most browsers support it now. More information is available here: <a href=\"http://www.w3.org/TR/CSS2/media.html\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/media.html</a></p>\n" }, { "answer_id": 85061, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 3, "selected": false, "text": "<p>You can achieve this effect by creating a css stylesheet which is targeted directly to printing, and another targeted directly for the screen.</p>\n\n<p>Use the link tag:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"print.css\" media=\"print, handheld\" /&gt;\n&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"screen.css\" media=\"screen\" /&gt;\n</code></pre>\n\n<p>to embed your stylesheet into your document. </p>\n\n<p>To hide is easy, just set your block style to hidden in whatever stylesheet you want and it wont be displayed. For example:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.newStyle1 {\n display: none;\n}\n</code></pre>\n\n<p>Then anything set to the style of <code>newStyle1</code> will not be displayed. </p>\n" }, { "answer_id": 85067, "author": "Toby Mills", "author_id": 12377, "author_profile": "https://Stackoverflow.com/users/12377", "pm_score": 1, "selected": false, "text": "<p>There are several options available to you:</p>\n\n<ul>\n<li>You can open a new window with slightly different data to be printed. </li>\n<li>There are also CSS styles which you can use to alter the page layout.</li>\n<li>Finally you can specify completly different style sheets for screen, printed media, Braille readers etc.</li>\n</ul>\n\n<p>e.g. <code>&lt;link href=\"css/print.css\" type=\"text/css\" rel=\"stylesheet\" media=\"print\" /&gt;</code></p>\n\n<p>See also <a href=\"http://www.w3schools.com/css/css_ref_print.asp\" rel=\"nofollow noreferrer\">CSS2 Print Reference</a></p>\n" }, { "answer_id": 85081, "author": "SpoonMeiser", "author_id": 1577190, "author_profile": "https://Stackoverflow.com/users/1577190", "pm_score": 0, "selected": false, "text": "<p>CSS allows you to create stylesheets for particular types of media, meaning that you can have a stylesheet that only applies when you're printing a page, allowing you to cause it to be formatted differently.</p>\n\n<p>Just include a media=\"print\" attribute on your stylesheet link for that stylesheet.</p>\n\n<p>This <a href=\"http://alistapart.com/stories/goingtoprint/\" rel=\"nofollow noreferrer\">A List Apart article</a> seems to be quite good on the subject.</p>\n" }, { "answer_id": 85087, "author": "Twan", "author_id": 6702, "author_profile": "https://Stackoverflow.com/users/6702", "pm_score": 0, "selected": false, "text": "<p>I tried using different style sheets based on the media, but I ran into trouble getting all the options I needed in. Since then I usually redirect to a different entrance of our (Fusebox) framework (i.e. print.php in stead of index.php) which in essence is the same file except it sets an extra flag/constant. </p>\n\n<p>In the XSL file associated with the page I then do additional work based on that flag/constant like leaving out the menu, columns of a table etc.</p>\n\n<p>i.e. (Page shows a link that the user has to click to display the password on the screen. The print version has the password printed.)</p>\n\n<pre><code>if (!BOOL_PRINT)\n echo \"&lt;TD class=\\\"tbl_teams_scroll_item\\\"&gt;&lt;SPAN class=\\\"span_password_hidden\\\" id=\\\"span_password_{\\$team_id}\\\" onClick=\\\"RevealPassword('{\\$team_id}','{\\$password}');\\\"&gt;&lt;xsl:value-of select=\\\"/PAGE/TEXTS/HIDDEN\\\" /&gt;&lt;/SPAN&gt;&lt;/TD&gt;\\n\";\nelse\n echo \"TD class=\\\"tbl_teams_scroll_item\\\"&gt;&lt;xsl:value-of select=\\\"PASSWORD\\\" /&gt;&lt;/TD&gt;\\n\";\n</code></pre>\n" }, { "answer_id": 85107, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 2, "selected": false, "text": "<p>The <code>@media</code> rule in CSS can be used to define alternate rules for print.This is often used to hide navigation and change the style to fit print better:</p>\n\n<pre><code>@media print {\n .sidebar { display: none; }\n}\n</code></pre>\n\n<p>You can also link a seperate stylesheet for print:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"print.css\" type=\"text/css\" media=\"print\" /&gt;\n</code></pre>\n" }, { "answer_id": 85110, "author": "dave", "author_id": 14355, "author_profile": "https://Stackoverflow.com/users/14355", "pm_score": 0, "selected": false, "text": "<p>You can define css rules that are specific to a media type. The following is a css example (copied from <a href=\"http://www.w3.org/TR/CSS2/media.html\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/media.html</a>, section 7.2.1) that specifies different font sizes what gets displayed on a web page and what gets printed. </p>\n\n<pre><code> @media print {\n BODY { font-size: 10pt }\n }\n @media screen {\n BODY { font-size: 12pt }\n }\n @media screen, print {\n BODY { line-height: 1.2 }\n }\n</code></pre>\n\n<p>Alternatively, you can specify what media a stylesheet should be applied to when including it in a page:</p>\n\n<pre><code> &lt;link href=\"webstyles.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\"/&gt;\n &lt;link href=\"printstyles.css\" type=\"text/css\" rel=\"stylesheet\" media=\"print\"/&gt;\n &lt;link href=\"commonstyles.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen,print\"/&gt;\n</code></pre>\n" }, { "answer_id": 85121, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 0, "selected": false, "text": "<p>Yet another option is to have a hidden IFRAME that you call iframe.contentWindow.print() on. That will allow you to create an invisible layout that prints exactly as you want it to.</p>\n\n<p>Of course, an even better solution is to export the file to a PDF and let the user print it out that way. PDFs produce the highest quality output, period. However, it is one more hoop for the user to jump through, so the rule of thumb is:</p>\n\n<ul>\n<li>PDFs for when the print layout matters</li>\n<li>HTML for when the pure text is more important than the layout</li>\n</ul>\n" }, { "answer_id": 87095, "author": "Steve Perks", "author_id": 16124, "author_profile": "https://Stackoverflow.com/users/16124", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/85019/how-can-you-make-a-web-page-send-to-the-printer-something-different-than-whats/85052#85052\">nsayer</a> mentions having a print button change the layout of your screen and then kicking off a <code>window.print()</code></p>\n\n<p>This is a solution that will probably have been overlooked by a lot of people and should be considered when you think your users want a little more of a WYSIWYG. It should probably be a \"printer friendly\" link though that changes the media type of your sheet sheets rather than \"print this\".</p>\n\n<p>Using jquery, you could do something like this (not checked):</p>\n\n<pre><code>$(document).ready(function(){\n $(\"#printFriendly\").click(function(){\n $(link[rel=link][media=screen]).remove();\n $(link[rel=link][media=print]).attr(\"media\",\"screen\");\n });\n});\n</code></pre>\n" }, { "answer_id": 134814, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 0, "selected": false, "text": "<p>Anything you can do with CSS you can do in a print stylesheet. This means you can hide content in the print version which is shown in the screen version or hide content in the screen version which you want to show up when printing.All you do is apply display:none to the appropriate sections in the appropriate stylesheet. </p>\n\n<p>Also it is a good idea to size your text in points for the print version (which is a <em>bad</em> idea for the screen version - stick to pixels, ems or percentages here). There is universal agreement as to what printed point sizes are where as mappings of pixels to points will vary with different resolution devices.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
Google Maps used to do this bit where when you hit the "Print" link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information. It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a "print version" of things like articles and so forth. But if you wanted to make a webpage such that a "printer friendly" version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that?
You can achieve this effect by creating a css stylesheet which is targeted directly to printing, and another targeted directly for the screen. Use the link tag: ``` <link rel="stylesheet" type="text/css" href="print.css" media="print, handheld" /> <link rel="stylesheet" type="text/css" href="screen.css" media="screen" /> ``` to embed your stylesheet into your document. To hide is easy, just set your block style to hidden in whatever stylesheet you want and it wont be displayed. For example: ```css .newStyle1 { display: none; } ``` Then anything set to the style of `newStyle1` will not be displayed.
85,033
<p>I am wrapping a native C++ class, which has the following methods:</p> <pre><code>class Native { public: class Local { std::string m_Str; int m_Int; }; typedef std::vector&lt;Local&gt; LocalVec; typedef LocalVec::iterator LocalIter; LocalIter BeginLocals(); LocalIter EndLocals(); private: LocalVec m_Locals; }; </code></pre> <p>1) What is the ".NET way" of representing this same kind of interface? A single method returning an array&lt;>? Does the array&lt;> generic have iterators, so that I could implement BeginLocals() and EndLocals()? </p> <p>2) Should Local be declared as a <strong>value struct</strong> in the .NET wrapper?</p> <p>I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for...</p>
[ { "answer_id": 85402, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 4, "selected": true, "text": "<p>Iterators aren't exactly translatable to \"the .net way\", but they are roughly replaced by IEnumerable &lt; T > and IEnumerator &lt; T >. </p>\n\n<p>Rather than </p>\n\n<pre><code> vector&lt;int&gt; a_vector;\n vector&lt;int&gt;::iterator a_iterator;\n for(int i= 0; i &lt; 100; i++)\n {\n a_vector.push_back(i);\n }\n\n int total = 0;\n a_iterator = a_vector.begin();\n while( a_iterator != a_vector.end() ) {\n total += *a_iterator;\n a_iterator++;\n }\n</code></pre>\n\n<p>you would see (in c#)</p>\n\n<pre><code>List&lt;int&gt; a_list = new List&lt;int&gt;();\nfor(int i=0; i &lt; 100; i++)\n{\n a_list.Add(i);\n}\nint total = 0;\nforeach( int item in a_list)\n{\n total += item;\n}\n</code></pre>\n\n<p>Or more explicitly (without hiding the IEnumerator behind the foreach syntax sugar):</p>\n\n<pre><code>List&lt;int&gt; a_list = new List&lt;int&gt;();\nfor (int i = 0; i &lt; 100; i++)\n{\n a_list.Add(i);\n}\nint total = 0;\nIEnumerator&lt;int&gt; a_enumerator = a_list.GetEnumerator();\nwhile (a_enumerator.MoveNext())\n{\n total += a_enumerator.Current;\n}\n</code></pre>\n\n<p>As you can see, foreach just hides the .net enumerator for you.</p>\n\n<p>So really, the \".net way\" would be to simply allow people to create List&lt; Local > items for themselves. If you do want to control iteration or make the collection a bit more custom, have your collection implement the IEnumerable&lt; T > and/or ICollection&lt; T > interfaces as well.</p>\n\n<p>A near direct translation to c# would be pretty much what you assumed:</p>\n\n<pre><code>public class Native\n{\n public class Local\n { \n public string m_str;\n public int m_int;\n }\n\n private List&lt;Local&gt; m_Locals = new List&lt;Local&gt;();\n\n public List&lt;Local&gt; Locals\n {\n get{ return m_Locals;}\n }\n}\n</code></pre>\n\n<p>Then a user would be able to </p>\n\n<pre><code>foreach( Local item in someNative.Locals) \n{\n ... \n}\n</code></pre>\n" }, { "answer_id": 86875, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 0, "selected": false, "text": "<p>@Phillip - Thanks, your answer really got me started in the right direction. </p>\n\n<p>After seeing your code, and doing a little more reading in Nish's book <strong>C++/CLI in Action</strong>, I think using an indexed property that returns a const tracking handle to a Local instance on the managed heap is probably the best approach. I ended up implementing something similar to the following:</p>\n\n<pre><code>public ref class Managed\n{\n public:\n ref class Local\n {\n String^ m_Str;\n int m_Int;\n };\n\n property const Local^ Locals[int]\n {\n const Local^ get(int Index)\n {\n // error checking here...\n return m_Locals[Index];\n }\n };\n\n private:\n List&lt;Local^&gt; m_Locals;\n};\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I am wrapping a native C++ class, which has the following methods: ``` class Native { public: class Local { std::string m_Str; int m_Int; }; typedef std::vector<Local> LocalVec; typedef LocalVec::iterator LocalIter; LocalIter BeginLocals(); LocalIter EndLocals(); private: LocalVec m_Locals; }; ``` 1) What is the ".NET way" of representing this same kind of interface? A single method returning an array<>? Does the array<> generic have iterators, so that I could implement BeginLocals() and EndLocals()? 2) Should Local be declared as a **value struct** in the .NET wrapper? I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for...
Iterators aren't exactly translatable to "the .net way", but they are roughly replaced by IEnumerable < T > and IEnumerator < T >. Rather than ``` vector<int> a_vector; vector<int>::iterator a_iterator; for(int i= 0; i < 100; i++) { a_vector.push_back(i); } int total = 0; a_iterator = a_vector.begin(); while( a_iterator != a_vector.end() ) { total += *a_iterator; a_iterator++; } ``` you would see (in c#) ``` List<int> a_list = new List<int>(); for(int i=0; i < 100; i++) { a_list.Add(i); } int total = 0; foreach( int item in a_list) { total += item; } ``` Or more explicitly (without hiding the IEnumerator behind the foreach syntax sugar): ``` List<int> a_list = new List<int>(); for (int i = 0; i < 100; i++) { a_list.Add(i); } int total = 0; IEnumerator<int> a_enumerator = a_list.GetEnumerator(); while (a_enumerator.MoveNext()) { total += a_enumerator.Current; } ``` As you can see, foreach just hides the .net enumerator for you. So really, the ".net way" would be to simply allow people to create List< Local > items for themselves. If you do want to control iteration or make the collection a bit more custom, have your collection implement the IEnumerable< T > and/or ICollection< T > interfaces as well. A near direct translation to c# would be pretty much what you assumed: ``` public class Native { public class Local { public string m_str; public int m_int; } private List<Local> m_Locals = new List<Local>(); public List<Local> Locals { get{ return m_Locals;} } } ``` Then a user would be able to ``` foreach( Local item in someNative.Locals) { ... } ```
85,034
<p>I want to make a table in SqlServer that will add, on insert, a auto incremented primary key. This should be an autoincremented id similar to MySql auto_increment functionality. (Below)</p> <pre><code>create table foo ( user_id int not null auto_increment, name varchar(50) ) </code></pre> <p>Is there a way of doing this with out creating an insert trigger?</p>
[ { "answer_id": 85038, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>Just set the field as an <a href=\"http://msdn.microsoft.com/en-us/library/aa933196.aspx\" rel=\"nofollow noreferrer\">identity field</a>.</p>\n" }, { "answer_id": 85042, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 5, "selected": true, "text": "<p>Like this</p>\n\n<pre><code>create table foo \n( \nuser_id int not null identity, \nname varchar(50) \n)\n</code></pre>\n" }, { "answer_id": 85043, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 1, "selected": false, "text": "<p>declare the field to be identity</p>\n" }, { "answer_id": 85826, "author": "CodeRot", "author_id": 14134, "author_profile": "https://Stackoverflow.com/users/14134", "pm_score": 0, "selected": false, "text": "<p>As others have said, just set the Identity option.</p>\n" }, { "answer_id": 85858, "author": "Nasir", "author_id": 16522, "author_profile": "https://Stackoverflow.com/users/16522", "pm_score": 1, "selected": false, "text": "<p>As advised above, use an IDENTITY field.</p>\n\n<pre><code>CREATE TABLE foo\n(\nuser_id int IDENTITY(1,1) NOT NULL,\nname varchar(50)\n)\n</code></pre>\n" }, { "answer_id": 86110, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": false, "text": "<p>OP requested an auto incremented primary key. The IDENTITY keyword does not, by itself, make a column be the primary key.</p>\n\n<pre><code>CREATE TABLE user\n(\n TheKey int IDENTITY(1,1) PRIMARY KEY,\n Name varchar(50)\n)\n</code></pre>\n" }, { "answer_id": 86595, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 2, "selected": false, "text": "<p>As others have mentioned: add the IDENTITY attribute to the column, and make it a primary key.</p>\n\n<p>There are, however, differences between MSSQL's IDENTITY and MySQL's AUTO_INCREMENT:</p>\n\n<ul>\n<li>MySQL requires that a unique\nconstraint (often in the form of a\nprimary key) be defined for the\nAUTO_INCREMENT column.<br />MSSQL doesn't have such a requirement.</li>\n<li>MySQL lets you manually insert values into an AUTO_INCREMENT column.\n<br />MSSQL prevents you from manually inserting a value into an IDENTITY\ncolumn; if needed, you can override\nthis by issuing a \"SET\nIDENTITY_INSERT tablename ON\"\ncommand before the insert.</li>\n<li>MySQL allows you to update values in an AUTO_INCREMENT column.<br />MSSQL refuses to update values in an\nIDENTITY column.</li>\n</ul>\n" }, { "answer_id": 244627, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 3, "selected": false, "text": "<p>They have answered your question but I want to add one bit of advice for someone new to using identity columns. There are times when you have to return the value of the identity just inserted so that you can insert into a related table. Many sources will tell you to use @@identity to get this value. Under no circumstances should you ever use @@identity if you want to mantain data integrity. It will give the identity created in a trigger if one of them is added to insert to another table. Since you cannot guarantee the value of @@identity will always be correct, it is best to never use @@identity. Use scope_identity() to get this value instead. I know this is slightly off topic, but it is important to your understanding of how to use identity with SQL Server. And trust me, you did not want to be fixing a problem of the related records having the wrong identity value fed to them. This is something that can quietly go wrong for months before it is dicovered and is almost impossible to fix the data afterward. </p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12942/" ]
I want to make a table in SqlServer that will add, on insert, a auto incremented primary key. This should be an autoincremented id similar to MySql auto\_increment functionality. (Below) ``` create table foo ( user_id int not null auto_increment, name varchar(50) ) ``` Is there a way of doing this with out creating an insert trigger?
Like this ``` create table foo ( user_id int not null identity, name varchar(50) ) ```
85,036
<p>I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance?</p> <p>I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to.</p>
[ { "answer_id": 85075, "author": "Craig", "author_id": 7861, "author_profile": "https://Stackoverflow.com/users/7861", "pm_score": 2, "selected": false, "text": "<p>Although not free I have had good experience using Red-Gates <a href=\"http://www.red-gate.com/products/SQL_Compare/index.htm\" rel=\"nofollow noreferrer\">SQL Compare tool</a>. It worked for me in the past. They have a free trial available which may be good enough to solve your current issue.</p>\n" }, { "answer_id": 85084, "author": "RBS", "author_id": 14299, "author_profile": "https://Stackoverflow.com/users/14299", "pm_score": 0, "selected": false, "text": "<p>You can use following type of query to find modified stored procedures , you can use any number then 7 as per your needs</p>\n\n<pre><code>SELECT name\n FROM sys.objects\n WHERE type = 'P'\n AND DATEDIFF(D,modify_date, GETDATE()) &lt; 7\n</code></pre>\n" }, { "answer_id": 85096, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 4, "selected": false, "text": "<p>You can execute this query to find all stored procedures modified in the last x number of days:</p>\n\n<pre><code>SELECT name\nFROM sys.objects\nWHERE type = 'P'\n AND DATEDIFF(D,modify_date, GETDATE()) &lt; X\n</code></pre>\n" }, { "answer_id": 85111, "author": "RBS", "author_id": 14299, "author_profile": "https://Stackoverflow.com/users/14299", "pm_score": 1, "selected": false, "text": "<p>you can also use the following code snipet </p>\n\n<pre><code>USE AdventureWorks2008;\n\nGO\n\nSELECT SprocName=name, create_date, modify_date\n\nFROM sys.objects\n\nWHERE type = 'P' \n\nAND name = 'uspUpdateEmployeeHireInfo'\n\nGO\n</code></pre>\n" }, { "answer_id": 85150, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 0, "selected": false, "text": "<p>There are several database compare tools out there. One that I've always like is SQLCompare by <a href=\"http://www.red-gate.com\" rel=\"nofollow noreferrer\">Red Gate</a>.</p>\n\n<p>You can also try using:</p>\n\n<pre><code>SELECT name\nFROM sys.objects\nWHERE modify_date &gt; @cutoffdate\n</code></pre>\n\n<p>In SQL 2000 that wouldn't have always worked, because using ALTER didn't update the date correctly, but in 2005 I believe that problem is fixed.</p>\n\n<p>I use a SQL compare tool myself though, so I can't vouch for that method 100%</p>\n" }, { "answer_id": 85191, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 7, "selected": true, "text": "<p>instead of using sysobjects which is not recommended anymore use sys.procedures</p>\n\n<pre><code>select name,create_date,modify_date\nfrom sys.procedures\norder by modify_date desc\n</code></pre>\n\n<p>you can do the where clause yourself but this will list it in order of modification date descending</p>\n" }, { "answer_id": 18616042, "author": "Ron Biggs", "author_id": 2362253, "author_profile": "https://Stackoverflow.com/users/2362253", "pm_score": 4, "selected": false, "text": "<p>There are some special cases where scripts might not give optimal results.</p>\n<p>One is deleting stored procedures or other objects in dev environment – you won’t catch this using system views because object won’t exist there any longer.</p>\n<p>Also, I’m not really sure this approach can work on changes such as permissions and similar.</p>\n<p>In such cases its best to use some third party tool just to double check nothing is missed.</p>\n<p>I’ve successfully used <a href=\"http://www.apexsql.com/sql_tools_diff.aspx\" rel=\"nofollow noreferrer\">ApexSQL Diff</a> in the past for similar tasks and it worked really good on large databases with 1000+ objects but you can’t go wrong with SQL Compare that’s already mentioned here or basically any other tool that exists on the market.</p>\n<p>Disclaimer: I’m not affiliated with any of the vendors I’m mentioning here but I do use both set of tools (Apex and RG) in the company I work for.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16137/" ]
I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance? I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to.
instead of using sysobjects which is not recommended anymore use sys.procedures ``` select name,create_date,modify_date from sys.procedures order by modify_date desc ``` you can do the where clause yourself but this will list it in order of modification date descending
85,058
<p>I see <a href="http://www.is-research.de/info/vmlanguages/index.html" rel="noreferrer">here</a> that there are a load of languages aside from Java that run on the JVM. I'm a bit confused about the whole concept of other languages running in the JVM. So:</p> <p>What is the advantage in having other languages for the JVM?</p> <p>What is required (in high level terms) to write a language/compiler for the JVM? </p> <p>How do you write/compile/run code in a language (other than Java) in the JVM?</p> <hr> <p><strong>EDIT:</strong> There were 3 follow up questions (originally comments) that were answered in the accepted answer. They are reprinted here for legibility:</p> <p>How would an app written in, say, JPython, interact with a Java app? </p> <p>Also, Can that JPython application use any of the JDK functions/objects?? </p> <p>What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK?</p>
[ { "answer_id": 85072, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>They do it to keep up with .Net. .Net allows C#, VB, J# (formerly), F#, Python, Ruby (coming soon), and c++. I'm probably missing some. Probably the big one in there is Python, for the scripting people.</p>\n" }, { "answer_id": 85095, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>What the JVM can do is defined by the JVM's bytecode (what you find in .class files) rather than the source language. So changing the high level source code language isn't going to have a substantial impact on the available functionality.</p>\n\n<p>As for what is required to write a compiler for the JVM, all you really need to do is generate correct bytecode / .class files. How you write/compile code with an alternate compiler sort of depends on the compiler in question, but once the compiler outputs .class files, running them is no different than running the .class files generated by javac.</p>\n" }, { "answer_id": 85103, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>I would answer, “because <a href=\"http://www.google.com/search?&amp;q=java%20sucks\" rel=\"nofollow noreferrer\">Java sucks</a>” but then again, perhaps that's <a href=\"http://en.wikipedia.org/wiki/Criticism_of_Java\" rel=\"nofollow noreferrer\">too obvious</a> … ;-)</p>\n" }, { "answer_id": 85118, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 4, "selected": false, "text": "<p>You need other languages on the JVM for the same reason you need multiple programming languages in general: Different languages are better as solving different problems ... static typing vs. dynamic typing, strict vs. lazy ... Declarative, Imperative, Object Oriented ... etc.</p>\n\n<p>In general, writing a \"compiler\" for another language to run on the JVM (or on the .Net CLR) is essentially a matter of compiling that language into java bytecode (or in the case of .Net, IL) instead of to assembly/machine language. </p>\n\n<p>That said, a lot of the extra languages that are being written for JVM aren't compiled, but rather interpreted scripting languages...</p>\n" }, { "answer_id": 85130, "author": "Alex Argo", "author_id": 5885, "author_profile": "https://Stackoverflow.com/users/5885", "pm_score": 2, "selected": false, "text": "<p>Java is a fairly verbose programming language that is getting outdated very quickly with all of the new fancy languages/frameworks coming out in the past 5 years. To support all the fancy syntax that people want in a language AND preserve backwards compatibility it makes more sense to add more languages to the runtime.</p>\n\n<p>Another benefit is it lets you run some web frameworks written in Ruby ala JRuby (aka Rails), or Grails(Groovy on Railys essentially), etc. on a proven hosting platform that likely already is in production at many companies, rather than having to using that not nearly as tried and tested Ruby hosting environments.</p>\n\n<p>To compile the other languages you are just converting to Java byte code.</p>\n" }, { "answer_id": 85141, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The advantage to having other languages for the JVM is quite the same as the advantage to having other languages for computer in general: while all turing-complete languages can technically accomplish the same tasks, some languages make some tasks easier than others while other languages make other tasks easier. Since the JVM is something we already have the ability to run on all (well, nearly all) computers, and a lot of computers, in fact already have it, we can get the \"write once, run anywhere\" benefit, but without requiring that one uses Java.</p>\n\n<p>Writing a language/compiler for the JVM isn't really different from writing one for a real machine. The real difference is that you have to compile to the JVM's bytecode instead of to the machine's executable code, but that's really a minor difference in the grand scheme of things.</p>\n\n<p>Writing code for a language other than Java in the JVM really isn't different from writing Java except, of course, that you'll be using a different language. You'll compile using the compiler that somebody writes for it (again, not much different from a C compiler, fundamentally, and pretty much not different at all from a Java compiler), and you'll end up being able to run it just like you would compiled Java code since once it's in bytecode, the JVM can't tell what language it came from.</p>\n" }, { "answer_id": 85154, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 1, "selected": false, "text": "<p>The advantage for these other languages is that they get relatively easy access to lots of java libraries.</p>\n\n<p>The advantage for Java people varies depending on language -- each has a story tell Java coders about what they do better. Some will stress how they can be used to add dynamic scripting to JVM-based apps, others will just talk about how their language is easier to use, has a better syntax, or so forth.</p>\n\n<p>What's required are the same things to write any other language compiler: parsing to an AST, then transforming that to instructions for the target architecture (byte code) and storing it in the right format (.class files).</p>\n\n<p>From the users' perspective, you just write code and run the compiler binaries, and out comes .class files you can mix in with those your java compiler produces.</p>\n" }, { "answer_id": 85158, "author": "Kyle", "author_id": 16379, "author_profile": "https://Stackoverflow.com/users/16379", "pm_score": 2, "selected": false, "text": "<p>Different languages are tailored to different tasks. While certain problem domains fit the Java language perfectly, some are much easier to express in alternative languages. Also, for a user accustomed to Ruby, Python, etc, the ability to generate Java bytecode and take advantage of the JDK classes and JIT compiler has obvious benefits.</p>\n" }, { "answer_id": 85193, "author": "TygerKrash", "author_id": 7652, "author_profile": "https://Stackoverflow.com/users/7652", "pm_score": 0, "selected": false, "text": "<p>To an extent it is probably an 'Arms Race' against the .NET CLR. </p>\n\n<p>But I think there are also genuine reasons for introducing new languages to the JVM, particularly when they will be run 'in parallel', you can use the right language for the right job, a scripting language like Groovy may be exactly what you need for your page presentation, whereas regular old Java is better for your business logic. </p>\n\n<p>I'm going to leave someone more qualified to talk about what is required to write a new language/compiler.</p>\n\n<p>As for how to writing code, you do it in notepad/vi as usual! (or use a development tool that supports the language if you want to do it the easy way.) Compiling will require a special compiler for the language that will interpret and compile it into bytecode.</p>\n\n<p>Since java also produces bytecode technically you don't need to do anything special to run it. </p>\n" }, { "answer_id": 85231, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 1, "selected": false, "text": "<p>The .NET languages are more for show than actual usefulness. Each language has been so butchered, that they're all C# with a new face.</p>\n\n<p>There are a variety of reasons to provide alternative languages for the Java VM:</p>\n\n<ul>\n<li>The JVM is multiplatform. Any language ported to the JVM gets that as a free bonus.</li>\n<li>There is quite a bit of legacy code out there. Antiquated engines like ColdFusion perform better while offering customers the ability to slowly phase their applications from the legacy solution to the modern solution.</li>\n<li>Certain forms of scripting are better suited to rapid development. JavaFX, for example, is designed with rapid Graphical development in mind. In this way it competes with engines like DarkBasic. (Processing is another player in this space.)</li>\n<li>Scripting environments can offer control. For example, an application may wish to expose a VBA-like environment to the user without exposing the underlying Java APIs. Using an engine like Rhino can provide an environment that supports quick and dirty coding in a carefully controlled sandbox. </li>\n<li>Interpreted scripts mean that there's no need to recompile anything. No need to recompile translates into a more dynamic environment. e.g. Despite OpenOffice's use of Java as a \"scripting language\", Java sucks for that use. The user has to go through all kinds of recompile/reload gyrations that are unnecessary in a dynamic scripting environment like Javascript.</li>\n<li>Which brings me to another point. Scripting engines can be more easily stopped and reloaded without stopping and reloading the entire JVM. This increases the utility of the scripting language as the environment can be reset at any time. </li>\n</ul>\n" }, { "answer_id": 85291, "author": "Chris Dodd", "author_id": 16406, "author_profile": "https://Stackoverflow.com/users/16406", "pm_score": 2, "selected": false, "text": "<p>Answering just your second question:</p>\n\n<p>The JVM is just an abstract machine and execution model. So targetting it with a compiler is just the same as any other machine and execution model that a compiler might target, be it implemented in hardware (x86, CELL, etc) or software (parrot, .NET). The JVM is fairly simple, so its actually a fairly easy target for compilers. Also, implementations tend to have pretty good JIT compilers (to deal with the lousy code that javac produces), so you can get good performance without having to worry about a lot of optimizations.</p>\n\n<p>A couple of caveats apply. First, the JVM directly embodies java's module and inheritance system, so trying to do anything else (multiple inheritance, multiple dispatch) is likely to be tricky and require convoluted code. Second, JVMs are optimized to deal with the kind of bytecode that javac produces. Producing bytecode that is very different from this is likely to get into odd corners of the JIT compiler/JVM which will likely be inefficient at best (at worst, they can crash the JVM or at least give spurious VirtualMachineError exceptions).</p>\n" }, { "answer_id": 85712, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>It's much easier for a compiler writer to generate JVM or CLR byte-codes. They are a much cleaner and higher level abstraction than any machine language. Because of this, it is much more feasible to experiment with creating new languages than ever before, because all you have to do is target one of these VM architectures and you will have a set of tools and libraries already available for your language. They let language designers focus more on the language than all the necessary support infrastructure.</p>\n" }, { "answer_id": 85751, "author": "Mike Tunnicliffe", "author_id": 13956, "author_profile": "https://Stackoverflow.com/users/13956", "pm_score": 3, "selected": false, "text": "<p>Turning this on its head, consider you want to design a new language and you want it to run in a managed runtime with a JIT and GC. Then consider that you could:</p>\n\n<p>(a) write you own managed runtime (VM) and tackle all sorts of technically difficult issues that will doubtless lead to many bugs, bad performance, improper threading and a great deal of portability effort </p>\n\n<p>or </p>\n\n<p>(b) compile your language into bytecode that can run on the Java VM which is already quite mature, fast and supported on a number of platforms (sometimes with more than one choice of vendor impementation).</p>\n\n<p>Given that the JavaVM bytecode is not tied so closely to the Java language as to unduly restrict the type of language you can implement, it has been a popular target environment for languages that want to run in a VM.</p>\n" }, { "answer_id": 86201, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 6, "selected": true, "text": "<p>To address your three questions separately:</p>\n\n<blockquote>\n <p>What is the advantage in having other languages for the JVM?</p>\n</blockquote>\n\n<p>There are two factors here. (1) Why have a language other than Java for the JVM, and (2) why have another language run on the JVM, instead of a different runtime? </p>\n\n<ol>\n<li>Other languages can satisfy other needs. For example, Java has no built-in support for <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"noreferrer\">closures</a>, a feature that is often very useful. </li>\n<li>A language that runs on the JVM is bytecode compatible with any other language that runs on the JVM, meaning that code written in one language can interact with a library written in another language.</li>\n</ol>\n\n<blockquote>\n <p>What is required (in high level terms) to write a language/compiler for the JVM?</p>\n</blockquote>\n\n<p>The JVM reads bytecode (.class) files to obtain the instructions it needs to perform. Thus any language that is to be run on the JVM needs to be compiled to bytecode adhering to the <a href=\"http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html\" rel=\"noreferrer\">Sun specification</a>. This process is similar to compiling to native code, except that instead of compiling to instructions understood by the CPU, the code is compiled to instructions that are interpreted by the JVM.</p>\n\n<blockquote>\n <p>How do you write/compile/run code in a language (other than Java) in the JVM?</p>\n</blockquote>\n\n<p>Very much in the same way you write/compile/run code in Java. To get your feet wet, I'd recommend looking at <a href=\"http://www.scala-lang.org/\" rel=\"noreferrer\">Scala</a>, which runs flawlessly on the JVM.</p>\n\n<p>Answering your follow up questions:</p>\n\n<blockquote>\n <p>How would an app written in, say, JPython, interact with a Java app?</p>\n</blockquote>\n\n<p>This depends on the implementation's choice of bridging the language gap. In your example, <a href=\"http://www.jython.org/Project/\" rel=\"noreferrer\">Jython project</a> has a straightforward means of doing this (<a href=\"http://wiki.python.org/jython/UserGuide#accessing-java-from-jython\" rel=\"noreferrer\">see here</a>):</p>\n\n<pre><code>from java.net import URL\nu = URL('http://jython.org')\n</code></pre>\n\n<blockquote>\n <p>Also, can that JPython application use any of the JDK functions/objects?</p>\n</blockquote>\n\n<p>Yes, see above.</p>\n\n<blockquote>\n <p>What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK?</p>\n</blockquote>\n\n<p>No. Scala (link above) for example implements functional features while maintaining compatibility with Java. For example:</p>\n\n<pre><code>object Timer {\n def oncePerSecond(callback: () =&gt; unit) {\n while (true) { callback(); Thread sleep 1000 }\n }\n def timeFlies() {\n println(\"time flies like an arrow...\")\n }\n def main(args: Array[String]) {\n oncePerSecond(timeFlies)\n }\n}\n</code></pre>\n" }, { "answer_id": 428046, "author": "Yaba", "author_id": 7524, "author_profile": "https://Stackoverflow.com/users/7524", "pm_score": 1, "selected": false, "text": "<p>Because the JSR process is rendering Java more and more dead: <a href=\"http://www.infoq.com/news/2009/01/java7-updated\" rel=\"nofollow noreferrer\">http://www.infoq.com/news/2009/01/java7-updated</a></p>\n\n<p>It's a shame that even essential and long known additions like Closures are not added just because the members cannot agree on an implementation.</p>\n" }, { "answer_id": 428120, "author": "Patrick Lee", "author_id": 48993, "author_profile": "https://Stackoverflow.com/users/48993", "pm_score": 0, "selected": false, "text": "<p>The reason is that the JVM platform offers a lot of advantages.</p>\n\n<ul>\n<li>Giant number of libraries</li>\n<li>Broader degree of platform\nimplementations</li>\n<li>Mature frameworks</li>\n<li>Legacy code that's\nalready part of your infrastructure</li>\n</ul>\n\n<p>The languages Sun is trying to support with their Scripting spec (e.g. Python, Ruby) are up and comers largely due to their perceived productivity enhancements. Running Jython allows you to, in theory, be more productive, and leverage the capabilities of <em>Python</em> to solve a problem more suited to Python, but still be able to integrate, on a runtime level, with your existing codebase. The classic implementations of <em>Python</em> and <em>Ruby</em> effect the same ability for <strong>C</strong> libraries.</p>\n\n<p>Additionally, it's often easier to express some things in a dynamic language than in Java. If this is the case, you can go the other way; consume <em>Python/Ruby</em> libraries from <em>Java</em>.</p>\n\n<p>There's a performance hit, but many are willing to accept that in exchange for a less verbose, clearer codebase.</p>\n" }, { "answer_id": 3164151, "author": "richj", "author_id": 38031, "author_profile": "https://Stackoverflow.com/users/38031", "pm_score": 1, "selected": false, "text": "<p>Java has accumulated a massive user base over seven major versions (from 1.0 to 1.6). Its capability to evolve is limited by the need to preserve backwards compatibility for the uncountable millions of lines of Java code running in production.</p>\n\n<p>This is a problem because Java needs to evolve to:</p>\n\n<ul>\n<li>compete with newer programming languages that have learned from Java's successes and failures.</li>\n<li>incorporate new advances in programming language design.</li>\n<li>allow users to take full advantage of advances in hardware - e.g. multi-core processors.</li>\n<li>fix some cutting edge ideas that introduced unexpected problems (e.g. checked exceptions, generics).</li>\n</ul>\n\n<p>The requirement for backwards compatibility is a barrier to staying competitive.</p>\n\n<p>If you compare Java to C#, Java has the advantage in mature, production ready libraries and frameworks, and a disadvantage in terms of language features and rate of increase in market share. This is what you would expect from comparing two successful languages that are one generation apart.</p>\n\n<p>Any new language has the same advantage and disadvantage that C# has compared to Java to an extreme degree. One way of maximizing the advantage in terms of language features, and minimizing the disadvantage in terms of mature libraries and frameworks is to build the language for an existing virtual machine and make it interoperable with code written for that virtual machine. This is the reason behind the modest success of Groovy and Clojure; and the excitement around Scala. Without the JVM these languages could only ever have occupied a tiny niche in a very specialized market segment, whereas with the JVM they occupy a significant niche in the mainstream.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142/" ]
I see [here](http://www.is-research.de/info/vmlanguages/index.html) that there are a load of languages aside from Java that run on the JVM. I'm a bit confused about the whole concept of other languages running in the JVM. So: What is the advantage in having other languages for the JVM? What is required (in high level terms) to write a language/compiler for the JVM? How do you write/compile/run code in a language (other than Java) in the JVM? --- **EDIT:** There were 3 follow up questions (originally comments) that were answered in the accepted answer. They are reprinted here for legibility: How would an app written in, say, JPython, interact with a Java app? Also, Can that JPython application use any of the JDK functions/objects?? What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK?
To address your three questions separately: > > What is the advantage in having other languages for the JVM? > > > There are two factors here. (1) Why have a language other than Java for the JVM, and (2) why have another language run on the JVM, instead of a different runtime? 1. Other languages can satisfy other needs. For example, Java has no built-in support for [closures](http://en.wikipedia.org/wiki/Closure_(computer_science)), a feature that is often very useful. 2. A language that runs on the JVM is bytecode compatible with any other language that runs on the JVM, meaning that code written in one language can interact with a library written in another language. > > What is required (in high level terms) to write a language/compiler for the JVM? > > > The JVM reads bytecode (.class) files to obtain the instructions it needs to perform. Thus any language that is to be run on the JVM needs to be compiled to bytecode adhering to the [Sun specification](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html). This process is similar to compiling to native code, except that instead of compiling to instructions understood by the CPU, the code is compiled to instructions that are interpreted by the JVM. > > How do you write/compile/run code in a language (other than Java) in the JVM? > > > Very much in the same way you write/compile/run code in Java. To get your feet wet, I'd recommend looking at [Scala](http://www.scala-lang.org/), which runs flawlessly on the JVM. Answering your follow up questions: > > How would an app written in, say, JPython, interact with a Java app? > > > This depends on the implementation's choice of bridging the language gap. In your example, [Jython project](http://www.jython.org/Project/) has a straightforward means of doing this ([see here](http://wiki.python.org/jython/UserGuide#accessing-java-from-jython)): ``` from java.net import URL u = URL('http://jython.org') ``` > > Also, can that JPython application use any of the JDK functions/objects? > > > Yes, see above. > > What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK? > > > No. Scala (link above) for example implements functional features while maintaining compatibility with Java. For example: ``` object Timer { def oncePerSecond(callback: () => unit) { while (true) { callback(); Thread sleep 1000 } } def timeFlies() { println("time flies like an arrow...") } def main(args: Array[String]) { oncePerSecond(timeFlies) } } ```
85,085
<p>I've got an RMI call defined as:</p> <pre><code>public void remoteGetCustomerNameNumbers(ArrayList&lt;String&gt; customerNumberList, ArrayList&lt;String&gt; customerNameList) throws java.rmi.RemoteException; </code></pre> <p>The function does a database lookup and populates the two ArrayLists. The calling function gets nothing. I believe this works with Vector types.</p> <p>Do I need to use the Vector, or is there a way to get this to work without making two calls. I've got some other ideas that I'd probably use, like returning a key/value pair, but I'd like to know if I can get this to work.</p> <p>Update:<br/> I would accept all of the answers given so far if I could. I hadn't known the network cost, so It makes sense to rework the function to return a LinkedHashMap instead of the two ArrayLists.</p>
[ { "answer_id": 85126, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 1, "selected": false, "text": "<p>You lose your references when you make the remote call. You'll need to return the lists rather than expect them to be populated by the remote call.</p>\n" }, { "answer_id": 85192, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>Arguments in RMI calls a serialised. Deserialisation on the server creates a copy of the lists. If the lists remained on the client side, then the number of network calls would be quite high. You can pass remote objects, but beware of the performance implications.</p>\n" }, { "answer_id": 86301, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 2, "selected": true, "text": "<p>As Tom mentions, you can pass remote objects. You'd have to create a class to hold your list that implements Remote. Anytime you pass something that implements Remote as an argument, whenever the receiving side uses it, it turns around and makes a remote call <em>back</em> to the caller to work with that object. </p>\n" }, { "answer_id": 86847, "author": "BCunningham", "author_id": 7689, "author_profile": "https://Stackoverflow.com/users/7689", "pm_score": 1, "selected": false, "text": "<p>As others have already mentioned, when passing objects as parameters to an RMI method, the object will get serialized, then deserialized on the other end inside the target object containing the RMI method. This breaks the reference from the original objects passed in, as you now have two distinct objects: one in the client code calling the method, and one on the remote side.</p>\n\n<p>In this specific example, a better approach would be to break up your method calls (since you appear to be doing two things in one method: getting customer names and getting customer numbers) and instead have your results returned to the caller rather than passing in a collection...like this:</p>\n\n<pre><code>public ArrayList&lt;String&gt; getCustomerNames() throws java.rmi.RemoteException;\n\npublic ArrayList&lt;String&gt; getCustomerNumbers() throws java.rmi.RemoteException;\n</code></pre>\n\n<p>Since both ArrayList and String implement Serializable, the results in the collection will be serialized and sent over the wire to the client code calling the method, at which point you can work with the data however you need. If instead you need to use a custom object in the collection, as long as your class implements the java.io.Serializable interface, and follows the specification for that interface you should have no problems.</p>\n\n<p>This would result in two separate calls over the wire, but is a much cleaner and simpler interaction, and avoids the reference breaking problem in your original example.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16345/" ]
I've got an RMI call defined as: ``` public void remoteGetCustomerNameNumbers(ArrayList<String> customerNumberList, ArrayList<String> customerNameList) throws java.rmi.RemoteException; ``` The function does a database lookup and populates the two ArrayLists. The calling function gets nothing. I believe this works with Vector types. Do I need to use the Vector, or is there a way to get this to work without making two calls. I've got some other ideas that I'd probably use, like returning a key/value pair, but I'd like to know if I can get this to work. Update: I would accept all of the answers given so far if I could. I hadn't known the network cost, so It makes sense to rework the function to return a LinkedHashMap instead of the two ArrayLists.
As Tom mentions, you can pass remote objects. You'd have to create a class to hold your list that implements Remote. Anytime you pass something that implements Remote as an argument, whenever the receiving side uses it, it turns around and makes a remote call *back* to the caller to work with that object.
85,091
<p>OK, this begins to drive me crazy. I have an asp.net webapp. Pretty straightforward, most of the code in the .aspx.vb, and a few classes in App_Code.</p> <p>The problem, which has begun to occur only today (even though most of the code was already written), is that once in a while, I have this error message :</p> <blockquote> <p>Error BC30002: Type ‘XXX’ is not defined</p> </blockquote> <p>The error occurs about every time I modify the files in the App_Code folder. EDIT : OK, this happens also if I don't touch anything for a while then refresh the page. I'm still trying to figure out exactly how to trigger this error.</p> <p>I just have to wait a little bit without touching anything, then refresh the page and it works, but it's very annoying.</p> <p>So I searched a little bit, but nothing came up except imports missing. Any idea ?</p>
[ { "answer_id": 85333, "author": "HaveThunk", "author_id": 14515, "author_profile": "https://Stackoverflow.com/users/14515", "pm_score": 3, "selected": false, "text": "<p>Sounds like a pre compile issue, particularly because you mention that you get the error and then wait and it disappears. ASP.NET may be still in the process of dynamically compiling your application or it has compiled the types into different assemblies.</p>\n\n<p>With dynamic compilation, you are not guaranteed to have different codebehind files compiled into the same assembly. So the type you are referencing may not be able to be resolved within its precompiled assembly.</p>\n\n<p>Try using the \"@Reference\" directive to indicate to the runtime that your page and the file that contains your type should be compiled into the same assembly. </p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/w70c655a(v=vs.100).aspx\" rel=\"nofollow noreferrer\">@ Reference - MSDN</a></p>\n" }, { "answer_id": 85431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Sounds like it happens every time the website spins up (the app gets recycled every time you touch app_code and probably you have IIS configured to shut down the website after X minutes of inactivity).</p>\n\n<p>I bet it has something to do with the asp.net worker process not having the correct access rights on the server. So its trying to load an assembly and is being denied. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa302435.aspx\" rel=\"nofollow noreferrer\">Check this link</a> and Table 19.3 for a list of all the folders the worker process account must have access to in order to function. And don't forget to give it rights to all files and folders in your virtual directory!</p>\n" }, { "answer_id": 156933, "author": "thomasb", "author_id": 6776, "author_profile": "https://Stackoverflow.com/users/6776", "pm_score": 4, "selected": true, "text": "<p>I think I found the problem.</p>\n\n<p>My code was like that :</p>\n\n<pre><code>Imports CMS\n\nSub Whatever()\n Dim a as new Arbo.MyObject() ' Arbo is a namespace inside CMS\n Dim b as new Util.MyOtherObject() ' Util is a namespace inside Util\nEnd Sub\n</code></pre>\n\n<p>I'm not sure why I wrote it like that, but it turns out the fact I was calling classes without either calling their whole namespace or importing their whole namespace was triggering the error.</p>\n\n<p>I rewrote it like this :</p>\n\n<pre><code>Imports CMS.Arbo\nImports CMS.Util \n\nSub Whatever()\n Dim a as new MyObject()\n Dim b as new MyOtherObject()\nEnd Sub\n</code></pre>\n\n<p>And now it works...</p>\n" }, { "answer_id": 48672096, "author": "Sjoerd Franken", "author_id": 9329584, "author_profile": "https://Stackoverflow.com/users/9329584", "pm_score": 3, "selected": false, "text": "<p>This happened to me after I added a new project to an old solution. I lowered the Target framework to match that of the other 'older' projects and the error went away.</p>\n" }, { "answer_id": 54686920, "author": "Wirah", "author_id": 482670, "author_profile": "https://Stackoverflow.com/users/482670", "pm_score": 0, "selected": false, "text": "<p>Replace your vbproj and vbproj.user file from your backup before if the references are equal</p>\n" }, { "answer_id": 66568997, "author": "tgolisch", "author_id": 283895, "author_profile": "https://Stackoverflow.com/users/283895", "pm_score": 2, "selected": false, "text": "<p>Check for a compiler warning (Output window of Visual Studio) &quot;warning : The following assembly has dependencies on a version of the .NET Framework that is higher than the target and might not load correctly during runtime causing a failure&quot;. This happens when one of your dlls is compiled with a newer version of dotnet. If your current project is set to use a lower version of dotnet, the dependency chain prevents the dll (with the higher dotnet ver) from loading. It gives a compile error in Visual Studio, but can still run in IIS.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6776/" ]
OK, this begins to drive me crazy. I have an asp.net webapp. Pretty straightforward, most of the code in the .aspx.vb, and a few classes in App\_Code. The problem, which has begun to occur only today (even though most of the code was already written), is that once in a while, I have this error message : > > Error BC30002: Type ‘XXX’ is not defined > > > The error occurs about every time I modify the files in the App\_Code folder. EDIT : OK, this happens also if I don't touch anything for a while then refresh the page. I'm still trying to figure out exactly how to trigger this error. I just have to wait a little bit without touching anything, then refresh the page and it works, but it's very annoying. So I searched a little bit, but nothing came up except imports missing. Any idea ?
I think I found the problem. My code was like that : ``` Imports CMS Sub Whatever() Dim a as new Arbo.MyObject() ' Arbo is a namespace inside CMS Dim b as new Util.MyOtherObject() ' Util is a namespace inside Util End Sub ``` I'm not sure why I wrote it like that, but it turns out the fact I was calling classes without either calling their whole namespace or importing their whole namespace was triggering the error. I rewrote it like this : ``` Imports CMS.Arbo Imports CMS.Util Sub Whatever() Dim a as new MyObject() Dim b as new MyOtherObject() End Sub ``` And now it works...
85,116
<p>I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.</p> <p>Bonus if I can output in the user's locale date format.</p>
[ { "answer_id": 85161, "author": "japollock", "author_id": 1210318, "author_profile": "https://Stackoverflow.com/users/1210318", "pm_score": -1, "selected": false, "text": "<p>Don't know how to do locale, but javascript is a client side technology.</p>\n\n<pre><code>usersLocalTime = new Date();\n</code></pre>\n\n<p>will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.</p>\n" }, { "answer_id": 85213, "author": "dave", "author_id": 14355, "author_profile": "https://Stackoverflow.com/users/14355", "pm_score": 2, "selected": false, "text": "<p>You could use the following, which reports the timezone offset from GMT in minutes: </p>\n\n<pre><code>new Date().getTimezoneOffset();\n</code></pre>\n\n<p>Note :\n - this function return a negative number.</p>\n" }, { "answer_id": 85235, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 5, "selected": false, "text": "<p>You can use <code>new Date().getTimezoneOffset()/60</code> for the timezone. There is also a <code>toLocaleString()</code> method for displaying a date using the user's locale.</p>\n\n<p>Here's the whole list: <a href=\"http://www.elated.com/articles/working-with-dates/\" rel=\"noreferrer\">Working with Dates</a></p>\n" }, { "answer_id": 85312, "author": "Aeon", "author_id": 13289, "author_profile": "https://Stackoverflow.com/users/13289", "pm_score": 1, "selected": false, "text": "<p>getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at <a href=\"https://github.com/mde/timezone-js\" rel=\"nofollow noreferrer\">mde's TimeZone.js</a>. </p>\n\n<p>There's a few more options discussed in the answer to <a href=\"https://stackoverflow.com/questions/15141762/how-to-initialize-javascript-date-to-a-particular-timezone/15171030#15171030\">this question</a></p>\n" }, { "answer_id": 85357, "author": "Mark", "author_id": 9303, "author_profile": "https://Stackoverflow.com/users/9303", "pm_score": 3, "selected": false, "text": "<p>Here's what I've used in past projects:</p>\n\n<pre><code>var myDate = new Date();\nvar tzo = (myDate.getTimezoneOffset()/60)*(-1);\n//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own\nmyDate = new Date.parseInvariant('&lt;%=DataCurrentDate%&gt;', 'yyyyMMdd hh:mm:ss');\nmyDate.setHours(myDate.getHours() + tzo);\n//here you would have to get a handle to your span / div to set. again, I'm using MS Ajax's $get\nvar dateSpn = $get('dataDate');\ndateSpn.innerHTML = myDate.localeFormat('F');\n</code></pre>\n" }, { "answer_id": 85793, "author": "Már Örlygsson", "author_id": 16271, "author_profile": "https://Stackoverflow.com/users/16271", "pm_score": 2, "selected": false, "text": "<p>The <code>.getTimezoneOffset()</code> method reports the time-zone offset in minutes, counting \"westwards\" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)</p>\n\n<p>To the get a normal time-zone offset in hours, you need to use:</p>\n\n<pre><code>var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60\n</code></pre>\n\n<p><strong>Important detail:</strong><br>\nNote that daylight savings time is factored into the result - so what this method gives you is really the <strong>time</strong> offset - not the actual geographic <strong>time-zone</strong> offset.</p>\n" }, { "answer_id": 86533, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 9, "selected": true, "text": "<p>Seems the most foolproof way to start with a UTC date is to create a new <code>Date</code> object and use the <code>setUTC…</code> methods to set it to the date/time you want.</p>\n\n<p>Then the various <code>toLocale…String</code> methods will provide localized output.</p>\n\n<h3>Example:</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// This would come from the server.\r\n// Also, this whole block could probably be made into an mktime function.\r\n// All very bare here for quick grasping.\r\nd = new Date();\r\nd.setUTCFullYear(2004);\r\nd.setUTCMonth(1);\r\nd.setUTCDate(29);\r\nd.setUTCHours(2);\r\nd.setUTCMinutes(45);\r\nd.setUTCSeconds(26);\r\n\r\nconsole.log(d); // -&gt; Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)\r\nconsole.log(d.toLocaleString()); // -&gt; Sat Feb 28 23:45:26 2004\r\nconsole.log(d.toLocaleDateString()); // -&gt; 02/28/2004\r\nconsole.log(d.toLocaleTimeString()); // -&gt; 23:45:26</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Some references:</h3>\n\n<ul>\n<li><a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleString\" rel=\"noreferrer\">toLocaleString</a></li>\n<li><a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleDateString\" rel=\"noreferrer\">toLocaleDateString</a></li>\n<li><a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleTimeString\" rel=\"noreferrer\">toLocaleTimeString</a></li>\n<li><a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTimezoneOffset\" rel=\"noreferrer\">getTimezoneOffset</a></li>\n</ul>\n" }, { "answer_id": 2830494, "author": "simianarmy", "author_id": 222367, "author_profile": "https://Stackoverflow.com/users/222367", "pm_score": 3, "selected": false, "text": "<p>Once you have your date object constructed, here's a snippet for the conversion:</p>\n\n<p>The function takes a UTC formatted Date object and format string.<br>\nYou will need a <code>Date.strftime</code> prototype.</p>\n\n<pre><code>function UTCToLocalTimeString(d, format) {\n if (timeOffsetInHours == null) {\n timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);\n }\n d.setHours(d.getHours() + timeOffsetInHours);\n\n return d.strftime(format);\n}\n</code></pre>\n" }, { "answer_id": 18852893, "author": "Daniel", "author_id": 200394, "author_profile": "https://Stackoverflow.com/users/200394", "pm_score": 2, "selected": false, "text": "<p>The best solution I've come across is to create [time display=\"llll\" datetime=\"UTC TIME\" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.</p>\n\n<p><a href=\"http://momentjs.com/\" rel=\"nofollow\">http://momentjs.com/</a> Moment.js </p>\n\n<p>will display the time nicely.</p>\n" }, { "answer_id": 23872920, "author": "theDmi", "author_id": 219187, "author_profile": "https://Stackoverflow.com/users/219187", "pm_score": 6, "selected": false, "text": "<h2>You can do it with <a href=\"http://momentjs.com/\" rel=\"nofollow noreferrer\">moment.js</a> (deprecated in 2021)</h2>\n<p>It's best to <a href=\"http://momentjs.com/docs/#/parsing/\" rel=\"nofollow noreferrer\">parse</a> your date string from UTC as follows (create an <a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO-8601</a> compatible string on the server to get consistent results across all browsers):</p>\n<pre><code>var m = moment(&quot;2013-02-08T09:30:26Z&quot;);\n</code></pre>\n<p>Now just use <code>m</code> in your application, moment.js defaults to the local timezone for display operations. There are <a href=\"http://momentjs.com/docs/#/displaying/\" rel=\"nofollow noreferrer\">many ways to format the date and time values</a> or extract portions of it.</p>\n<p>You can even format a moment object in the users locale like this:</p>\n<pre><code>m.format('LLL') // Returns &quot;February 8 2013 8:30 AM&quot; on en-us\n</code></pre>\n<p>To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the <a href=\"http://momentjs.com/timezone/\" rel=\"nofollow noreferrer\">moment.js timezone extension</a>. That page has also some examples, it's pretty simple to use.</p>\n<p>Note: Moment JS recommends more modern alternatives, so it is probably not a good choice for new projects.</p>\n" }, { "answer_id": 32781372, "author": "hriziya", "author_id": 1005741, "author_profile": "https://Stackoverflow.com/users/1005741", "pm_score": 2, "selected": false, "text": "<p>With date from PHP code I used something like this..</p>\n\n<pre><code>function getLocalDate(php_date) {\n var dt = new Date(php_date);\n var minutes = dt.getTimezoneOffset();\n dt = new Date(dt.getTime() + minutes*60000);\n return dt;\n}\n</code></pre>\n\n<p>We can call it like this</p>\n\n<pre><code>var localdateObj = getLocalDate('2015-09-25T02:57:46');\n</code></pre>\n" }, { "answer_id": 41000624, "author": "Anja", "author_id": 1544659, "author_profile": "https://Stackoverflow.com/users/1544659", "pm_score": 2, "selected": false, "text": "<p>I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.</p>\n\n<p>The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z</p>\n\n<p>Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see <a href=\"https://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference\">JavaScript for detecting browser language preference</a>), so I get the browser language from the server.</p>\n\n<p>Python/Django: send request browser language as context parameter:</p>\n\n<pre><code>language = request.META.get('HTTP_ACCEPT_LANGUAGE')\nreturn render(request, 'cssexy/index.html', { \"language\": language })\n</code></pre>\n\n<p>HTML: write it in a hidden input:</p>\n\n<pre><code>&lt;input type=\"hidden\" id=\"browserlanguage\" value={{ language }}/&gt;\n</code></pre>\n\n<p>JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression</p>\n\n<pre><code>const browserlanguage = document.getElementById(\"browserlanguage\").value;\nvar defaultlang = browserlanguage.replace(/(\\w{2}\\-\\w{2}),.*/, \"$1\");\n</code></pre>\n\n<p>JavaScript: convert to datetime and format it:</p>\n\n<pre><code>var options = { hour: \"2-digit\", minute: \"2-digit\" };\nvar dt = (new Date(str)).toLocaleDateString(defaultlang, options);\n</code></pre>\n\n<p>See: <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString</a></p>\n\n<p>The result is (browser language is en-gb): 05/12/2016, 14:58</p>\n" }, { "answer_id": 43863035, "author": "Jeremy Chone", "author_id": 686724, "author_profile": "https://Stackoverflow.com/users/686724", "pm_score": 4, "selected": false, "text": "<p>In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.</p>\n<p>Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.</p>\n<pre><code>var d = new Date(); \nd = new Date(d.getTime() - d.getTimezoneOffset() * 60000)\nvar yyyymmdd = t.toISOString().slice(0, 10); \n// 2017-05-09T08:24:26.581Z (but this is not UTC)\n</code></pre>\n<p>The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.</p>\n" }, { "answer_id": 51259500, "author": "Codemaker", "author_id": 7103882, "author_profile": "https://Stackoverflow.com/users/7103882", "pm_score": 0, "selected": false, "text": "<p>To convert date to local date use toLocaleDateString() method.</p>\n\n<pre><code>var date = (new Date(str)).toLocaleDateString(defaultlang, options);\n</code></pre>\n\n<p>To convert time to local time use toLocaleTimeString() method.</p>\n\n<pre><code>var time = (new Date(str)).toLocaleTimeString(defaultlang, options);\n</code></pre>\n" }, { "answer_id": 54813917, "author": "Serg", "author_id": 1844247, "author_profile": "https://Stackoverflow.com/users/1844247", "pm_score": 3, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])\r\nvar serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server\r\nvar serverDateStr = serverDate.toLocaleString(\"en-US\", {\r\n year: 'numeric',\r\n month: 'numeric',\r\n day: 'numeric',\r\n hour: 'numeric',\r\n minute: 'numeric',\r\n second: 'numeric'\r\n})\r\nvar userDate = new Date(serverDateStr + \" UTC\");\r\nvar locale = window.navigator.userLanguage || window.navigator.language;\r\n\r\nvar clientDateStr = userDate.toLocaleString(locale, {\r\n year: 'numeric',\r\n month: 'numeric',\r\n day: 'numeric'\r\n});\r\n\r\nvar clientDateTimeStr = userDate.toLocaleString(locale, {\r\n year: 'numeric',\r\n month: 'numeric',\r\n day: 'numeric',\r\n hour: 'numeric',\r\n minute: 'numeric',\r\n second: 'numeric'\r\n});\r\n\r\nconsole.log(\"Server UTC date: \" + serverDateStr);\r\nconsole.log(\"User's local date: \" + clientDateStr);\r\nconsole.log(\"User's local date&amp;time: \" + clientDateTimeStr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 67201763, "author": "Flavien Volken", "author_id": 532695, "author_profile": "https://Stackoverflow.com/users/532695", "pm_score": 3, "selected": false, "text": "<p><strong>2021 - you can use the browser native</strong> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat\" rel=\"noreferrer\">Intl.DateTimeFormat</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>const utcDate = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));\nconsole.log(new Intl.DateTimeFormat().format(utcDate));\n// expected output: &quot;21/04/2021&quot;, my locale is Switzerland\n</code></pre>\n<p>Below is straight from the documentation:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));\n// Results below assume UTC timezone - your results may vary\n\n// Specify default date formatting for language (locale)\nconsole.log(new Intl.DateTimeFormat('en-US').format(date));\n// expected output: &quot;12/20/2020&quot;\n \n// Specify default date formatting for language with a fallback language (in this case Indonesian)\nconsole.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));\n// expected output: &quot;20/12/2020&quot;\n \n// Specify date and time format using &quot;style&quot; options (i.e. full, long, medium, short)\nconsole.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date));\n// Expected output &quot;Sunday, 20 December 2020 at 14:23:16 GMT+11&quot;\n</code></pre>\n" }, { "answer_id": 71803712, "author": "Hans Bouwmeester", "author_id": 8005373, "author_profile": "https://Stackoverflow.com/users/8005373", "pm_score": 0, "selected": false, "text": "<p>A very old question but perhaps this helps someone stumbling into this.\nBelow code formats an ISO8601 date string in a human-friendly format corresponding the user's time-zone and locale. Adapt as needed. For example: for your app, are the hours, minutes, seconds even significant to display to the user for dates more than 1 days, 1 week, 1 month, 1 year or whatever old?</p>\n<p>Also depending on your application's implementation, don't forget to re-render periodically.\n(In my code below at least every 24hours).</p>\n<pre><code>export const humanFriendlyDateStr = (iso8601) =&gt; {\n\n // Examples (using Node.js):\n\n // Get an ISO8601 date string using Date()\n // &gt; new Date()\n // 2022-04-08T22:05:18.595Z\n\n // If it was earlier today, just show the time:\n // &gt; humanFriendlyDateStr('2022-04-08T22:05:18.595Z')\n // '3:05 PM'\n\n // If it was during the past week, add the day:\n // &gt; humanFriendlyDateStr('2022-04-07T22:05:18.595Z')\n // 'Thu 3:05 PM'\n\n // If it was more than a week ago, add the date\n // &gt; humanFriendlyDateStr('2022-03-07T22:05:18.595Z')\n // '3/7, 2:05 PM'\n\n // If it was more than a year ago add the year\n // &gt; humanFriendlyDateStr('2021-03-07T22:05:18.595Z')\n // '3/7/2021, 2:05 PM'\n\n // If it's sometime in the future return the full date+time:\n // &gt; humanFriendlyDateStr('2023-03-07T22:05:18.595Z')\n // '3/7/2023, 2:05 PM'\n\n const datetime = new Date(Date.parse(iso8601))\n const now = new Date()\n const ageInDays = (now - datetime) / 86400000\n let str\n\n // more than 1 year old?\n if (ageInDays &gt; 365) {\n str = datetime.toLocaleDateString([], {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n })\n // more than 1 week old?\n } else if (ageInDays &gt; 7) {\n str = datetime.toLocaleDateString([], {\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n })\n // more than 1 day old?\n } else if (ageInDays &gt; 1) {\n str = datetime.toLocaleDateString([], {\n weekday: 'short',\n hour: 'numeric',\n minute: 'numeric',\n })\n // some time today?\n } else if (ageInDays &gt; 0) {\n str = datetime.toLocaleTimeString([], {\n timeStyle: 'short',\n })\n // in the future?\n } else {\n str = datetime.toLocaleDateString([], {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n })\n }\n return str\n}\n</code></pre>\n<p>Inspired from: <a href=\"https://alexwlchan.net/2020/05/human-friendly-dates-in-javascript/\" rel=\"nofollow noreferrer\">https://alexwlchan.net/2020/05/human-friendly-dates-in-javascript/</a></p>\n<p>Tested using Node.js</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone. Bonus if I can output in the user's locale date format.
Seems the most foolproof way to start with a UTC date is to create a new `Date` object and use the `setUTC…` methods to set it to the date/time you want. Then the various `toLocale…String` methods will provide localized output. ### Example: ```js // This would come from the server. // Also, this whole block could probably be made into an mktime function. // All very bare here for quick grasping. d = new Date(); d.setUTCFullYear(2004); d.setUTCMonth(1); d.setUTCDate(29); d.setUTCHours(2); d.setUTCMinutes(45); d.setUTCSeconds(26); console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT) console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004 console.log(d.toLocaleDateString()); // -> 02/28/2004 console.log(d.toLocaleTimeString()); // -> 23:45:26 ``` ### Some references: * [toLocaleString](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleString) * [toLocaleDateString](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleDateString) * [toLocaleTimeString](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleTimeString) * [getTimezoneOffset](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/getTimezoneOffset)
85,119
<p>I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish <code>if</code> and <code>elif</code> statements for every site as shown in the following code, which I would like to avoid.</p> <pre class="lang-py prettyprint-override"><code>if site == 'site1': ... elif site == 'site2: ... </code></pre> <p>What are some good and clever ways of running multiple sites from a single, common Python web framework (i.e., Pylons, TurboGears, etc)?</p>
[ { "answer_id": 85134, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 5, "selected": true, "text": "<p>Django has this built in. See <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites\" rel=\"noreferrer\">the sites framework</a>.</p>\n\n<p>As a general technique, include a 'host' column in your database schema attached to the data you want to be host-specific, then include the <code>Host</code> HTTP header in the query when you are retrieving data.</p>\n" }, { "answer_id": 85271, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "<p>I use CherryPy as my web server (which comes bundled with Turbogears), and I simply run multiple instances of the CherryPy web server on different ports bound to localhost. Then I configure Apache with mod_proxy and mod_rewrite to transparently forward requests to the proper port based on the HTTP request.</p>\n" }, { "answer_id": 86003, "author": "defnull", "author_id": 407880, "author_profile": "https://Stackoverflow.com/users/407880", "pm_score": 2, "selected": false, "text": "<p>Using multiple server instances on local ports is a good idea, but you don't need a full featured web server to redirect HTTP requests. </p>\n\n<p>I would use <a href=\"http://www.apsis.ch/pound/\" rel=\"nofollow noreferrer\">pound</a> as a reverse proxy to do the job. It is small, fast, simple and does exactly what we need here.</p>\n\n<blockquote>\n <p>WHAT POUND IS:</p>\n \n <ol>\n <li><strong>a reverse-proxy: it passes requests from client browsers to one or more back-end servers.</strong></li>\n <li>a load balancer: it will distribute the requests from the client browsers among several back-end servers, while keeping session information.</li>\n <li>an SSL wrapper: Pound will decrypt HTTPS requests from client browsers and pass them as plain HTTP to the back-end servers.</li>\n <li>an HTTP/HTTPS sanitizer: Pound will verify requests for correctness and accept only well-formed ones.</li>\n <li>a fail over-server: should a back-end server fail, Pound will take note of the fact and stop passing requests to it until it recovers.</li>\n <li><strong>a request redirector: requests may be distributed among servers according to the requested URL.</strong></li>\n </ol>\n</blockquote>\n" }, { "answer_id": 86705, "author": "Gabriel Ross", "author_id": 10751, "author_profile": "https://Stackoverflow.com/users/10751", "pm_score": 3, "selected": false, "text": "<p>Using Django on apache with mod_python, I host multiple (unrelated) django sites simply with the following apache config:</p>\n\n<pre><code>&lt;VirtualHost 1.2.3.4&gt;\n DocumentRoot /www/site1\n ServerName site1.com\n &lt;Location /&gt;\n SetHandler python-program\n SetEnv DJANGO_SETTINGS_MODULE site1.settings\n PythonPath \"['/www'] + sys.path\"\n PythonDebug On\n PythonInterpreter site1\n &lt;/Location&gt;\n&lt;/VirtualHost&gt;\n\n&lt;VirtualHost 1.2.3.4&gt;\n DocumentRoot /www/site2\n ServerName site2.com\n &lt;Location /&gt;\n SetHandler python-program\n SetEnv DJANGO_SETTINGS_MODULE site2.settings\n PythonPath \"['/www'] + sys.path\"\n PythonDebug On\n PythonInterpreter site2\n &lt;/Location&gt;\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>No need for multiple apache instances or proxy servers. Using a different PythonInterpreter directive for each site (the name you enter is arbitrary) keeps the namespaces separate.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4919/" ]
I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish `if` and `elif` statements for every site as shown in the following code, which I would like to avoid. ```py if site == 'site1': ... elif site == 'site2: ... ``` What are some good and clever ways of running multiple sites from a single, common Python web framework (i.e., Pylons, TurboGears, etc)?
Django has this built in. See [the sites framework](http://docs.djangoproject.com/en/dev/ref/contrib/sites/#ref-contrib-sites). As a general technique, include a 'host' column in your database schema attached to the data you want to be host-specific, then include the `Host` HTTP header in the query when you are retrieving data.
85,122
<p>On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only <em>Sleep</em> with millisecond granularity. </p> <p>On Unix, I can use the use the <code>select</code> system call to create a microsecond sleep which is pretty straightforward:</p> <pre><code>int usleep(long usec) { struct timeval tv; tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, 0, &amp;tv); } </code></pre> <p>How can I achieve the same on Windows?</p>
[ { "answer_id": 85143, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": -1, "selected": true, "text": "<p>On Windows the use of <code>select</code> forces you to include the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Winsock</a> library which has to be initialized like this in your application:</p>\n\n<pre><code>WORD wVersionRequested = MAKEWORD(1,0);\nWSADATA wsaData;\nWSAStartup(wVersionRequested, &amp;wsaData);\n</code></pre>\n\n<p>And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method:</p>\n\n<pre><code>int usleep(long usec)\n{\n struct timeval tv;\n fd_set dummy;\n SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);\n FD_ZERO(&amp;dummy);\n FD_SET(s, &amp;dummy);\n tv.tv_sec = usec/1000000L;\n tv.tv_usec = usec%1000000L;\n return select(0, 0, 0, &amp;dummy, &amp;tv);\n}\n</code></pre>\n\n<p>All these created usleep methods return zero when successful and non-zero for errors.</p>\n" }, { "answer_id": 85149, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": false, "text": "<p>This indicates a mis-understanding of sleep functions. The parameter you pass is a <em>minimum</em> time for sleeping. There's no guarantee that the thread will wake up after exactly the time specified. In fact, threads don't \"wake up\" at all, but are rather chosen for execution by the OS scheduler. The scheduler might choose to wait much longer than the requested sleep duration to activate a thread, especially if another thread is still active at that moment.</p>\n" }, { "answer_id": 85200, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 6, "selected": false, "text": "<p>As Joel says, you can't meaningfully 'sleep' (i.e. relinquish your scheduled CPU) for such short periods. If you want to delay for some short time, then you need to spin, repeatedly checking a suitably high-resolution timer (e.g. the 'performance timer') and hoping that something of high priority doesn't pre-empt you anyway.</p>\n\n<p>If you really care about accurate delays of such short times, you should not be using Windows.</p>\n" }, { "answer_id": 85201, "author": "Joe Schneider", "author_id": 1541, "author_profile": "https://Stackoverflow.com/users/1541", "pm_score": 5, "selected": false, "text": "<p>Use the high resolution multimedia timers available in winmm.lib. See <a href=\"http://www.codeguru.com/cpp/w-p/system/timers/article.php/c5759/\" rel=\"noreferrer\">this</a> for an example.</p>\n" }, { "answer_id": 85217, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>What are you waiting for that requires such precision? In general if you <strong>need</strong> to specify that level of precision (e.g. because of a dependency on some external hardware) you are on the wrong platform and should look at a real time OS.</p>\n\n<p>Otherwise you should be considering if there is an event you can synchronize on, or in the worse case just busy wait the CPU and use the high performance counter API to measure the elapsed time.</p>\n" }, { "answer_id": 85234, "author": "darron", "author_id": 15896, "author_profile": "https://Stackoverflow.com/users/15896", "pm_score": 3, "selected": false, "text": "<p>Yes, you need to understand your OS' time quantums. On Windows, you won't even be getting 1ms resolution times unless you change the time quantum to 1ms. (Using for example timeBeginPeriod()/timeEndPeriod()) That still won't really guarantee anything. Even a little load or a single crappy device driver will throw everything off.</p>\n\n<p>SetThreadPriority() helps, but is quite dangerous. Bad device drivers can still ruin you.</p>\n\n<p>You need an ultra-controlled computing environment to make this ugly stuff work at all.</p>\n" }, { "answer_id": 85365, "author": "theschmitzer", "author_id": 2167252, "author_profile": "https://Stackoverflow.com/users/2167252", "pm_score": 0, "selected": false, "text": "<p>Try boost::xtime and a timed_wait()</p>\n\n<p>has nanosecond accuracy.</p>\n" }, { "answer_id": 85927, "author": "mbyrne215", "author_id": 5241, "author_profile": "https://Stackoverflow.com/users/5241", "pm_score": 3, "selected": false, "text": "<p>As several people have pointed out, sleep and other related functions are by default dependent on the \"system tick\". This is the minimum unit of time between OS tasks; the scheduler, for instance, will not run faster than this. Even with a realtime OS, the system tick is not usually less than 1 ms. While it is tunable, this has implications for the entire system, not just your sleep functionality, because your scheduler will be running more frequently, and potentially increasing the overhead of your OS (amount of time for the scheduler to run, vs. amount of time a task can run).</p>\n\n<p>The solution to this is to use an external, high-speed clock device. Most Unix systems will allow you to specify to your timers and such a different clock to use, as opposed to the default system clock.</p>\n" }, { "answer_id": 85929, "author": "user16523", "author_id": 16523, "author_profile": "https://Stackoverflow.com/users/16523", "pm_score": 3, "selected": false, "text": "<p>If you want so much granularity you are in the wrong place (in user space). </p>\n\n<p>Remember that if you are in user space your time is not always precise. </p>\n\n<p>The scheduler can start your thread (or app), and schedule it, so you are depending by the OS scheduler. </p>\n\n<p>If you are looking for something precise you have to go:\n1) In kernel space (like drivers)\n2) Choose an RTOS.</p>\n\n<p>Anyway if you are looking for some granularity (but remember the problem with user space ) look to\nQueryPerformanceCounter Function and QueryPerformanceFrequency function in MSDN.</p>\n" }, { "answer_id": 91058, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>Just use Sleep(0). 0 is clearly less than a millisecond. Now, that sounds funny, but I'm serious. Sleep(0) tells Windows that you don't have anything to do right now, but that you do want to be reconsidered as soon as the scheduler runs again. And since obviously the thread can't be scheduled to run before the scheduler itself runs, this is the shortest delay possible.</p>\n\n<p>Note that you can pass in a microsecond number to your usleep, but so does void usleep(__int64 t) { Sleep(t/1000); } - no guarantees to actually sleeping that period.</p>\n" }, { "answer_id": 860113, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I have the same problem and nothing seems to be faster than a ms, even the Sleep(0). My problem is the communication between a client and a server application where I use the _InterlockedExchange function to test and set a bit and then I Sleep(0).</p>\n\n<p>I really need to perform thousands of operations per second this way and it doesn't work as fast as I planned.</p>\n\n<p>Since I have a thin client dealing with the user, which in turn invokes an agent which then talks to a thread, I will move soon to merge the thread with the agent so that no event interface will be required.</p>\n\n<p>Just to give you guys an idea how slow this Sleep is, I ran a test for 10 seconds performing an empty loop (getting something like 18,000,000 loops) whereas with the event in place I only got 180,000 loops. That is, 100 times slower!</p>\n" }, { "answer_id": 1448900, "author": "Hendrik", "author_id": 123411, "author_profile": "https://Stackoverflow.com/users/123411", "pm_score": 2, "selected": false, "text": "<p>Actually using this usleep function will cause a big memory/resource leak. (depending how often called)</p>\n\n<p>use this corrected version (sorry can't edit?)</p>\n\n<pre><code>bool usleep(unsigned long usec)\n{\n struct timeval tv;\n fd_set dummy;\n SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);\n FD_ZERO(&amp;dummy);\n FD_SET(s, &amp;dummy);\n tv.tv_sec = usec / 1000000ul;\n tv.tv_usec = usec % 1000000ul;\n bool success = (0 == select(0, 0, 0, &amp;dummy, &amp;tv));\n closesocket(s);\n return success;\n}\n</code></pre>\n" }, { "answer_id": 10554704, "author": "Lightness1024", "author_id": 489858, "author_profile": "https://Stackoverflow.com/users/489858", "pm_score": 1, "selected": false, "text": "<p>Like everybody mentioned, there is indeed no guarantees about the sleep time.\nBut nobody wants to admit that sometimes, on an idle system, the usleep command can be very precise. Especially with a tickless kernel. Windows&nbsp;Vista has it and Linux has it since 2.6.16.</p>\n\n<p>Tickless kernels exists to help improve laptops batterly life: c.f. Intel's powertop utility.</p>\n\n<p>In that condition, I happend to have measured the Linux usleep command that respected the requested sleep time very closely, down to half a dozen of micro seconds.</p>\n\n<p>So, maybe the OP wants something that will roughly work most of the time on an idling system, and be able to ask for micro second scheduling!\nI actually would want that on Windows too.</p>\n\n<p>Also Sleep(0) sounds like boost::thread::yield(), which terminology is clearer.</p>\n\n<p>I wonder if <a href=\"http://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29\" rel=\"nofollow\">Boost</a>-timed locks have a better precision. Because then you could just lock on a mutex that nobody ever releases, and when the timeout is reached, continue on...\nTimeouts are set with boost::system_time + boost::milliseconds &amp; cie (xtime is deprecated).</p>\n" }, { "answer_id": 11456112, "author": "Arno", "author_id": 1504523, "author_profile": "https://Stackoverflow.com/users/1504523", "pm_score": 3, "selected": false, "text": "<p>Generally a sleep will last at least until the next system interrupt occurs. However, this\ndepends on settings of the multimedia timer resources. It may be set to something close to \n1 ms, some hardware even allows to run at interrupt periods of 0.9765625 (<em>ActualResolution</em> provided by <code>NtQueryTimerResolution</code> will show 0.9766 but that's actually wrong. They just can't put the correct number into the <em>ActualResolution</em> format. It's 0.9765625ms at 1024 interrupts per second).</p>\n\n<p>There is one exception wich allows us to escape from the fact that it may be impossible to sleep for less than the interrupt period: It is the famous <code>Sleep(0)</code>. This is a very powerful\ntool and it is not used as often as it should! It relinquishes the reminder of the thread's time slice. This way the thread will stop until the scheduler forces the thread to get cpu service again. <code>Sleep(0)</code> is an asynchronous service, the call will force the scheduler to react independent of an interrupt.</p>\n\n<p>A second way is the use of a <code>waitable object</code>. A wait function like <code>WaitForSingleObject()</code> can wait for an event. In order to have a thread sleeping for any time, also times in the microsecond regime, the thread needs to setup some service thread which will generate an event at the desired delay. The \"sleeping\" thread will setup this thread and then pause at the wait function until the service thread will set the event signaled.</p>\n\n<p>This way any thread can \"sleep\" or wait for any time. The service thread can be of big complexity and it may offer system wide services like timed events at microsecond resolution. However, microsecond resolution may force the service thread to spin on a high resolution time service for at most one interrupt period (~1ms). If care is taken, this can\nrun very well, particulary on multi-processor or multi-core systems. A one ms spin does not hurt considerably on multi-core system, when the affinity mask for the calling thread and the service thread are carefully handled.</p>\n\n<p>Code, description, and testing can be visited at the <a href=\"http://www.windowstimestamp.com\" rel=\"noreferrer\">Windows Timestamp Project</a></p>\n" }, { "answer_id": 31200345, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 2, "selected": false, "text": "<p>Try using <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms686289(v=vs.85).aspx\" rel=\"nofollow\">SetWaitableTimer</a>...</p>\n" }, { "answer_id": 31411628, "author": "Oskar Dahlberg", "author_id": 4858189, "author_profile": "https://Stackoverflow.com/users/4858189", "pm_score": 5, "selected": false, "text": "<pre><code>#include &lt;Windows.h&gt;\n\nstatic NTSTATUS(__stdcall *NtDelayExecution)(BOOL Alertable, PLARGE_INTEGER DelayInterval) = (NTSTATUS(__stdcall*)(BOOL, PLARGE_INTEGER)) GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"NtDelayExecution\");\nstatic NTSTATUS(__stdcall *ZwSetTimerResolution)(IN ULONG RequestedResolution, IN BOOLEAN Set, OUT PULONG ActualResolution) = (NTSTATUS(__stdcall*)(ULONG, BOOLEAN, PULONG)) GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"ZwSetTimerResolution\");\n\nstatic void SleepShort(float milliseconds) {\n static bool once = true;\n if (once) {\n ULONG actualResolution;\n ZwSetTimerResolution(1, true, &amp;actualResolution);\n once = false;\n }\n\n LARGE_INTEGER interval;\n interval.QuadPart = -1 * (int)(milliseconds * 10000.0f);\n NtDelayExecution(false, &amp;interval);\n}\n</code></pre>\n\n<p>Works very well for sleeping extremely short times. Remember though that at a certain point the actual delays will never be consistent because the system can't maintain consistent delays of such a short time.</p>\n" }, { "answer_id": 33448417, "author": "rauprog", "author_id": 4798975, "author_profile": "https://Stackoverflow.com/users/4798975", "pm_score": 0, "selected": false, "text": "<p><strong>Sleep function that is way less than a millisecond-maybe</strong></p>\n\n<p>I found that sleep(0) worked for me. On a system with a near 0% load on the cpu in task manager, I wrote a simple console program and the sleep(0) function slept for a consistent 1-3 microseconds, which is way less than a millisecond.</p>\n\n<p>But from the above answers in this thread, I know that the amount sleep(0) sleeps can vary much more wildly than this on systems with a large cpu load.</p>\n\n<p>But as I understand it, the sleep function should not be used as a timer. It should be used to make the program use the least percentage of the cpu as possible and execute as frequently as possible. For my purposes, such as moving a projectile across the screen in a videogame much faster than one pixel a millisecond, sleep(0) works, I think.</p>\n\n<p>You would just make sure the sleep interval is way smaller than the largest amount of time it would sleep. You don't use the sleep as a timer but just to make the game use the minimum amount of cpu percentage possible. You would use a separate function that has nothing to do is sleep to get to know when a particular amount of time has passed and then move the projectile one pixel across the screen-at a time of say 1/10th of a millisecond or 100 microseconds.</p>\n\n<p>The pseudo-code would go something like this.</p>\n\n<pre><code>while (timer1 &lt; 100 microseconds) {\nsleep(0);\n}\n\nif (timer2 &gt;=100 microseconds) {\nmove projectile one pixel\n}\n\n//Rest of code in iteration here\n</code></pre>\n\n<p>I know the answer may not work for advanced issues or programs but may work for some or many programs. </p>\n" }, { "answer_id": 43564734, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 1, "selected": false, "text": "<p>If your goal is to <em>\"wait for a very short amount of time\"</em> because you are doing a <em>spinwait</em>, then there are increasing levels of waiting you can perform.</p>\n\n<pre><code>void SpinOnce(ref Int32 spin)\n{\n /*\n SpinOnce is called each time we need to wait. \n But the action it takes depends on how many times we've been spinning:\n\n 1..12 spins: spin 2..4096 cycles\n 12..32: call SwitchToThread (allow another thread ready to go on time core to execute)\n over 32 spins: Sleep(0) (give up the remainder of our timeslice to any other thread ready to run, also allows APC and I/O callbacks)\n */\n spin += 1;\n\n if (spin &gt; 32)\n Sleep(0); //give up the remainder of our timeslice\n else if (spin &gt; 12)\n SwitchTothread(); //allow another thread on our CPU to have the remainder of our timeslice\n else\n {\n int loops = (1 &lt;&lt; spin); //1..12 ==&gt; 2..4096\n while (loops &gt; 0)\n loops -= 1;\n }\n}\n</code></pre>\n\n<p>So if your goal is actually to wait <em>only for a little bit</em>, you can use something like:</p>\n\n<pre><code>int spin = 0;\nwhile (!TryAcquireLock()) \n{ \n SpinOne(ref spin);\n}\n</code></pre>\n\n<p>The virtue here is that we wait longer each time, eventually going completely to sleep. </p>\n" }, { "answer_id": 72823146, "author": "sir-pinecone", "author_id": 134027, "author_profile": "https://Stackoverflow.com/users/134027", "pm_score": 0, "selected": false, "text": "<p>If the machine is running Windows 10 version 1803 or later then you can use <code>CreateWaitableTimerExW</code> with the <code>CREATE_WAITABLE_TIMER_HIGH_RESOLUTION</code> flag.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only *Sleep* with millisecond granularity. On Unix, I can use the use the `select` system call to create a microsecond sleep which is pretty straightforward: ``` int usleep(long usec) { struct timeval tv; tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, 0, &tv); } ``` How can I achieve the same on Windows?
On Windows the use of `select` forces you to include the [Winsock](https://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx) library which has to be initialized like this in your application: ``` WORD wVersionRequested = MAKEWORD(1,0); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); ``` And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method: ``` int usleep(long usec) { struct timeval tv; fd_set dummy; SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); FD_ZERO(&dummy); FD_SET(s, &dummy); tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, &dummy, &tv); } ``` All these created usleep methods return zero when successful and non-zero for errors.
85,137
<p>Say I have a class named Frog, it looks like:</p> <pre><code>public class Frog { public int Location { get; set; } public int JumpCount { get; set; } public void OnJump() { JumpCount++; } } </code></pre> <p>I need help with 2 things:</p> <ol> <li>I want to create an event named Jump in the class definition.</li> <li>I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.</li> </ol>
[ { "answer_id": 85188, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 7, "selected": true, "text": "<pre><code>public event EventHandler Jump;\npublic void OnJump()\n{\n EventHandler handler = Jump;\n if (null != handler) handler(this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>then</p>\n\n<pre><code>Frog frog = new Frog();\nfrog.Jump += new EventHandler(yourMethod);\n\nprivate void yourMethod(object s, EventArgs e)\n{\n Console.WriteLine(\"Frog has Jumped!\");\n}\n</code></pre>\n" }, { "answer_id": 54242833, "author": "Tezra", "author_id": 6893866, "author_profile": "https://Stackoverflow.com/users/6893866", "pm_score": 3, "selected": false, "text": "<p>Here is a sample of how to use a normal EventHandler, or a custom delegate. Note that <code>?.</code> is used instead of <code>.</code> to insure that if the event is null, it will fail cleanly (return null)</p>\n\n<pre><code>public delegate void MyAwesomeEventHandler(int rawr);\npublic event MyAwesomeEventHandler AwesomeJump;\n\npublic event EventHandler Jump;\n\npublic void OnJump()\n{\n AwesomeJump?.Invoke(42);\n Jump?.Invoke(this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>Note that the event itself is only null if there are no subscribers, and that once invoked, the event is thread safe. So you can also assign a default empty handler to insure the event is not null. Note that this is technically vulnerable to someone else wiping out all of the events (using GetInvocationList), so use with caution.</p>\n\n<pre><code>public event EventHandler Jump = delegate { };\n\npublic void OnJump()\n{\n Jump(this, EventArgs.Empty);\n}\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
Say I have a class named Frog, it looks like: ``` public class Frog { public int Location { get; set; } public int JumpCount { get; set; } public void OnJump() { JumpCount++; } } ``` I need help with 2 things: 1. I want to create an event named Jump in the class definition. 2. I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.
``` public event EventHandler Jump; public void OnJump() { EventHandler handler = Jump; if (null != handler) handler(this, EventArgs.Empty); } ``` then ``` Frog frog = new Frog(); frog.Jump += new EventHandler(yourMethod); private void yourMethod(object s, EventArgs e) { Console.WriteLine("Frog has Jumped!"); } ```
85,159
<p>Is there any way to parse a string in the format HH:MM into a Date (or other) object using the standard libraries?</p> <p>I know that I can parse something like "9/17/2008 10:30" into a Date object using</p> <pre><code>var date:Date = new Date(Date.parse("9/17/2008 10:30"); </code></pre> <p>But I want to parse just 10:30 by itself. The following code will not work.</p> <pre><code>var date:Date = new Date(Date.parse("10:30"); </code></pre> <p>I know I can use a custom RegEx to do this fairly easily, but it seems like this should be possible using the existing Flex API.</p>
[ { "answer_id": 85174, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 1, "selected": false, "text": "<p>Have you considered prepending \"01/01/2000 \" to the time string and then applying Date?</p>\n\n<p>Alternately there's probably a tokenizer that will take the input and split it up at the : giving you an array of strings you can convert to integers. A tokenizer isn't hard to write, either, and can be fun if one doesn't exist in flex.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 87125, "author": "mikechambers", "author_id": 10232, "author_profile": "https://Stackoverflow.com/users/10232", "pm_score": 2, "selected": false, "text": "<p>If you have to use the exact format you specified, then you need to parse it yourself.</p>\n\n<p>Here is a simple example (not tested):</p>\n\n<pre><code>var str:String = \"9/17/2008 10:30\"\n\nvar items:Array = str.split(\" \");\nvar dateElements:Array = items[0].split(\"/\");\nvar timeElements:Array = items[1].split(\":\");\n\nvar n:Date = new Date(dateElements[2],\n dateElements[0],\n dateElements[1].\n timeElements[0],\n timeElements[1]);\n</code></pre>\n\n<p>If the time is not expressed in 24 clock, then there is no way to check for AM or PM (code will assume AM).</p>\n" }, { "answer_id": 91775, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 1, "selected": true, "text": "<p>To answer your specific question: no, there's no library function to do what you want to do, but then there's no library function for parsing dates on the ISO format, on the German format, on the Swedish format, dates where the years are in roman numerals etc.</p>\n\n<p>Why not use regular expressions? That's what they are for.</p>\n" }, { "answer_id": 100684, "author": "Cosma Colanicchia", "author_id": 11867, "author_profile": "https://Stackoverflow.com/users/11867", "pm_score": 2, "selected": false, "text": "<p>As a simple and free solution, you could use some static methods of the DateField:</p>\n\n<ul>\n<li>DateField.stringToDate(valueString:String, inputFormat:String):Date</li>\n<li>DateField.dateToString(value:Date, outputFattern:String):String</li>\n</ul>\n\n<p>But unfortunately they don't support hours/minutes/seconds (just the date).</p>\n\n<p>In your specific case: the Date object always contains also a \"date\" information.. if it isn't important, couldn't you simply concatenate a standard date string before parsing?</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
Is there any way to parse a string in the format HH:MM into a Date (or other) object using the standard libraries? I know that I can parse something like "9/17/2008 10:30" into a Date object using ``` var date:Date = new Date(Date.parse("9/17/2008 10:30"); ``` But I want to parse just 10:30 by itself. The following code will not work. ``` var date:Date = new Date(Date.parse("10:30"); ``` I know I can use a custom RegEx to do this fairly easily, but it seems like this should be possible using the existing Flex API.
To answer your specific question: no, there's no library function to do what you want to do, but then there's no library function for parsing dates on the ISO format, on the German format, on the Swedish format, dates where the years are in roman numerals etc. Why not use regular expressions? That's what they are for.
85,179
<p>I've long been a fan of Stored Procedure Keyboard Accelerators, as described in <a href="http://blogs.msdn.com/irenak/archive/2006/10/27/sysk-228-get-table-columns-or-rows-with-single-key-press.aspx" rel="nofollow noreferrer">this article</a>. When we moved from SQL 2000 to 2005, though, and from Query Analyzer to Management Studio, the handling of the arguments changed. In QA, comma-separated arguments were automatically read as two separate arguments. In SSMS -- at least for me -- it's being read as one argument, with commas in it. Similarly, if I pass in a single argument with single quotes in it, I get a syntax error, <em>unless I escape the quotes</em> (' -> ''). In the article linked above, the author implies that this should not be the case for SSMS, but even with her exact example, comma-separated arguments are still being interpreted as one argument on every SSMS installation I've tried it on (3 of them), running against every SQL Server installation I've tried (4 of them).</p> <p>E.g., typing the following into SSMS, </p> <pre><code>Person,4 </code></pre> <p>then selecting it and running the shortcut, I get the error message "Invalid object name 'Person,4'.</p> <p>Does anybody have any idea how to fix this? Does anybody even use these shortcuts? I've Googled this problem several times over the past two years, and have had no luck.</p> <p>Edit: May be an issue with a specific build of SSMS. I have a follow-up post below.</p>
[ { "answer_id": 85976, "author": "Tim Lentine", "author_id": 2833, "author_profile": "https://Stackoverflow.com/users/2833", "pm_score": 1, "selected": false, "text": "<p>I had never tried this until I read your question and then read the article you referenced, so take this with a grain of salt. </p>\n\n<p>That said, I am able to get the process to work on my computer using SSMS, and I am also able to duplicate the error you described. </p>\n\n<p>To get this to work as expected I created the sproc in the master database, assigned the keyboard shortcut and restarted SSMS. I then typed the databasename.schema_name.table_name in single quotes followed by a comma and then an integer value (the sproc I tested was the GetRows sample in the article). I was still connected to the master database.</p>\n\n<p>This worked without incident.</p>\n\n<p>To get the same error that you mentioned, I removed either the reference to the schema name or database name and received the same error you did.</p>\n\n<p>Perhaps you need to add the database name and schema name before the table name?</p>\n" }, { "answer_id": 86658, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 1, "selected": true, "text": "<p>Tim's suggestion didn't solve my problem on my development PC, but it did convince me to try again from a different PC. When using a different PC's SSMS to log into the development PC's database and trying exactly what Tim describes, I'm having the same behavior Tim describes.</p>\n\n<p>I was also able to re-replicate the argument parsing issue on the other PCs I had tried in the past. I'm hoping Tim can let me know what's the version and build number on his SSMS installation, because my current theory is that the problem is just from the specific build that my coworkers and I have on our dev PCs -- the version string is \"Microsoft SQL Server Management Studio 9.00.1399.00\". All of our installs of that version took place well over a year ago, so I don't know that I can trace back what disk it's from.</p>\n\n<p>The one that is NOT having the problem is actually our development server, which has \"Microsoft SQL Server Management Studio 9.00.3042.00\" installed. I don't know if this might be something I can make go away by patching or something, but it currently looks like 1399 reads the entire selection as a single argument, while 3042 does some pre-parsing. I've also recently found that when I pass in a string that contains \"--\" (comment token) in 3042, everything after the \"--\" is ignored, while in 1399, it's all included in the first argument.</p>\n" }, { "answer_id": 92481, "author": "Tim Lentine", "author_id": 2833, "author_profile": "https://Stackoverflow.com/users/2833", "pm_score": 0, "selected": false, "text": "<p>I am using SSMS version 9.00.3042.00 as well, which probably explains why it is working on my machine. </p>\n" }, { "answer_id": 377568, "author": "Flair", "author_id": 38819, "author_profile": "https://Stackoverflow.com/users/38819", "pm_score": 0, "selected": false, "text": "<p>Agree with Tim. I have just upgraded to SQL Server 05 sp2 and I confirm that this bug gets fixed.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1818/" ]
I've long been a fan of Stored Procedure Keyboard Accelerators, as described in [this article](http://blogs.msdn.com/irenak/archive/2006/10/27/sysk-228-get-table-columns-or-rows-with-single-key-press.aspx). When we moved from SQL 2000 to 2005, though, and from Query Analyzer to Management Studio, the handling of the arguments changed. In QA, comma-separated arguments were automatically read as two separate arguments. In SSMS -- at least for me -- it's being read as one argument, with commas in it. Similarly, if I pass in a single argument with single quotes in it, I get a syntax error, *unless I escape the quotes* (' -> ''). In the article linked above, the author implies that this should not be the case for SSMS, but even with her exact example, comma-separated arguments are still being interpreted as one argument on every SSMS installation I've tried it on (3 of them), running against every SQL Server installation I've tried (4 of them). E.g., typing the following into SSMS, ``` Person,4 ``` then selecting it and running the shortcut, I get the error message "Invalid object name 'Person,4'. Does anybody have any idea how to fix this? Does anybody even use these shortcuts? I've Googled this problem several times over the past two years, and have had no luck. Edit: May be an issue with a specific build of SSMS. I have a follow-up post below.
Tim's suggestion didn't solve my problem on my development PC, but it did convince me to try again from a different PC. When using a different PC's SSMS to log into the development PC's database and trying exactly what Tim describes, I'm having the same behavior Tim describes. I was also able to re-replicate the argument parsing issue on the other PCs I had tried in the past. I'm hoping Tim can let me know what's the version and build number on his SSMS installation, because my current theory is that the problem is just from the specific build that my coworkers and I have on our dev PCs -- the version string is "Microsoft SQL Server Management Studio 9.00.1399.00". All of our installs of that version took place well over a year ago, so I don't know that I can trace back what disk it's from. The one that is NOT having the problem is actually our development server, which has "Microsoft SQL Server Management Studio 9.00.3042.00" installed. I don't know if this might be something I can make go away by patching or something, but it currently looks like 1399 reads the entire selection as a single argument, while 3042 does some pre-parsing. I've also recently found that when I pass in a string that contains "--" (comment token) in 3042, everything after the "--" is ignored, while in 1399, it's all included in the first argument.
85,181
<p>This is pretty weird.</p> <p>I have my Profiler open and it obviously shows that a stored procedure is called. I open the database and the SP list, but the SP doesn't exist. However, there's another SP whose name is the same except it has a prefix 'x'</p> <p>Is SQL Server 2005 mapping the SP name to a different one for security purposes?</p> <p>EDIT: I found out it's a Synonym, whatever that is. </p>
[ { "answer_id": 85245, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>Possibly silly questions, but just in case... have you refreshed the SP list? Have you checked for a stored procedure of that name under a different owner? If you created the stored procedure without specifying the owner then it could be in the list under your ownership (or not at all if the list is filtered to only \"dbo\" for example).</p>\n" }, { "answer_id": 85251, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You may not have permission to see all the objects in the database</p>\n" }, { "answer_id": 85263, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 1, "selected": false, "text": "<p>Adding to the previous answers, it could also be under \"System Stored Procedures\", and if the name of the stored procedure begins with \"sp_\", it could also be in the master database.</p>\n" }, { "answer_id": 85341, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 4, "selected": true, "text": "<p>In general, when you know an object exists because it's been used in a query, and you can't find it in the object tree in Management Studio, you can do this to find it. </p>\n\n<pre><code>select *\nfrom sys.objects\nwhere name = 'THE_NAME_YOU_WANT'\n</code></pre>\n\n<p>I just checked, and it works with Synonyms.</p>\n" }, { "answer_id": 6598930, "author": "Amit Sharma", "author_id": 831758, "author_profile": "https://Stackoverflow.com/users/831758", "pm_score": 1, "selected": false, "text": "<p>The stored procedure will be inside the database you have selected at time of stored procedure creation. So search inside the database from which it is extracting data, otherwise it will be inside the master database. If still you are not able to find then first number solution is best one. i.e. </p>\n\n<pre><code>select * from sys.objects where name = 'name of stored procedure'\n</code></pre>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088/" ]
This is pretty weird. I have my Profiler open and it obviously shows that a stored procedure is called. I open the database and the SP list, but the SP doesn't exist. However, there's another SP whose name is the same except it has a prefix 'x' Is SQL Server 2005 mapping the SP name to a different one for security purposes? EDIT: I found out it's a Synonym, whatever that is.
In general, when you know an object exists because it's been used in a query, and you can't find it in the object tree in Management Studio, you can do this to find it. ``` select * from sys.objects where name = 'THE_NAME_YOU_WANT' ``` I just checked, and it works with Synonyms.
85,183
<p>I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance.</p> <p>Does </p> <pre><code>container.Release(obj); </code></pre> <p>automatically call Dispose() immediately? Or do I need to do</p> <pre><code>obj.Dispose(); container.Release(obj); </code></pre> <p>Couldn't find anything in the documentation on what exactly Release does</p> <p><strong>EDIT:</strong> See my answer below for the results of tests I ran. Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle? This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it?</p>
[ { "answer_id": 85498, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "<p>It depends on the lifestyle of the component you specified when you added it to the container.</p>\n\n<p>You would use Release() If the lifestyle is Pooled. This puts the component back in the pool for the next retrieval (the object is not destroyed, so disposing would be bad)</p>\n\n<p>if the lifestyle is transient, a new object is created when you get the component. In this case the disposal is up to you, and you do not need to call Release</p>\n\n<p>If the lifestyle is Thread, the same component is used for each thread, not destroyed.</p>\n\n<p>If the lifestyle is Singleton, only one component is created and not detroyed.</p>\n\n<p>Most likely, you are using transient components? (if you are concerned about disposing of them in a timely manner)\nin that case, just wrap it with a using and you're set (or call the dispose yourself somewhere)</p>\n\n<pre><code>using(ISomeService service = container.Resolve&lt;ISomeService&gt;())\n{\n // Do stuff here\n // service.Dispose is automatically called \n}\n</code></pre>\n\n<p><strong>Edit</strong> - Yes, in order to \"refresh\" or dispose and recreate your singleton you would need to either destroy the container or write a custom lifecycle. Doing a custom lifecycle is not actually that difficult and keeps the logic to do so in one place.</p>\n" }, { "answer_id": 85820, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 1, "selected": false, "text": "<p>Alright, so I've been running tests and it seems like <code>Container.Release()</code> WILL implicitly cause an IDisposable's <code>Dispose()</code> method to execute only if the lifestyle is Transient (this is probably not exactly correct but point is that it wont' do a darn thing if the lifestyle is singleton).</p>\n\n<p>Now if you call <code>Container.Dispose()</code> it WILL call the disposable methods also, though unfortunately it will dispose of the whole kernel and you will have to add all components back in:</p>\n\n<pre><code>var container = new WindsorContainer();\ncontainer.AddComponentWithLifestyle&lt;MyDisposable&gt;(Castle.Core.LifestyleType.Singleton);\nvar obj = container.Resolve&lt;MyDisposable&gt;(); // Create a new instance of MyDisposable\nobj.DoSomething();\nvar obj2 = container.Resolve&lt;MyDisposable&gt;(); // Returns the same instance as obj\nobj2.DoSomething();\ncontainer.Dispose(); // Will call the Disposable method of obj\n// Now the components need to be added back in \n container.AddComponentWithLifestyle&lt;MyDisposable&gt;(Castle.Core.LifestyleType.Singleton);\nvar obj3 = container.Resolve&lt;MyDisposable&gt;(); // Create a new instance of MyDisposable\n</code></pre>\n\n<p>Fortunately in my case I can afford to just drop all components and I can restore them fairly easily. However this is sub-optimal.</p>\n" }, { "answer_id": 166485, "author": "Bittercoder", "author_id": 4843, "author_profile": "https://Stackoverflow.com/users/4843", "pm_score": 5, "selected": true, "text": "<p>This is something I think people aren't really aware of when working with the Windsor container - especially the often <em><strong>surprising</strong></em> behavior that disposable transient components are held onto by the container for the lifetime of the kernel until it's disposed unless you release them yourself - though it is documented - take a look <a href=\"https://github.com/castleproject/Windsor/blob/master/docs/release-policy.md\" rel=\"noreferrer\">here</a> - but to quickly quote:</p>\n<blockquote>\n<p>the MicroKernel has a pluggable release policy that can hook up and implement some\nrouting to dispose the components. The MicroKernel comes with three IReleasePolicy implementations:</p>\n<ul>\n<li>AllComponentsReleasePolicy: track all components to enforce correct disposal upon the MicroKernel instance disposal</li>\n<li>LifecycledComponentsReleasePolicy: only track components that have a decommission lifecycle associated</li>\n<li>NoTrackingReleasePolicy: does not perform any tracking</li>\n</ul>\n<p>You can also implement your own release policy by using the interface IReleasePolicy.</p>\n</blockquote>\n<p>What you might find easier is to change the policy to a <strong>NoTrackingReleasePolicy</strong> and then handle the disposing yourself - this is potentially risky as well, but if your lifestyles are largely transient (or if when your container is disposed your application is about to close anyway) it's probably not a big deal. Remember however that any components which have already been injected with the singleton will hold a reference, so you could end up causing problems trying to &quot;refresh&quot; your singletons - it seems like a bad practice, and I wonder if perhaps you can avoid having to do this in the first place by improving the way your applications put together.</p>\n<p>Other approaches are to build a custom lifecycle with it's own decommission implementation (so releasing the singleton would actually dispose of the component, much like the transient lifecycle does).</p>\n<p>Alternatively another approach is to have a decorator for your service registered in the container with a singleton lifestyle, but your actual underlying service registered in the container with a transient lifestyle - then when you need to refresh the component just dispose of the transient underlying component held by the decorator and replace it with a freshly resolved instance (resolve it using the components key, rather then the service, to avoid getting the decorator) - this avoids issues with other singleton services (which aren't being &quot;refreshed&quot;) from holding onto stale services which have been disposed of making them unusable, but does require a bit of casting etc. to make it work.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance. Does ``` container.Release(obj); ``` automatically call Dispose() immediately? Or do I need to do ``` obj.Dispose(); container.Release(obj); ``` Couldn't find anything in the documentation on what exactly Release does **EDIT:** See my answer below for the results of tests I ran. Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle? This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it?
This is something I think people aren't really aware of when working with the Windsor container - especially the often ***surprising*** behavior that disposable transient components are held onto by the container for the lifetime of the kernel until it's disposed unless you release them yourself - though it is documented - take a look [here](https://github.com/castleproject/Windsor/blob/master/docs/release-policy.md) - but to quickly quote: > > the MicroKernel has a pluggable release policy that can hook up and implement some > routing to dispose the components. The MicroKernel comes with three IReleasePolicy implementations: > > > * AllComponentsReleasePolicy: track all components to enforce correct disposal upon the MicroKernel instance disposal > * LifecycledComponentsReleasePolicy: only track components that have a decommission lifecycle associated > * NoTrackingReleasePolicy: does not perform any tracking > > > You can also implement your own release policy by using the interface IReleasePolicy. > > > What you might find easier is to change the policy to a **NoTrackingReleasePolicy** and then handle the disposing yourself - this is potentially risky as well, but if your lifestyles are largely transient (or if when your container is disposed your application is about to close anyway) it's probably not a big deal. Remember however that any components which have already been injected with the singleton will hold a reference, so you could end up causing problems trying to "refresh" your singletons - it seems like a bad practice, and I wonder if perhaps you can avoid having to do this in the first place by improving the way your applications put together. Other approaches are to build a custom lifecycle with it's own decommission implementation (so releasing the singleton would actually dispose of the component, much like the transient lifecycle does). Alternatively another approach is to have a decorator for your service registered in the container with a singleton lifestyle, but your actual underlying service registered in the container with a transient lifestyle - then when you need to refresh the component just dispose of the transient underlying component held by the decorator and replace it with a freshly resolved instance (resolve it using the components key, rather then the service, to avoid getting the decorator) - this avoids issues with other singleton services (which aren't being "refreshed") from holding onto stale services which have been disposed of making them unusable, but does require a bit of casting etc. to make it work.
85,190
<p>Consider:</p> <pre><code>List&lt;String&gt; someList = new ArrayList&lt;String&gt;(); // add "monkey", "donkey", "skeleton key" to someList </code></pre> <pre><code>for (String item : someList) { System.out.println(item); } </code></pre> <p>What would the equivalent <code>for</code> loop look like without using the <em>for each</em> syntax?</p>
[ { "answer_id": 85206, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 11, "selected": true, "text": "<pre><code>for (Iterator&lt;String&gt; i = someIterable.iterator(); i.hasNext();) {\n String item = i.next();\n System.out.println(item);\n}\n</code></pre>\n\n<p>Note that if you need to use <code>i.remove();</code> in your loop, or access the actual iterator in some way, you cannot use the <code>for ( : )</code> idiom, since the actual iterator is merely inferred.</p>\n\n<p>As was noted by Denis Bueno, this code works for any object that implements the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html\" rel=\"noreferrer\"><code>Iterable</code> interface</a>.</p>\n\n<p>Also, if the right-hand side of the <code>for (:)</code> idiom is an <code>array</code> rather than an <code>Iterable</code> object, the internal code uses an int index counter and checks against <code>array.length</code> instead. See the <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2\" rel=\"noreferrer\">Java Language Specification</a>.</p>\n" }, { "answer_id": 85209, "author": "toluju", "author_id": 12457, "author_profile": "https://Stackoverflow.com/users/12457", "pm_score": 6, "selected": false, "text": "<p>The for-each loop in Java uses the underlying iterator mechanism. So it's identical to the following:</p>\n\n<pre><code>Iterator&lt;String&gt; iterator = someList.iterator();\n\nwhile (iterator.hasNext()) {\n String item = iterator.next();\n System.out.println(item);\n}\n</code></pre>\n" }, { "answer_id": 85220, "author": "Hank", "author_id": 7610, "author_profile": "https://Stackoverflow.com/users/7610", "pm_score": 4, "selected": false, "text": "<p>Here's an equivalent expression.</p>\n\n<pre><code>for(Iterator&lt;String&gt; sit = someList.iterator(); sit.hasNext(); ) {\n System.out.println(sit.next());\n}\n</code></pre>\n" }, { "answer_id": 85221, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 3, "selected": false, "text": "<p>It would look something like this. Very crufty. </p>\n\n<pre><code>for (Iterator&lt;String&gt; i = someList.iterator(); i.hasNext(); )\n System.out.println(i.next());\n</code></pre>\n\n<p>There is a good writeup on <em>for each</em> in the <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html\" rel=\"nofollow noreferrer\">Sun documentation</a>.</p>\n" }, { "answer_id": 85232, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>for (Iterator&lt;String&gt; itr = someList.iterator(); itr.hasNext(); ) {\n String item = itr.next();\n System.out.println(item);\n}\n</code></pre>\n" }, { "answer_id": 85242, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 5, "selected": false, "text": "<p>It's implied by <a href=\"https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work/85206#85206\">nsayer's answer</a>, but it's worth noting that the OP's for(..) syntax will work when &quot;someList&quot; is <em>anything</em> that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.</p>\n" }, { "answer_id": 85279, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 4, "selected": false, "text": "<p>Also note that using the \"foreach\" method in the original question does have some limitations, such as not being able to remove items from the list during the iteration.</p>\n\n<p>The new for-loop is easier to read and removes the need for a separate iterator, but is only really usable in read-only iteration passes.</p>\n" }, { "answer_id": 85424, "author": "Mikezx6r", "author_id": 5382, "author_profile": "https://Stackoverflow.com/users/5382", "pm_score": 9, "selected": false, "text": "<p>The construct <em>for each</em> is also valid for arrays. e.g.</p>\n\n<pre><code>String[] fruits = new String[] { \"Orange\", \"Apple\", \"Pear\", \"Strawberry\" };\n\nfor (String fruit : fruits) {\n // fruit is an element of the `fruits` array.\n}\n</code></pre>\n\n<p>which is essentially equivalent of</p>\n\n<pre><code>for (int i = 0; i &lt; fruits.length; i++) {\n String fruit = fruits[i];\n // fruit is an element of the `fruits` array.\n}\n</code></pre>\n\n<p>So, overall summary: <br/>\n<a href=\"https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work/85206#85206\">[nsayer]</a> The following is the longer form of what is happening:</p>\n\n<blockquote>\n<pre><code>for(Iterator&lt;String&gt; i = someList.iterator(); i.hasNext(); ) {\n String item = i.next();\n System.out.println(item);\n}\n</code></pre>\n \n <p>Note that if you need to use\n i.remove(); in your loop, or access\n the actual iterator in some way, you\n cannot use the for( : ) idiom, since\n the actual Iterator is merely\n inferred.</p>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work/85242#85242\">[Denis Bueno]</a></p>\n\n<blockquote>\n <p>It's implied by nsayer's answer, but\n it's worth noting that the OP's for(..)\n syntax will work when \"someList\" is\n anything that implements\n java.lang.Iterable -- it doesn't have\n to be a list, or some collection from\n java.util. Even your own types,\n therefore, can be used with this\n syntax.</p>\n</blockquote>\n" }, { "answer_id": 85933, "author": "Ryan Delucchi", "author_id": 9931, "author_profile": "https://Stackoverflow.com/users/9931", "pm_score": 5, "selected": false, "text": "<p>The Java \"for-each\" loop construct will allow iteration over two types of objects:</p>\n\n<ul>\n<li><code>T[]</code> <em>(arrays of any type)</em></li>\n<li><code>java.lang.Iterable&lt;T&gt;</code></li>\n</ul>\n\n<p>The <code>Iterable&lt;T&gt;</code> interface has only one method: <code>Iterator&lt;T&gt; iterator()</code>. This works on objects of type <code>Collection&lt;T&gt;</code> because the <code>Collection&lt;T&gt;</code> interface extends <code>Iterable&lt;T&gt;</code>.</p>\n" }, { "answer_id": 7956673, "author": "MRocklin", "author_id": 616616, "author_profile": "https://Stackoverflow.com/users/616616", "pm_score": 7, "selected": false, "text": "<p>Here is an answer which does not assume knowledge of Java Iterators. It is less precise, but it is useful for education.</p>\n\n<p>While programming we often write code that looks like the following:</p>\n\n<pre><code>char[] grades = ....\nfor(int i = 0; i &lt; grades.length; i++) { // for i goes from 0 to grades.length\n System.out.print(grades[i]); // Print grades[i]\n}\n</code></pre>\n\n<p>The foreach syntax allows this common pattern to be written in a more natural and less syntactically noisy way.</p>\n\n<pre><code>for(char grade : grades) { // foreach grade in grades\n System.out.print(grade); // print that grade\n}\n</code></pre>\n\n<p>Additionally this syntax is valid for objects such as Lists or Sets which do not support array indexing, but which do implement the Java Iterable interface.</p>\n" }, { "answer_id": 12722557, "author": "oneConsciousness", "author_id": 1503768, "author_profile": "https://Stackoverflow.com/users/1503768", "pm_score": 4, "selected": false, "text": "<p>The concept of a foreach loop as mentioned in Wikipedia is highlighted below:</p>\n\n<blockquote>\n <p>Unlike other for loop constructs, however, foreach loops usually\n maintain <strong>no explicit counter</strong>: they essentially say \"do this to\n everything in this set\", rather than \"do this x times\". This avoids\n potential <strong>off-by-one errors</strong> and makes code simpler to read.</p>\n</blockquote>\n\n<p>So the concept of a foreach loop describes that the loop does not use any explicit counter which means that there is no need of using indexes to traverse in the list thus it saves user from off-by-one error. To describe the general concept of this off-by-one error, let us take an example of a loop to traverse in a list using indexes.</p>\n\n<pre><code>// In this loop it is assumed that the list starts with index 0\nfor(int i=0; i&lt;list.length; i++){\n\n}\n</code></pre>\n\n<p>But suppose if the list starts with index 1 then this loop is going to throw an exception as it will found no element at index 0 and this error is called an off-by-one error. So to avoid this off-by-one error the concept of a foreach loop is used. There may be other advantages too, but this is what I think is the main concept and advantage of using a foreach loop.</p>\n" }, { "answer_id": 19828685, "author": "PrivateName", "author_id": 2923930, "author_profile": "https://Stackoverflow.com/users/2923930", "pm_score": 5, "selected": false, "text": "<p>A foreach loop syntax is:</p>\n<pre><code>for (type obj:array) {...}\n</code></pre>\n<p>Example:</p>\n<pre><code>String[] s = {&quot;Java&quot;, &quot;Coffe&quot;, &quot;Is&quot;, &quot;Cool&quot;};\nfor (String str:s /*s is the array*/) {\n System.out.println(str);\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Java\nCoffe\nIs\nCool\n</code></pre>\n<p>WARNING: You can access array elements with the foreach loop, but you can NOT initialize them. Use the original <code>for</code> loop for that.</p>\n<p>WARNING: You must match the type of the array with the other object.</p>\n<pre><code>for (double b:s) // Invalid-double is not String\n</code></pre>\n<p>If you want to edit elements, use the original <code>for</code> loop like this:</p>\n<pre><code>for (int i = 0; i &lt; s.length-1 /*-1 because of the 0 index */; i++) {\n if (i==1) //1 because once again I say the 0 index\n s[i]=&quot;2 is cool&quot;;\n else\n s[i] = &quot;hello&quot;;\n}\n</code></pre>\n<p>Now if we dump s to the console, we get:</p>\n<pre class=\"lang-none prettyprint-override\"><code>hello\n2 is cool\nhello\nhello\n</code></pre>\n" }, { "answer_id": 22114571, "author": "aliteralmind", "author_id": 2736496, "author_profile": "https://Stackoverflow.com/users/2736496", "pm_score": 8, "selected": false, "text": "<p>The <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html\" rel=\"noreferrer\">for-each loop</a>, added in <a href=\"http://docs.oracle.com/javase/1.5.0/docs/guide/language/index.html\" rel=\"noreferrer\">Java 5</a> (also called the &quot;enhanced for loop&quot;), is equivalent to using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html\" rel=\"noreferrer\"><code>java.util.Iterator</code></a>--it's syntactic sugar for the same thing. Therefore, when reading each element, one by one and in order, a for-each should always be chosen over an iterator, as it is more convenient and concise.</p>\n<h3>For-each</h3>\n<pre><code>for (int i : intList) {\n System.out.println(&quot;An element in the list: &quot; + i);\n}\n</code></pre>\n<h3>Iterator</h3>\n<pre><code>Iterator&lt;Integer&gt; intItr = intList.iterator();\nwhile (intItr.hasNext()) {\n System.out.println(&quot;An element in the list: &quot; + intItr.next());\n}\n</code></pre>\n<p>There are situations where you must use an <code>Iterator</code> directly. For example, attempting to delete an element while using a for-each can (will?) result in a <code>ConcurrentModificationException</code>.</p>\n<h2>For-each vs. for-loop: Basic differences</h2>\n<p>The only practical difference between for-loop and for-each is that, in the case of indexable objects, you do not have access to the index. An example when the basic for-loop is required:</p>\n<pre><code>for (int i = 0; i &lt; array.length; i++) {\n if(i &lt; 5) {\n // Do something special\n } else {\n // Do other stuff\n }\n}\n</code></pre>\n<p>Although you could manually create a separate index int-variable with for-each,</p>\n<pre><code>int idx = -1;\nfor (int i : intArray) {\n idx++;\n ...\n}\n</code></pre>\n<p>...it is not recommended, since <a href=\"http://www.java-made-easy.com/variable-scope.html\" rel=\"noreferrer\">variable-scope</a> is not ideal, and the basic <code>for</code> loop is simply the standard and expected format for this use case.</p>\n<h2>For-each vs. for-loop: Performance</h2>\n<p>When accessing collections, a for-each is <a href=\"https://stackoverflow.com/questions/1879255/traditional-for-loop-vs-iterator-in-java\">significantly faster</a> than the basic <code>for</code> loop's array access. When accessing arrays, however--at least with primitive and wrapper-arrays--access via indexes is dramatically faster.</p>\n<h3>Timing the difference between iterator and index access for primitive int-arrays</h3>\n<p>Indexes are 23-<em>40</em> percent faster than iterators when accessing <code>int</code> or <code>Integer</code> arrays. Here is the output from the testing class at the bottom of this post, which sums the numbers in a 100-element primitive-int array (A is iterator, B is index):</p>\n<pre class=\"lang-none prettyprint-override\"><code>[C:\\java_code\\]java TimeIteratorVsIndexIntArray 1000000\nTest A: 358,597,622 nanoseconds\nTest B: 269,167,681 nanoseconds\nB faster by 89,429,941 nanoseconds (24.438799231635727% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntArray 1000000\nTest A: 377,461,823 nanoseconds\nTest B: 278,694,271 nanoseconds\nB faster by 98,767,552 nanoseconds (25.666236154695838% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntArray 1000000\nTest A: 288,953,495 nanoseconds\nTest B: 207,050,523 nanoseconds\nB faster by 81,902,972 nanoseconds (27.844689860906513% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntArray 1000000\nTest A: 375,373,765 nanoseconds\nTest B: 283,813,875 nanoseconds\nB faster by 91,559,890 nanoseconds (23.891659337194227% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntArray 1000000\nTest A: 375,790,818 nanoseconds\nTest B: 220,770,915 nanoseconds\nB faster by 155,019,903 nanoseconds (40.75164734599769% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntArray 1000000\nTest A: 326,373,762 nanoseconds\nTest B: 202,555,566 nanoseconds\nB faster by 123,818,196 nanoseconds (37.437545972215744% faster)\n</code></pre>\n<p>I also ran this for an <code>Integer</code> array, and indexes are still the clear winner, but only between 18 and 25 percent faster.</p>\n<h3>For collections, iterators are faster than indexes</h3>\n<p>For a <code>List</code> of <code>Integers</code>, however, iterators are the clear winner. Just change the int-array in the test-class to:</p>\n<pre><code>List&lt;Integer&gt; intList = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100});\n</code></pre>\n<p>And make the necessary changes to the test-function (<code>int[]</code> to <code>List&lt;Integer&gt;</code>, <code>length</code> to <code>size()</code>, etc.):</p>\n<pre class=\"lang-none prettyprint-override\"><code>[C:\\java_code\\]java TimeIteratorVsIndexIntegerList 1000000\nTest A: 3,429,929,976 nanoseconds\nTest B: 5,262,782,488 nanoseconds\nA faster by 1,832,852,512 nanoseconds (34.326681820485675% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntegerList 1000000\nTest A: 2,907,391,427 nanoseconds\nTest B: 3,957,718,459 nanoseconds\nA faster by 1,050,327,032 nanoseconds (26.038700083921256% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntegerList 1000000\nTest A: 2,566,004,688 nanoseconds\nTest B: 4,221,746,521 nanoseconds\nA faster by 1,655,741,833 nanoseconds (38.71935684115413% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntegerList 1000000\nTest A: 2,770,945,276 nanoseconds\nTest B: 3,829,077,158 nanoseconds\nA faster by 1,058,131,882 nanoseconds (27.134122749113843% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntegerList 1000000\nTest A: 3,467,474,055 nanoseconds\nTest B: 5,183,149,104 nanoseconds\nA faster by 1,715,675,049 nanoseconds (32.60101667104192% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntList 1000000\nTest A: 3,439,983,933 nanoseconds\nTest B: 3,509,530,312 nanoseconds\nA faster by 69,546,379 nanoseconds (1.4816434912159906% faster)\n\n[C:\\java_code\\]java TimeIteratorVsIndexIntList 1000000\nTest A: 3,451,101,466 nanoseconds\nTest B: 5,057,979,210 nanoseconds\nA faster by 1,606,877,744 nanoseconds (31.269164666060377% faster)\n</code></pre>\n<p>In one test they're almost equivalent, but with collections, iterator wins.</p>\n<p>*This post is based on two answers I wrote on Stack Overflow:</p>\n<ul>\n<li><p><em><a href=\"https://stackoverflow.com/questions/22110482/uses-and-syntax-for-for-each-loop-in-java/22110517#22110517\">Uses and syntax for for-each loop in Java</a></em></p>\n</li>\n<li><p><em><a href=\"https://stackoverflow.com/questions/22540025/should-i-use-an-iterator-or-a-forloop-to-iterate/22540191#22540191\">Should I use an Iterator or a forloop to iterate?</a></em></p>\n</li>\n</ul>\n<p>Some more information: <em><a href=\"https://stackoverflow.com/questions/2113216/which-is-more-efficient-a-for-each-loop-or-an-iterator\">Which is more efficient, a for-each loop, or an iterator?</a></em></p>\n<h3>The full testing class</h3>\n<p>I created this compare-the-time-it-takes-to-do-any-two-things class after reading <a href=\"https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java\">this question</a> on Stack Overflow:</p>\n<pre><code>import java.text.NumberFormat;\nimport java.util.Locale;\n\n/**\n &amp;lt;P&amp;gt;{@code java TimeIteratorVsIndexIntArray 1000000}&amp;lt;/P&amp;gt;\n\n @see &amp;lt;CODE&amp;gt;&amp;lt;A HREF=&amp;quot;https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java&amp;quot;&amp;gt;https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java&amp;lt;/A&amp;gt;&amp;lt;/CODE&amp;gt;\n **/\npublic class TimeIteratorVsIndexIntArray {\n\n public static final NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);\n\n public static final void main(String[] tryCount_inParamIdx0) {\n int testCount;\n\n // Get try-count from a command-line parameter\n try {\n testCount = Integer.parseInt(tryCount_inParamIdx0[0]);\n }\n catch(ArrayIndexOutOfBoundsException | NumberFormatException x) {\n throw new IllegalArgumentException(&quot;Missing or invalid command line parameter: The number of testCount for each test. &quot; + x);\n }\n\n //Test proper...START\n int[] intArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100};\n\n long lStart = System.nanoTime();\n for(int i = 0; i &lt; testCount; i++) {\n testIterator(intArray);\n }\n\n long lADuration = outputGetNanoDuration(&quot;A&quot;, lStart);\n\n lStart = System.nanoTime();\n for(int i = 0; i &lt; testCount; i++) {\n testFor(intArray);\n }\n\n long lBDuration = outputGetNanoDuration(&quot;B&quot;, lStart);\n\n outputGetABTestNanoDifference(lADuration, lBDuration, &quot;A&quot;, &quot;B&quot;);\n }\n\n private static final void testIterator(int[] int_array) {\n int total = 0;\n for(int i = 0; i &lt; int_array.length; i++) {\n total += int_array[i];\n }\n }\n\n private static final void testFor(int[] int_array) {\n int total = 0;\n for(int i : int_array) {\n total += i;\n }\n }\n //Test proper...END\n\n //Timer testing utilities...START\n public static final long outputGetNanoDuration(String s_testName, long l_nanoStart) {\n long lDuration = System.nanoTime() - l_nanoStart;\n System.out.println(&quot;Test &quot; + s_testName + &quot;: &quot; + nf.format(lDuration) + &quot; nanoseconds&quot;);\n return lDuration;\n }\n\n public static final long outputGetABTestNanoDifference(long l_aDuration, long l_bDuration, String s_aTestName, String s_bTestName) {\n long lDiff = -1;\n double dPct = -1.0;\n String sFaster = null;\n if(l_aDuration &gt; l_bDuration) {\n lDiff = l_aDuration - l_bDuration;\n dPct = 100.00 - (l_bDuration * 100.0 / l_aDuration + 0.5);\n sFaster = &quot;B&quot;;\n }\n else {\n lDiff = l_bDuration - l_aDuration;\n dPct = 100.00 - (l_aDuration * 100.0 / l_bDuration + 0.5);\n sFaster = &quot;A&quot;;\n }\n System.out.println(sFaster + &quot; faster by &quot; + nf.format(lDiff) + &quot; nanoseconds (&quot; + dPct + &quot;% faster)&quot;);\n return lDiff;\n }\n\n //Timer testing utilities...END\n\n}\n</code></pre>\n" }, { "answer_id": 23171818, "author": "Jrovalle", "author_id": 3551958, "author_profile": "https://Stackoverflow.com/users/3551958", "pm_score": 5, "selected": false, "text": "<p>In Java 8 features you can use this:</p>\n\n<pre><code>List&lt;String&gt; messages = Arrays.asList(\"First\", \"Second\", \"Third\");\n\nvoid forTest(){\n messages.forEach(System.out::println);\n}\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>First\nSecond\nThird\n</code></pre>\n" }, { "answer_id": 30700135, "author": "TheArchon", "author_id": 4752024, "author_profile": "https://Stackoverflow.com/users/4752024", "pm_score": 2, "selected": false, "text": "<p>The Java for-each idiom can only be applied to arrays or objects of type <strong>*Iterable</strong>. This idiom is <strong><em>implicit</em></strong> as it truly backed by an Iterator. The Iterator is programmed by the programmer and often uses an integer index or a node (depending on the data structure) to keep track of its position. On paper it is slower than a regular for-loop, a least for \"linear\" structures like arrays and Lists but it provides greater abstraction. </p>\n" }, { "answer_id": 32857986, "author": "Manohar", "author_id": 2039852, "author_profile": "https://Stackoverflow.com/users/2039852", "pm_score": 3, "selected": false, "text": "<p>It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below.</p>\n\n<p><strong>Normal <code>for</code> loop:</strong></p>\n\n<pre><code>void cancelAll(Collection&lt;TimerTask&gt; list) {\n for (Iterator&lt;TimerTask&gt; i = list.iterator(); i.hasNext();)\n i.next().cancel();\n}\n</code></pre>\n\n<p><strong>Using for-each:</strong></p>\n\n<pre><code>void cancelAll(Collection&lt;TimerTask&gt; list) {\n for (TimerTask t : list)\n t.cancel();\n}\n</code></pre>\n\n<p><strong>for-each</strong> is a construct over a collection that implements <strong>Iterator</strong>. Remember that, your collection should implement <strong>Iterator</strong>; otherwise you can't use it with for-each.</p>\n\n<p>The following line is read as \"<em>for each TimerTask t in list.</em>\"</p>\n\n<pre><code>for (TimerTask t : list)\n</code></pre>\n\n<p>There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors).</p>\n" }, { "answer_id": 33232565, "author": "akhil_mittal", "author_id": 1216775, "author_profile": "https://Stackoverflow.com/users/1216775", "pm_score": 6, "selected": false, "text": "<p>As defined in <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2\" rel=\"nofollow noreferrer\">JLS</a>, a <em>for-each</em> loop can have two forms:</p>\n<ol>\n<li><p>If the type of expression is a subtype of <code>Iterable</code> then translation is as:</p>\n<pre><code>List&lt;String&gt; someList = new ArrayList&lt;String&gt;();\nsomeList.add(&quot;Apple&quot;);\nsomeList.add(&quot;Ball&quot;);\nfor (String item : someList) {\n System.out.println(item);\n}\n\n// Is translated to:\n\nfor(Iterator&lt;String&gt; stringIterator = someList.iterator(); stringIterator.hasNext(); ) {\n String item = stringIterator.next();\n System.out.println(item);\n}\n</code></pre>\n</li>\n<li><p>If the expression necessarily has an array type <code>T[]</code> then:</p>\n<pre><code>String[] someArray = new String[2];\nsomeArray[0] = &quot;Apple&quot;;\nsomeArray[1] = &quot;Ball&quot;;\n\nfor(String item2 : someArray) {\n System.out.println(item2);\n}\n\n// Is translated to:\nfor (int i = 0; i &lt; someArray.length; i++) {\n String item2 = someArray[i];\n System.out.println(item2);\n}\n</code></pre>\n</li>\n</ol>\n<p>Java 8 has introduced streams which perform generally better with a decent size dataset. We can use them as:</p>\n<pre><code>someList.stream().forEach(System.out::println);\nArrays.stream(someArray).forEach(System.out::println);\n</code></pre>\n" }, { "answer_id": 40283536, "author": "Santhosh Rajkumar", "author_id": 6037775, "author_profile": "https://Stackoverflow.com/users/6037775", "pm_score": 3, "selected": false, "text": "<pre><code>public static Boolean Add_Tag(int totalsize)\n{\n List&lt;String&gt; fullst = new ArrayList&lt;String&gt;();\n for(int k=0; k&lt;totalsize; k++)\n {\n fullst.addAll();\n }\n}\n</code></pre>\n" }, { "answer_id": 40857220, "author": "L Joey", "author_id": 5332814, "author_profile": "https://Stackoverflow.com/users/5332814", "pm_score": 3, "selected": false, "text": "<p>As so many good answers said, an object must implement the <code>Iterable interface</code> if it wants to use a <code>for-each</code> loop.</p>\n<p>I'll post a simple example and try to explain in a different way how a <code>for-each</code> loop works.</p>\n<p>The <code>for-each</code> loop example:</p>\n<pre><code>public class ForEachTest {\n\n public static void main(String[] args) {\n\n List&lt;String&gt; list = new ArrayList&lt;String&gt;();\n list.add(&quot;111&quot;);\n list.add(&quot;222&quot;);\n\n for (String str : list) {\n System.out.println(str);\n }\n }\n}\n</code></pre>\n<p>Then, if we use <code>javap</code> to decompile this class, we will get this bytecode sample:</p>\n<pre class=\"lang-none prettyprint-override\"><code>public static void main(java.lang.String[]);\n flags: ACC_PUBLIC, ACC_STATIC\n Code:\n stack=2, locals=4, args_size=1\n 0: new #16 // class java/util/ArrayList\n 3: dup\n 4: invokespecial #18 // Method java/util/ArrayList.&quot;&lt;init&gt;&quot;:()V\n 7: astore_1\n 8: aload_1\n 9: ldc #19 // String 111\n 11: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z\n 16: pop\n 17: aload_1\n 18: ldc #27 // String 222\n 20: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z\n 25: pop\n 26: aload_1\n 27: invokeinterface #29, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;\n</code></pre>\n<p>As we can see from the last line of the sample, the compiler will automatically convert the use of <code>for-each</code> keyword to the use of an <code>Iterator</code> at compile time. That may explain why object, which doesn't implement the <code>Iterable interface</code>, will throw an <code>Exception</code> when it tries to use the <code>for-each</code> loop.</p>\n" }, { "answer_id": 44018004, "author": "Alexander Drobyshevsky", "author_id": 1693748, "author_profile": "https://Stackoverflow.com/users/1693748", "pm_score": 4, "selected": false, "text": "<p>An alternative to forEach in order to avoid your &quot;for each&quot;:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List&lt;String&gt; someList = new ArrayList&lt;String&gt;();\n</code></pre>\n<p>Variant 1 (plain):</p>\n<pre class=\"lang-java prettyprint-override\"><code>someList.stream().forEach(listItem -&gt; {\n System.out.println(listItem);\n});\n</code></pre>\n<p>Variant 2 (parallel execution (faster)):</p>\n<pre class=\"lang-java prettyprint-override\"><code>someList.parallelStream().forEach(listItem -&gt; {\n System.out.println(listItem);\n});\n</code></pre>\n" }, { "answer_id": 48497277, "author": "Rei Brown", "author_id": 8352967, "author_profile": "https://Stackoverflow.com/users/8352967", "pm_score": 1, "selected": false, "text": "<p>This looks crazy but hey it works</p>\n\n<pre><code>List&lt;String&gt; someList = new ArrayList&lt;&gt;(); //has content\nsomeList.forEach(System.out::println);\n</code></pre>\n\n<p>This works. <strong><em>Magic</em></strong></p>\n" }, { "answer_id": 49015283, "author": "stackFan", "author_id": 3315482, "author_profile": "https://Stackoverflow.com/users/3315482", "pm_score": 3, "selected": false, "text": "<p>Prior to Java 8, you need to use the following:</p>\n\n<pre><code>Iterator&lt;String&gt; iterator = someList.iterator();\n\nwhile (iterator.hasNext()) {\n String item = iterator.next();\n System.out.println(item);\n}\n</code></pre>\n\n<p>However, with the introduction of Streams in Java 8 you can do same thing in much less syntax. For example, for your <code>someList</code> you can do:</p>\n\n<pre><code>someList.stream().forEach(System.out::println);\n</code></pre>\n\n<p>You can find more about streams <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 50135519, "author": "gomisha", "author_id": 5719544, "author_profile": "https://Stackoverflow.com/users/5719544", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"https://funnelgarden.com/java-for-loop/#Enhanced_For_Loop\" rel=\"noreferrer\">Java for each loop</a> (aka enhanced for loop) is a simplified version of a for loop. The advantage is that there is less code to write and less variables to manage. The downside is that you have no control over the step value and no access to the loop index inside the loop body.</p>\n\n<p>They are best used when the step value is a simple increment of 1 and when you only need access to the current loop element. For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element.</p>\n\n<p>There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.</p>\n\n<p>Enhanced for loops follow this order of execution:</p>\n\n<p>1) loop body</p>\n\n<p>2) repeat from step 1 until entire array or collection has been traversed</p>\n\n<p><strong>Example – Integer Array</strong></p>\n\n<pre><code>int [] intArray = {1, 3, 5, 7, 9};\nfor(int currentValue : intArray) {\n System.out.println(currentValue);\n}\n</code></pre>\n\n<p>The currentValue variable holds the current value being looped over in the intArray array. Notice there’s no explicit step value – it’s always an increment by 1.</p>\n\n<p>The colon can be thought of to mean “in”. So the enhanced for loop declaration states: loop over intArray and store the current array int value <strong>in</strong> the currentValue variable.</p>\n\n<p>Output:</p>\n\n<pre><code>1\n3\n5\n7\n9\n</code></pre>\n\n<p><strong>Example – String Array</strong></p>\n\n<p>We can use the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the current String value <strong>in</strong> the currentString variable.</p>\n\n<pre><code>String [] myStrings = {\n \"alpha\",\n \"beta\",\n \"gamma\",\n \"delta\"\n};\n\nfor(String currentString : myStrings) {\n System.out.println(currentString);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>alpha\nbeta\ngamma\ndelta\n</code></pre>\n\n<p><strong>Example – List</strong></p>\n\n<p>The enhanced for loop can also be used to iterate over a java.util.List as follows:</p>\n\n<pre><code>List&lt;String&gt; myList = new ArrayList&lt;String&gt;();\nmyList.add(\"alpha\");\nmyList.add(\"beta\");\nmyList.add(\"gamma\");\nmyList.add(\"delta\");\n\nfor(String currentItem : myList) {\n System.out.println(currentItem);\n}\n</code></pre>\n\n<p>The loop declaration states: loop over myList List of Strings and store the current List value <strong>in</strong> the currentItem variable.</p>\n\n<p>Output:</p>\n\n<pre><code>alpha\nbeta\ngamma\ndelta\n</code></pre>\n\n<p><strong>Example – Set</strong></p>\n\n<p>The enhanced for loop can also be used to iterate over a java.util.Set as follows:</p>\n\n<pre><code>Set&lt;String&gt; mySet = new HashSet&lt;String&gt;();\nmySet.add(\"alpha\");\nmySet.add(\"alpha\");\nmySet.add(\"beta\");\nmySet.add(\"gamma\");\nmySet.add(\"gamma\");\nmySet.add(\"delta\");\n\nfor(String currentItem : mySet) {\n System.out.println(currentItem);\n}\n</code></pre>\n\n<p>The loop declaration states: loop over mySet Set of Strings and store the current Set value <strong>in</strong> the currentItem variable. Notice that since this is a Set, duplicate String values are not stored.</p>\n\n<p>Output:</p>\n\n<pre><code>alpha\ndelta\nbeta\ngamma\n</code></pre>\n\n<p>Source: <a href=\"https://funnelgarden.com/java-for-loop/\" rel=\"noreferrer\">Loops in Java – Ultimate Guide</a></p>\n" }, { "answer_id": 50966962, "author": "Du-Lacoste", "author_id": 3600553, "author_profile": "https://Stackoverflow.com/users/3600553", "pm_score": 4, "selected": false, "text": "<p>Using older Java versions, including <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7\" rel=\"nofollow noreferrer\">Java 7</a>, you can use a <code>foreach</code> loop as follows.</p>\n<pre><code>List&lt;String&gt; items = new ArrayList&lt;&gt;();\nitems.add(&quot;A&quot;);\nitems.add(&quot;B&quot;);\nitems.add(&quot;C&quot;);\nitems.add(&quot;D&quot;);\nitems.add(&quot;E&quot;);\n\nfor(String item : items) {\n System.out.println(item);\n}\n</code></pre>\n<p>The following is the very latest way of using a <em>for each</em> loop in <a href=\"https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8\" rel=\"nofollow noreferrer\">Java 8</a> (loop a List with <code>forEach</code> + lambda expression or method reference).</p>\n<h3>Lambda</h3>\n<pre><code>// Output: A,B,C,D,E\nitems.forEach(item-&gt;System.out.println(item));\n</code></pre>\n<h3>Method reference</h3>\n<pre><code>// Output: A,B,C,D,E\nitems.forEach(System.out::println);\n</code></pre>\n<p>For more information, refer to <em>&quot;<a href=\"https://www.mkyong.com/java8/java-8-foreach-examples/\" rel=\"nofollow noreferrer\">Java 8 forEach examples</a>&quot;</em>.</p>\n" }, { "answer_id": 52098209, "author": "vivekkurien", "author_id": 3356847, "author_profile": "https://Stackoverflow.com/users/3356847", "pm_score": 4, "selected": false, "text": "<p>In Java 8, they introduced forEach. Using it List, Maps can be looped.</p>\n\n<p><strong>Loop a List using for each</strong></p>\n\n<pre><code>List&lt;String&gt; someList = new ArrayList&lt;String&gt;();\nsomeList.add(\"A\");\nsomeList.add(\"B\");\nsomeList.add(\"C\");\n\nsomeList.forEach(listItem -&gt; System.out.println(listItem))\n</code></pre>\n\n<p>or </p>\n\n<pre><code>someList.forEach(listItem-&gt; {\n System.out.println(listItem); \n});\n</code></pre>\n\n<p><strong>Loop a Map using for each</strong></p>\n\n<pre><code>Map&lt;String, String&gt; mapList = new HashMap&lt;&gt;();\n mapList.put(\"Key1\", \"Value1\");\n mapList.put(\"Key2\", \"Value2\");\n mapList.put(\"Key3\", \"Value3\");\n\nmapList.forEach((key,value)-&gt;System.out.println(\"Key: \" + key + \" Value : \" + value));\n</code></pre>\n\n<p>or</p>\n\n<pre><code>mapList.forEach((key,value)-&gt;{\n System.out.println(\"Key : \" + key + \" Value : \" + value);\n});\n</code></pre>\n" }, { "answer_id": 59667941, "author": "mightyWOZ", "author_id": 4413098, "author_profile": "https://Stackoverflow.com/users/4413098", "pm_score": 3, "selected": false, "text": "<p>As many of other answers correctly state, the <em>for each</em> loop is just syntactic sugar over the same old <em>for</em> loop and the compiler translates it to the same old <em>for</em> loop.</p>\n<p>javac (<a href=\"https://en.wikipedia.org/wiki/OpenJDK\" rel=\"nofollow noreferrer\">OpenJDK</a>) has a switch, <code>-XD-printflat</code>, which generates a Java file with all the syntactic sugar removed. The complete command looks like this:</p>\n<pre><code>javac -XD-printflat -d src/ MyFile.java\n\n//-d is used to specify the directory for output java file\n</code></pre>\n<h3>So let’s remove the syntactical sugar</h3>\n<p>To answer this question, I created a file and wrote two versions of <em>for each</em>, one with <em>array</em> and another with a <em>list</em>. My Java file looked like this:</p>\n<pre><code>import java.util.*;\n\npublic class Temp{\n\n private static void forEachArray(){\n int[] arr = new int[]{1,2,3,4,5};\n for(int i: arr){\n System.out.print(i);\n }\n }\n\n private static void forEachList(){\n List&lt;Integer&gt; list = Arrays.asList(1,2,3,4,5);\n for(Integer i: list){\n System.out.print(i);\n }\n }\n}\n</code></pre>\n<p>When I <code>compiled</code> this file with above switch, I got the following output.</p>\n<pre><code>import java.util.*;\n\npublic class Temp {\n\n public Temp() {\n super();\n }\n\n private static void forEachArray() {\n int[] arr = new int[]{1, 2, 3, 4, 5};\n for (/*synthetic*/ int[] arr$ = arr, len$ = arr$.length, i$ = 0; i$ &lt; len$; ++i$) {\n int i = arr$[i$];\n {\n System.out.print(i);\n }\n }\n }\n\n private static void forEachList() {\n List list = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5)});\n for (/*synthetic*/ Iterator i$ = list.iterator(); i$.hasNext(); ) {\n Integer i = (Integer)i$.next();\n {\n System.out.print(i);\n }\n }\n }\n}\n</code></pre>\n<p>You can see that along with the other syntactic sugar (Autoboxing), <em>for each</em> loops got changed to simple loops.</p>\n" }, { "answer_id": 65906872, "author": "nabayram", "author_id": 14692626, "author_profile": "https://Stackoverflow.com/users/14692626", "pm_score": 1, "selected": false, "text": "<p>I think this will work:</p>\n<pre><code>for (Iterator&lt;String&gt; i = someList.iterator(); i.hasNext(); ) {\n String x = i.next();\n System.out.println(x);\n}\n</code></pre>\n" }, { "answer_id": 66815146, "author": "Java-Dev", "author_id": 10428563, "author_profile": "https://Stackoverflow.com/users/10428563", "pm_score": 1, "selected": false, "text": "<p>The code would be:</p>\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\n\npublic class ForLoopDemo {\n\n public static void main(String[] args) {\n\n List&lt;String&gt; someList = new ArrayList&lt;String&gt;();\n\n someList.add(&quot;monkey&quot;);\n someList.add(&quot;donkey&quot;);\n someList.add(&quot;skeleton key&quot;);\n\n // Iteration using For Each loop\n System.out.println(&quot;Iteration using a For Each loop:&quot;);\n for (String item : someList) {\n System.out.println(item);\n }\n\n // Iteration using a normal For loop\n System.out.println(&quot;\\nIteration using normal For loop: &quot;);\n for (int index = 0; index &lt; someList.size(); index++) {\n System.out.println(someList.get(index));\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 71194990, "author": "IsraelCena", "author_id": 9877306, "author_profile": "https://Stackoverflow.com/users/9877306", "pm_score": 0, "selected": false, "text": "<p>Using <em>forEach</em>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int[] numbers = {1,2,3,4,5};\n\nArrays.stream(numbers).forEach(System.out::println);\n</code></pre>\n<p>Response:</p>\n<pre class=\"lang-none prettyprint-override\"><code>1\n2\n3\n4\n5\n\nThe process finished with exit code 0\n</code></pre>\n<p>PS: You need a Array (<code>int[] numbers</code>), and <code>import java.util.Arrays;</code></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5074/" ]
Consider: ``` List<String> someList = new ArrayList<String>(); // add "monkey", "donkey", "skeleton key" to someList ``` ``` for (String item : someList) { System.out.println(item); } ``` What would the equivalent `for` loop look like without using the *for each* syntax?
``` for (Iterator<String> i = someIterable.iterator(); i.hasNext();) { String item = i.next(); System.out.println(item); } ``` Note that if you need to use `i.remove();` in your loop, or access the actual iterator in some way, you cannot use the `for ( : )` idiom, since the actual iterator is merely inferred. As was noted by Denis Bueno, this code works for any object that implements the [`Iterable` interface](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html). Also, if the right-hand side of the `for (:)` idiom is an `array` rather than an `Iterable` object, the internal code uses an int index counter and checks against `array.length` instead. See the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2).
85,282
<p>In C# you can make a block inside of a method that is not attached to any other statement.</p> <pre><code> public void TestMethod() { { string x = "test"; string y = x; { int z = 42; int zz = z; } } } </code></pre> <p>This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block.</p> <p>Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings.</p>
[ { "answer_id": 85311, "author": "junkforce", "author_id": 2153, "author_profile": "https://Stackoverflow.com/users/2153", "pm_score": 1, "selected": false, "text": "<p>As far as I can see, it'd only be useful from an organizational standpoint. I can't really conceive of any logical value in doing that. Perhaps someone will have a proper example.</p>\n" }, { "answer_id": 85315, "author": "Ed Schwehm", "author_id": 1206, "author_profile": "https://Stackoverflow.com/users/1206", "pm_score": 5, "selected": true, "text": "<p>Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects.</p>\n\n<p><a href=\"https://stackoverflow.com/users/7093/ray-hayes\">Ray Hayes</a> points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit. </p>\n" }, { "answer_id": 85320, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 0, "selected": false, "text": "<p>One reason for doing this is that the variables 'z' and 'zz' would not be available to code below the end of that inner block. When you do this in Java, the JVM pushes a stack frame for the inner code, and those values can live on the stack. When the code exits the block, the stack frame is popped and those values go away. Depending on the types involved, this can save you from having to use heap and/or garbage collection.</p>\n" }, { "answer_id": 85323, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 2, "selected": false, "text": "<p>It's a by-product of a the parser rule that statement is either a simple statement or a block. i.e. a block can be used wherever a single statement can.</p>\n\n<p>e.g.</p>\n\n<pre><code>if (someCondition)\n SimpleStatement();\n\nif (SomeCondition)\n{\n BlockOfStatements();\n}\n</code></pre>\n\n<p>Others have pointed out that variable declarations are in scope until the end of the containing block. It's good for temporary vars to have a short scope, but I've never had to use a block on it's own to limit the scope of a variable. Sometimes you use a block underneath a \"using\" statement for that.</p>\n\n<p>So generally it's not valuable.</p>\n" }, { "answer_id": 85355, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 0, "selected": false, "text": "<p>In C# -- like c/c++/java -- braces denote a scope. This dictates the lifetime of a variable. As the closing brace is reached, the variable becomes immediately available for a garbage collection. In c++, it would cause a class's destructor to be called if the var represented an instance. </p>\n\n<p>As for usage, the only possible use is to free up a large object but tbh, setting it to null would have the same effect. I suspect the former usage is probably just to keep c++ programmers moving to managed code somewhat in familiar and comfortable territory. If really want to call a \"destructor\" in c#, you typically implement the IDisposable interface and use the \"using (var) {...}\" pattern.</p>\n\n<p>Oisin</p>\n" }, { "answer_id": 85361, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 0, "selected": false, "text": "<p>Even if it was actually useful for any reason (e.g. variable scope control), I would discourage you from such construct from the standpoint of good old code readibility.</p>\n" }, { "answer_id": 85433, "author": "Tim Erickson", "author_id": 8787, "author_profile": "https://Stackoverflow.com/users/8787", "pm_score": 0, "selected": false, "text": "<p>There is no value to this other than semantic and for scope and garbage collection, none of which is significant in this limited example. If you think it makes the code clearer, for yourself and/or others, then you certainly could use it. However, the more accepted convention for semantic clarification in code generally would use line breaks only with option in-line comments:</p>\n\n<pre><code>public void TestMethod()\n{\n //do something with some strings\n string x = \"test\";\n string y = x;\n\n //do something else with some ints\n int z = 42;\n int zz = z;\n}\n</code></pre>\n" }, { "answer_id": 86275, "author": "BlackTigerX", "author_id": 8411, "author_profile": "https://Stackoverflow.com/users/8411", "pm_score": 2, "selected": false, "text": "<p>An example would be if you wanted to reuse a variable name, normally you can't reuse variable names\nThis is not valid</p>\n\n<pre><code> int a = 10;\n Console.WriteLine(a);\n\n int a = 20;\n Console.WriteLine(a);\n</code></pre>\n\n<p>but this is:</p>\n\n<pre><code> {\n int a = 10;\n Console.WriteLine(a);\n }\n {\n int a = 20;\n Console.WriteLine(a);\n }\n</code></pre>\n\n<p>The only thing I can think of right now, is for example if you were processing some large object, and you extracted some information out of it, and after that you were going to perform a bunch of operations, you could put the large object processing in a block, so that it goes out of scope, then continue with the other operations</p>\n\n<pre><code> {\n //Process a large object and extract some data\n }\n //large object is out of scope here and will be garbage collected, \n //you can now perform other operations with the extracted data that can take a long time, \n //without holding the large object in memory\n\n //do processing with extracted data\n</code></pre>\n" }, { "answer_id": 86351, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "<p>This allows you to create a scope block anywhere. It's not that useful on it's own, but can make logic simpler:</p>\n\n<pre><code>switch( value )\n{\n case const1: \n int i = GetValueSomeHow();\n //do something\n return i.ToString();\n\n case const2:\n int i = GetADifferentValue();\n //this will throw an exception - i is already declared\n ...\n</code></pre>\n\n<p>In C# we can use a scope block so that items declared under each case are only in scope in that case:</p>\n\n<pre><code>switch( value )\n{\n case const1: \n {\n int i = GetValueSomeHow();\n //do something\n return i.ToString();\n }\n\n case const2:\n {\n int i = GetADifferentValue();\n //no exception now\n return SomeFunctionOfInt( i );\n }\n ...\n</code></pre>\n\n<p>This can also work for gotos and labels, not that you often use them in C#.</p>\n" }, { "answer_id": 13864283, "author": "Servy", "author_id": 1159478, "author_profile": "https://Stackoverflow.com/users/1159478", "pm_score": 1, "selected": false, "text": "<p>The one practical reason for it to exist is if you want to restrict the scope of some variable when there is no compelling need to introduce any other reason for the block. In actual practice, this is virtually never useful.</p>\n\n<p>Personally, my guess is that from a language/compiler point of view it's easier to say that you can put a block anywhere a statement is expected, and they simply didn't go out of their way to prevent you from using it without an if/for/method declaration/ etc.</p>\n\n<p>Consider the beginning <a href=\"http://ericlippert.com/2012/12/04/why-are-braces-required/\" rel=\"nofollow\">this recent blog post</a> from Eric Lippert. An <code>if</code> statement isn't followed by either a single statement or a number of statements enclosed on curly braces, it's simply followed by a single statement. Anytime you enclose 0 to N statements in curly braces you make that section of code equivalent (from the point of view of the language parser) one statement. This same practice applies to all looping structures as well, although as the main point of the blog post explains, it doesn't apply to try/catch/finally blocks.</p>\n\n<p>When addressing blocks from that point of view the question then becomes, \"Is there a compelling reason to prevent blocks from being used anywhere a single statement could be used?\" and the answer is, \"No\".</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3289/" ]
In C# you can make a block inside of a method that is not attached to any other statement. ``` public void TestMethod() { { string x = "test"; string y = x; { int z = 42; int zz = z; } } } ``` This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block. Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings.
Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects. [Ray Hayes](https://stackoverflow.com/users/7093/ray-hayes) points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit.
85,353
<p>What is the best (or as good as possible) general SVN ignore pattern to use? </p> <p>There are a number of different IDE, editor, compiler, plug-in, platform, etc. specific files and some file types that "overlap" (i.e. desirable for some types projects and not for others). </p> <p><strong>There are however, a large number of file types that you just never want included in source control automatically regardless the specifics of your development environment.</strong></p> <p>The answer to this question would serve as a good starting point for any project - only requiring them to add the few environment specific items they need. It could be adapted for other Version Control Systems (VCS) as well.</p>
[ { "answer_id": 85371, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 3, "selected": false, "text": "<p>Used for my Visual Studio projects</p>\n\n<pre><code>*/bin */obj *.user *.suo\n</code></pre>\n\n<p>You can expand more file types from there.</p>\n" }, { "answer_id": 85377, "author": "Zach Burlingame", "author_id": 2233, "author_profile": "https://Stackoverflow.com/users/2233", "pm_score": 9, "selected": true, "text": "<p>I'll add my own two cents to this question:</p>\n\n<p>I use the following SVN ignore pattern with TortoiseSVN and Subversion CLI for native C++, C#/VB.NET, and PERL projects on both Windows and Linux platforms. It works well for me! </p>\n\n<p>Formatted for copy and paste:</p>\n\n<pre>\n*.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk *.msi* .res *.pch *.suo *.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user *.generated.cs\n</pre>\n\n<p>Formatted for readability:</p>\n\n<pre>\n*.o *.lo *.la #*# .*.rej *.rej\n.*~ *~ .#* .DS_Store thumbs.db \nThumbs.db *.bak *.class *.exe *.dll\n*.mine *.obj *.ncb *.lib *.log \n*.idb *.pdb *.ilk *.msi* .res *.pch *.suo \n*.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs \nrelease Release debug Debug\nignore Ignore bin Bin obj Obj\n*.csproj.user *.user\n*.generated.cs\n</pre>\n" }, { "answer_id": 85390, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 4, "selected": false, "text": "<p>Windows users might want to throw in desktop.ini and thumbs.db.</p>\n" }, { "answer_id": 85406, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>Visual Studio (VC++) users definitely need to exclude the <strong>.ncb</strong> files</p>\n" }, { "answer_id": 85419, "author": "petr k.", "author_id": 15497, "author_profile": "https://Stackoverflow.com/users/15497", "pm_score": 4, "selected": false, "text": "<p>Every time I come across a file I generally do not want in the repository, I update the pattern. I believe there is no \"best\" pattern - it always <strong>depends on the language and environment</strong> you develop in. </p>\n\n<p>Moreover, you're not very likely to think of all the possible \"ignorable\" filetypes - you'll always encounter a filetype you simply forgot to include. Thats why updating the pattern as you go works the best.</p>\n" }, { "answer_id": 85422, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 1, "selected": false, "text": "<p>Mac users probably want to throw in .DS_Store. In addition, if there are dev's using Emacs or Vim, you probably want to add ~<em>~ and #</em>#.</p>\n" }, { "answer_id": 85429, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 0, "selected": false, "text": "<p>The pattern depends on which operating system you're using.</p>\n\n<p>On Linux, you'll want to block **.o*, **.so*, **.a*, and **.la* to begin with. You may also want to block **~* (backup file from editing) and #*# (emacs backup from a crash).</p>\n\n<p>On Windows, you'll want **.obj*, **.lib*, and **.dll* at the very least.</p>\n\n<p>Any other files you need to block depend on your IDE, editor, and compiler.</p>\n" }, { "answer_id": 85440, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 1, "selected": false, "text": "<p>For Eclipse, I use:</p>\n\n<pre><code>bin\n.*\n</code></pre>\n\n<p>.* gets all the project configuration. You almost never want to check in a 'hidden' directory or file, but if it comes up, you can still svn add it.</p>\n" }, { "answer_id": 186509, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "<p>Since you may be using third party libs and dll's as part of the project(s) then I don't see the wisdom in blocking *.lib and *.dll from the repository. These are the things that are meant to be stored in the repository.</p>\n" }, { "answer_id": 843183, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Based on Burly's ignore pattern, I have added ReSharper to the ignore list</p>\n\n<p>Formatted for copy and paste:</p>\n\n<pre><code>*.o *.lo .la ## .*.rej .rej .~ ~ .# .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk .msi .res *.pch *.suo *.exp ~. cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user _ReSharper.* *.resharper.user\n</code></pre>\n\n<p>Formatted for readability:</p>\n\n<pre><code>*.o *.lo .la ## .*.rej .rej .~ ~ .# .DS_Store thumbs.db Thumbs.db *.bak\n*.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk .msi .res *.pch *.suo *.exp ~. cvs\nCVS .CVS .cvs release Release debug\nDebug ignore Ignore bin Bin obj Obj\n*.csproj.user *.user _ReSharper.* *.resharper.user\n</code></pre>\n" }, { "answer_id": 1815482, "author": "Dima Pasko", "author_id": 23731, "author_profile": "https://Stackoverflow.com/users/23731", "pm_score": 5, "selected": false, "text": "<p>My ignore pattern for Visual Studio:</p>\n\n<pre>\n*/bin */obj */Release */Debug *.suo *.err *.log *.obj *.bin *.dll *.exe *.LOG *.user *.pdb [tT]emp [tT]empPE Ankh.Load thumbs.db *.resharper *.vspscc *.vsssccc *.scc */_ReSharper* */_ReSharper.* bin obj *.resharperoptions *.db *.bak *_ReSharper* *.snk logs output TestResults *.crunchsolution.* *.crunchproject.*\n</pre>\n\n<p>Formatted for readability</p>\n\n<pre>\n*/bin */obj */Release */Debug *.suo *.err *.log *.obj *.bin *.dll *.exe \n*.LOG *.user *.pdb [tT]emp [tT]empPE Ankh.Load thumbs.db *.resharper \n*.vspscc *.vsssccc *.scc */_ReSharper* */_ReSharper.* bin obj \n*.resharperoptions *.db *.bak *_ReSharper* *.snk logs output TestResults \n*.crunchsolution.* *.crunchproject.*\n</pre>\n" }, { "answer_id": 3082358, "author": "Hammad Rajjoub", "author_id": 362024, "author_profile": "https://Stackoverflow.com/users/362024", "pm_score": 0, "selected": false, "text": "<p>Gotta add Resharper to the mix if you use one.</p>\n\n<p>another one to look out for is Ankh*.*</p>\n" }, { "answer_id": 6902355, "author": "Dalmas", "author_id": 533552, "author_profile": "https://Stackoverflow.com/users/533552", "pm_score": 1, "selected": false, "text": "<p>Visual Studio 2010 users should add <code>ipch</code> (a folder which contains C++ precompiled headers) and <code>*.sdf</code> (huge files used by intellisense for any kind of project).</p>\n" }, { "answer_id": 7764856, "author": "Richard Dingwall", "author_id": 91551, "author_profile": "https://Stackoverflow.com/users/91551", "pm_score": 0, "selected": false, "text": "<p>Don't forget <a href=\"http://www.ncrunch.net\" rel=\"nofollow\">NCrunch</a> temporary files:</p>\n\n<pre><code>*.crunchsolution.* *.crunchproject.*\n</code></pre>\n" }, { "answer_id": 17672499, "author": "Holger Bille", "author_id": 1967424, "author_profile": "https://Stackoverflow.com/users/1967424", "pm_score": 0, "selected": false, "text": "<p>And core dumps (cygwin, linux)</p>\n\n<pre><code>*.stackdump core.*\n</code></pre>\n" }, { "answer_id": 39466037, "author": "koppor", "author_id": 873282, "author_profile": "https://Stackoverflow.com/users/873282", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://www.gitignore.io/\" rel=\"nofollow\">gitignore.io</a> provides configurable patterns for git. They provide a readable list, which you need to reformat for SVN.</p>\n\n<p>For instance, <a href=\"https://www.gitignore.io/api/microsoftoffice%2Cwindows\" rel=\"nofollow\">requesting MicrosoftOffice and Windows</a> returns</p>\n\n<pre><code># Created by https://www.gitignore.io/api/microsoftoffice,windows\n\n### MicrosoftOffice ###\n*.tmp\n\n# Word temporary\n~$*.doc*\n\n# Excel temporary\n~$*.xls*\n\n# Excel Backup File\n*.xlk\n\n# PowerPoint temporary\n~$*.ppt*\n\n# Visio autosave temporary files\n*.~vsdx\n\n\n### Windows ###\n# Windows image file caches\nThumbs.db\nehthumbs.db\n\n# Folder config file\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n</code></pre>\n" }, { "answer_id": 39466162, "author": "koppor", "author_id": 873282, "author_profile": "https://Stackoverflow.com/users/873282", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://www.gitignore.io/\" rel=\"nofollow\">gitignore.io</a> provides configurable patterns for git. They provide a readable list, which you need to reformat for SVN.</p>\n\n<p>For instance, <a href=\"https://www.gitignore.io/api/microsoftoffice%2Cwindows\" rel=\"nofollow\">requesting MicrosoftOffice and Windows</a> returns</p>\n\n<pre><code># Created by https://www.gitignore.io/api/microsoftoffice,windows\n\n### MicrosoftOffice ###\n*.tmp\n\n# Word temporary\n~$*.doc*\n\n# Excel temporary\n~$*.xls*\n\n# Excel Backup File\n*.xlk\n\n# PowerPoint temporary\n~$*.ppt*\n\n# Visio autosave temporary files\n*.~vsdx\n\n\n### Windows ###\n# Windows image file caches\nThumbs.db\nehthumbs.db\n\n# Folder config file\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n</code></pre>\n\n<p>It seems that it can be directly used as <code>svn:global-ignore</code></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2233/" ]
What is the best (or as good as possible) general SVN ignore pattern to use? There are a number of different IDE, editor, compiler, plug-in, platform, etc. specific files and some file types that "overlap" (i.e. desirable for some types projects and not for others). **There are however, a large number of file types that you just never want included in source control automatically regardless the specifics of your development environment.** The answer to this question would serve as a good starting point for any project - only requiring them to add the few environment specific items they need. It could be adapted for other Version Control Systems (VCS) as well.
I'll add my own two cents to this question: I use the following SVN ignore pattern with TortoiseSVN and Subversion CLI for native C++, C#/VB.NET, and PERL projects on both Windows and Linux platforms. It works well for me! Formatted for copy and paste: ``` *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk *.msi* .res *.pch *.suo *.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user *.generated.cs ``` Formatted for readability: ``` *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk *.msi* .res *.pch *.suo *.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user *.generated.cs ```
85,373
<p>In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year?</p> <p>Let's say that I have a date of <strong>2008-09-17 12:56:53.430</strong>, then the output of flooring should be:</p> <ul> <li>Year: 2008-01-01 00:00:00.000</li> <li>Month: 2008-09-01 00:00:00.000</li> <li>Day: 2008-09-17 00:00:00.000</li> <li>Hour: 2008-09-17 12:00:00.000</li> <li>Minute: 2008-09-17 12:56:00.000</li> <li>Second: 2008-09-17 12:56:53.000</li> </ul>
[ { "answer_id": 85379, "author": "Portman", "author_id": 1690, "author_profile": "https://Stackoverflow.com/users/1690", "pm_score": 8, "selected": true, "text": "<p>The key is to use <a href=\"http://msdn.microsoft.com/en-us/library/ms186819.aspx\" rel=\"noreferrer\">DATEADD</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms189794.aspx\" rel=\"noreferrer\">DATEDIFF</a> along with the appropriate SQL timespan enumeration.</p>\n\n<pre><code>declare @datetime datetime;\nset @datetime = getdate();\nselect @datetime;\nselect dateadd(year,datediff(year,0,@datetime),0);\nselect dateadd(month,datediff(month,0,@datetime),0);\nselect dateadd(day,datediff(day,0,@datetime),0);\nselect dateadd(hour,datediff(hour,0,@datetime),0);\nselect dateadd(minute,datediff(minute,0,@datetime),0);\nselect dateadd(second,datediff(second,'2000-01-01',@datetime),'2000-01-01');\nselect dateadd(week,datediff(week,0,@datetime),-1); --Beginning of week is Sunday\nselect dateadd(week,datediff(week,0,@datetime),0); --Beginning of week is Monday\n</code></pre>\n\n<p>Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor.</p>\n" }, { "answer_id": 85405, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms187928.aspx\" rel=\"nofollow noreferrer\">CONVERT()</a> function can do this as well, depending on what style you use.</p>\n" }, { "answer_id": 85607, "author": "typicalrunt", "author_id": 13996, "author_profile": "https://Stackoverflow.com/users/13996", "pm_score": 1, "selected": false, "text": "<p>Too bad it's not Oracle, or else you could use trunc() or to_char().</p>\n\n<p>But I had similar issues with SQL Server and used the CONVERT() and DateDiff() methods, as referenced <a href=\"http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=54594\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 86499, "author": "Chris Wuestefeld", "author_id": 10082, "author_profile": "https://Stackoverflow.com/users/10082", "pm_score": 5, "selected": false, "text": "<p>In SQL Server here's a little trick to do that:</p>\n\n<pre><code>SELECT CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)\n</code></pre>\n\n<p>You cast the DateTime into a float, which represents the Date as the integer portion and the Time as the fraction of a day that's passed. Chop off that decimal portion, then cast that back to a DateTime, and you've got midnight at the beginning of that day.</p>\n\n<p>This is probably more efficient than all the DATEADD and DATEDIFF stuff. It's certainly way easier to type.</p>\n" }, { "answer_id": 561614, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Since PostgreSQL is also a \"SQL Server\", I'll mention </p>\n\n<pre><code>date_trunc()\n</code></pre>\n\n<p>Which does exactly what you're asking gracefully.</p>\n\n<p>For example:</p>\n\n<pre>\n select date_trunc('hour',current_timestamp);\n date_trunc\n------------------------\n 2009-02-18 07:00:00-08\n(1 row)\n\n</pre>\n" }, { "answer_id": 10212540, "author": "Moe Cazzell", "author_id": 1341767, "author_profile": "https://Stackoverflow.com/users/1341767", "pm_score": 4, "selected": false, "text": "<p>Expanding upon the Convert/Cast solution, in Microsoft SQL Server 2008 you can do the following:</p>\n\n<pre><code>cast(cast(getdate() as date) as datetime)\n</code></pre>\n\n<p>Just replace <code>getdate()</code> with any column which is a datetime.</p>\n\n<p>There are no strings involved in this conversion.</p>\n\n<p>This is ok for ad-hoc queries or updates, but for key joins or heavily used processing it may be better to handle the conversion within the processing or redefine the tables to have appropriate keys and data.</p>\n\n<p>In 2005, you can use the messier floor: <code>cast(floor(cast(getdate() as float)) as datetime)</code></p>\n\n<p>I don't think that uses string conversion either, but I can't speak to comparing actual efficiency versus armchair estimates.</p>\n" }, { "answer_id": 17860749, "author": "Dan Atkinson", "author_id": 31532, "author_profile": "https://Stackoverflow.com/users/31532", "pm_score": 3, "selected": false, "text": "<p>I've used <a href=\"https://stackoverflow.com/a/85379/31532\">@Portman's answer</a> many times over the years as a reference when flooring dates and have moved its working into a function which you may find useful.</p>\n\n<p>I make no claims to its performance and merely provide it as a tool for the user.</p>\n\n<p><strong>I ask that, if you do decide to upvote this answer, please also upvote <a href=\"https://stackoverflow.com/a/85379/31532\">@Portman's answer</a>, as my code is a derivative of his.</strong></p>\n\n<pre><code>IF OBJECT_ID('fn_FloorDate') IS NOT NULL DROP FUNCTION fn_FloorDate\nSET ANSI_NULLS OFF\nGO\nSET QUOTED_IDENTIFIER ON\nGO\nCREATE FUNCTION [dbo].[fn_FloorDate] (\n @Date DATETIME = NULL,\n @DatePart VARCHAR(6) = 'day'\n)\nRETURNS DATETIME\nAS\nBEGIN\n IF (@Date IS NULL)\n SET @Date = GETDATE();\n\n RETURN\n CASE\n WHEN LOWER(@DatePart) = 'year' THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0)\n WHEN LOWER(@DatePart) = 'month' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0)\n WHEN LOWER(@DatePart) = 'day' THEN DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)\n WHEN LOWER(@DatePart) = 'hour' THEN DATEADD(HOUR, DATEDIFF(HOUR, 0, @Date), 0)\n WHEN LOWER(@DatePart) = 'minute' THEN DATEADD(MINUTE, DATEDIFF(MINUTE, 0, @Date), 0)\n WHEN LOWER(@DatePart) = 'second' THEN DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', @Date), '2000-01-01')\n ELSE DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)\n END;\nEND\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>DECLARE @date DATETIME;\nSET @date = '2008-09-17 12:56:53.430';\n\nSELECT\n @date AS [Now],--2008-09-17 12:56:53.430\n dbo.fn_FloorDate(@date, 'year') AS [Year],--2008-01-01 00:00:00.000\n dbo.fn_FloorDate(default, default) AS [NoParams],--2013-11-05 00:00:00.000\n dbo.fn_FloorDate(@date, default) AS [ShouldBeDay],--2008-09-17 00:00:00.000\n dbo.fn_FloorDate(@date, 'month') AS [Month],--2008-09-01 00:00:00.000\n dbo.fn_FloorDate(@date, 'day') AS [Day],--2008-09-17 00:00:00.000\n dbo.fn_FloorDate(@date, 'hour') AS [Hour],--2008-09-17 12:00:00.000\n dbo.fn_FloorDate(@date, 'minute') AS [Minute],--2008-09-17 12:56:00.000\n dbo.fn_FloorDate(@date, 'second') AS [Second];--2008-09-17 12:56:53.000\n</code></pre>\n" }, { "answer_id": 26166191, "author": "Sean", "author_id": 4103350, "author_profile": "https://Stackoverflow.com/users/4103350", "pm_score": 1, "selected": false, "text": "<p>There are several ways to skin this cat =)</p>\n\n<pre><code>select convert(datetime,convert(varchar,CURRENT_TIMESTAMP,101))\n</code></pre>\n" }, { "answer_id": 37059540, "author": "pinaldave", "author_id": 892707, "author_profile": "https://Stackoverflow.com/users/892707", "pm_score": 0, "selected": false, "text": "<p>DateAdd along with DateDiff can help to do many different tasks. For example, you can find last day of any month as well can find last day of previous or next month. </p>\n\n<pre><code>----Last Day of Previous Month\nSELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))\nLastDay_PreviousMonth\n----Last Day of Current Month\nSELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))\nLastDay_CurrentMonth\n----Last Day of Next Month\nSELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))\nLastDay_NextMonth\n</code></pre>\n\n<p><a href=\"http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/\" rel=\"nofollow\">Source</a></p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1690/" ]
In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year? Let's say that I have a date of **2008-09-17 12:56:53.430**, then the output of flooring should be: * Year: 2008-01-01 00:00:00.000 * Month: 2008-09-01 00:00:00.000 * Day: 2008-09-17 00:00:00.000 * Hour: 2008-09-17 12:00:00.000 * Minute: 2008-09-17 12:56:00.000 * Second: 2008-09-17 12:56:53.000
The key is to use [DATEADD](http://msdn.microsoft.com/en-us/library/ms186819.aspx) and [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794.aspx) along with the appropriate SQL timespan enumeration. ``` declare @datetime datetime; set @datetime = getdate(); select @datetime; select dateadd(year,datediff(year,0,@datetime),0); select dateadd(month,datediff(month,0,@datetime),0); select dateadd(day,datediff(day,0,@datetime),0); select dateadd(hour,datediff(hour,0,@datetime),0); select dateadd(minute,datediff(minute,0,@datetime),0); select dateadd(second,datediff(second,'2000-01-01',@datetime),'2000-01-01'); select dateadd(week,datediff(week,0,@datetime),-1); --Beginning of week is Sunday select dateadd(week,datediff(week,0,@datetime),0); --Beginning of week is Monday ``` Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor.
85,427
<p>Is the documentation for Rich Edit Controls really as bad (wrong?) as it seems to be? Right now I'm manually calling LoadLibrary("riched20.dll") in order to get a Rich Edit Control to show up. The documentation for Rich Edit poorly demonstrates this in the first code sample for using Rich Edit controls.</p> <p>It talks about calling InitCommonControlsEx() to add visual styles, but makes no mention of which flags to pass in.</p> <p>Is there a better way to load a Rich Edit control?</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx</a></p> <p>Here's the only code I could write to make it work:</p> <pre><code>#include "Richedit.h" #include "commctrl.h" INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_USEREX_CLASSES; //Could be 0xFFFFFFFF and it still wouldn't work InitCommonControlsEx(&amp;icex); //Does nothing for Rich Edit controls LoadLibrary("riched20.dll"); //Manually? For real? hWndRichEdit = CreateWindowEx( ES_SUNKEN, RICHEDIT_CLASS, "", WS_BORDER | WS_VISIBLE | WS_CHILD, 2, 2, 100, 24, hWnd, (HMENU) ID_RICH_EDIT, hInst, NULL); </code></pre>
[ { "answer_id": 85497, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 1, "selected": false, "text": "<p>Isn't there an import library (maybe riched20.lib) that you can link to. Then you won't have to load it \"manually\" at run time. That's how all the standard controls work. VS automatically adds a reference to user32.lib when you create a project.</p>\n" }, { "answer_id": 85501, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 0, "selected": false, "text": "<p>I think you have to call CoInitializeEx before you create any of the common controls.</p>\n\n<p>The LoadLibrary is not needed. If you link with the correct .lib file the exe-loader will take care of such details for you. </p>\n" }, { "answer_id": 85505, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 3, "selected": true, "text": "<p>Using MFC, RichEdit controls just work.</p>\n\n<p>Loading with InitCommonControlsEx() - ICC_USEREX_CLASSES doesn't load RichEdit AFAIK, you don't need it as it only does the 'standard' common controls, which don't include richedit. Apparently you only need to call this to enable 'visual styles' in Windows, not to get RichEdits working.</p>\n\n<p>If you're using 2008, you want to include Msftedit.dll and use the MSFTEDIT_CLASS instead (MS are rubbish for backward compatibilty sometimes).</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx#creating_re_control\" rel=\"nofollow noreferrer\">docs</a> do suggest you're doing it right for Win32 programming.</p>\n" }, { "answer_id": 85671, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": false, "text": "<p>Many years ago, I ran into this same issue, and yes, the answer was to load the .dll manually. The reason, as far as I can remember, is that the RichEdit window class is registered in DllMain of riched20.dll.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16408/" ]
Is the documentation for Rich Edit Controls really as bad (wrong?) as it seems to be? Right now I'm manually calling LoadLibrary("riched20.dll") in order to get a Rich Edit Control to show up. The documentation for Rich Edit poorly demonstrates this in the first code sample for using Rich Edit controls. It talks about calling InitCommonControlsEx() to add visual styles, but makes no mention of which flags to pass in. Is there a better way to load a Rich Edit control? <http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx> Here's the only code I could write to make it work: ``` #include "Richedit.h" #include "commctrl.h" INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_USEREX_CLASSES; //Could be 0xFFFFFFFF and it still wouldn't work InitCommonControlsEx(&icex); //Does nothing for Rich Edit controls LoadLibrary("riched20.dll"); //Manually? For real? hWndRichEdit = CreateWindowEx( ES_SUNKEN, RICHEDIT_CLASS, "", WS_BORDER | WS_VISIBLE | WS_CHILD, 2, 2, 100, 24, hWnd, (HMENU) ID_RICH_EDIT, hInst, NULL); ```
Using MFC, RichEdit controls just work. Loading with InitCommonControlsEx() - ICC\_USEREX\_CLASSES doesn't load RichEdit AFAIK, you don't need it as it only does the 'standard' common controls, which don't include richedit. Apparently you only need to call this to enable 'visual styles' in Windows, not to get RichEdits working. If you're using 2008, you want to include Msftedit.dll and use the MSFTEDIT\_CLASS instead (MS are rubbish for backward compatibilty sometimes). The [docs](http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx#creating_re_control) do suggest you're doing it right for Win32 programming.
85,450
<p>I have a SQL Server 2005 machine with a JDE DB2 set up as a linked server.</p> <p>For some reason the performance of any queries from this box to the db2 box are horrible.</p> <p>For example. The following takes 7 mins to run from Management Studio</p> <pre><code>SELECT * FROM F42119 WHERE SDUPMJ &gt;= 107256 </code></pre> <p>Whereas it takes seconds to run in iSeries Navigator</p> <p>Any thoughts? I'm assuming some config issue.</p>
[ { "answer_id": 88059, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>My first thought would go to the drivers. Years ago I had to link DB2 to SQL Server 2000 and it was extremely difficult to find the correct combination of drivers and setup parameters that would work... </p>\n\n<p>So maybe I'm biased because of that, but I would try upgrading or downgrading the driver or changing the setup so that the DB2 driver can run INPROC (if it's not already doing so).</p>\n" }, { "answer_id": 96649, "author": "Chad Braun-Duin", "author_id": 5458, "author_profile": "https://Stackoverflow.com/users/5458", "pm_score": 1, "selected": false, "text": "<p>It might be a memory issue on your SQL Server machine. I recently learned that linked server queries use memory allocation by the OS. Whereas native SQL Server queries use memory pre-allocated by SQL Server. If your SQL Server machine is configured to use 90% or more of the server's memory, I would scale that back a bit. Maybe 60% is the right place to be.</p>\n\n<p>Another thing to check is the SQL Server processor priority. Make sure \"Boost SQL Server priority\" is not enabled.</p>\n\n<p>I assume you are going through ODBC for access. Remember that you are not writing native db2 queries here, but instead ODBC sql queries. If you only need read-only data, you may want to try configuring your ODBC datasource to read-only mode (if that is an option).</p>\n" }, { "answer_id": 96764, "author": "K Richard", "author_id": 16771, "author_profile": "https://Stackoverflow.com/users/16771", "pm_score": 0, "selected": false, "text": "<p>I've had several issues with DB2 as a linked a server. I do not know if it will address your problems, but here is what fixed mine:</p>\n\n<p>1) Enabled lazy close support and pre-fetch during EXECUTE in the ODBC settings\n2) Add \"FOR FETCH ONLY\" on all selects\n3) Query using the SELECT * FROM OPENROWSET(LinkedServerName, 'SQL Command') method</p>\n" }, { "answer_id": 245205, "author": "Bob", "author_id": 32224, "author_profile": "https://Stackoverflow.com/users/32224", "pm_score": 3, "selected": false, "text": "<p>In certain searches SQL Server will decide to pull the entire table down to itself and sort and search the data within SQL Server instead of sending the query to the remote server. This is usually a problem with collation settings. </p>\n\n<p>Make sure the provider has the following options set:\nData Access,\nCollation Compatible,\nUse Remote Collation</p>\n\n<p>Then create a new Linked Server using the provider and select the following provider options\nDynamic Parameters,\nNested Queries,\nAllow In Process</p>\n\n<p>After setting the options change the query slightly to get a new query plan.</p>\n" }, { "answer_id": 245231, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 1, "selected": false, "text": "<p>In a project with DB2 integration, I replaced every query via direct select or view by stored procedures calling the OPENQUERY function. </p>\n\n<p>My interpretation is that SqlServer fetches the whole table before applying the WHERE conditions, whereas OPENQUERY passes the SQL statement directly to the db driver.</p>\n\n<p>Anyway, performance was acceptable after the modifications.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a SQL Server 2005 machine with a JDE DB2 set up as a linked server. For some reason the performance of any queries from this box to the db2 box are horrible. For example. The following takes 7 mins to run from Management Studio ``` SELECT * FROM F42119 WHERE SDUPMJ >= 107256 ``` Whereas it takes seconds to run in iSeries Navigator Any thoughts? I'm assuming some config issue.
In certain searches SQL Server will decide to pull the entire table down to itself and sort and search the data within SQL Server instead of sending the query to the remote server. This is usually a problem with collation settings. Make sure the provider has the following options set: Data Access, Collation Compatible, Use Remote Collation Then create a new Linked Server using the provider and select the following provider options Dynamic Parameters, Nested Queries, Allow In Process After setting the options change the query slightly to get a new query plan.
85,451
<p>Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?</p> <p>for example:</p> <pre><code>start = time.clock() ... do something elapsed = (time.clock() - start) </code></pre> <p>vs.</p> <pre><code>start = time.time() ... do something elapsed = (time.time() - start) </code></pre>
[ { "answer_id": 85480, "author": "user15910", "author_id": 15910, "author_profile": "https://Stackoverflow.com/users/15910", "pm_score": 4, "selected": false, "text": "<p>Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provides NO accuracy because it may manage CPU time. </p>\n" }, { "answer_id": 85489, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p><code>clock()</code> -> floating point number</p>\n\n<p>Return the CPU time or real time since the start of the process or since\nthe first call to <code>clock()</code>. This has as much precision as the system\nrecords.</p>\n\n<p><code>time()</code> -> floating point number</p>\n\n<p>Return the current time in seconds since the Epoch.\nFractions of a second may be present if the system clock provides them.</p>\n\n<p>Usually <code>time()</code> is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time)</p>\n" }, { "answer_id": 85511, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": false, "text": "<p>The short answer is: most of the time <code>time.clock()</code> will be better.\nHowever, if you're timing some hardware (for example some algorithm you put in the GPU), then <code>time.clock()</code> will get rid of this time and <code>time.time()</code> is the only solution left.</p>\n\n<p>Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, ...), this is worse with <code>time.time()</code> but exists also with <code>time.clock()</code>, so you should never run one timing test only, but always run a series of test and look at mean/variance of the times.</p>\n" }, { "answer_id": 85529, "author": "Babak", "author_id": 4676, "author_profile": "https://Stackoverflow.com/users/4676", "pm_score": 2, "selected": false, "text": "<p>Short answer: use <strong>time.clock()</strong> for timing in Python.</p>\n\n<p>On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number.</p>\n\n<p>time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value.</p>\n" }, { "answer_id": 85533, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 7, "selected": false, "text": "<p>As of 3.3, <a href=\"https://docs.python.org/3/library/time.html#time.clock\" rel=\"noreferrer\"><em>time.clock()</em> is deprecated</a>, and it's suggested to use <strong><a href=\"https://docs.python.org/3/library/time.html#time.process_time\" rel=\"noreferrer\">time.process_time()</a></strong> or <strong><a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"noreferrer\">time.perf_counter()</a></strong> instead.</p>\n\n<p>Previously in 2.7, according to the <strong><a href=\"https://docs.python.org/2.7/library/time.html#time.clock\" rel=\"noreferrer\">time module docs</a></strong>:</p>\n\n<blockquote>\n <p><strong>time.clock()</strong></p>\n \n <p>On Unix, return the current processor time as a floating point number\n expressed in seconds. The precision, and in fact the very definition\n of the meaning of “processor time”, depends on that of the C function\n of the same name, but in any case, <strong>this is the function to use for\n benchmarking Python or timing algorithms.</strong></p>\n \n <p>On Windows, this function returns wall-clock seconds elapsed since the\n first call to this function, as a floating point number, based on the\n Win32 function QueryPerformanceCounter(). The resolution is typically\n better than one microsecond.</p>\n</blockquote>\n\n<p>Additionally, there is the <a href=\"https://docs.python.org/2/library/timeit.html\" rel=\"noreferrer\">timeit</a> module for benchmarking code snippets.</p>\n" }, { "answer_id": 85536, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/85451#85511\">Others</a> have answered re: <code>time.time()</code> vs. <code>time.clock()</code>. </p>\n\n<p>However, if you're timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the <a href=\"https://docs.python.org/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code> module</a>.</p>\n" }, { "answer_id": 85586, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>On Unix time.clock() measures the amount of CPU time that has been used by the current process, so it's no good for measuring elapsed time from some point in the past. On Windows it will measure wall-clock seconds elapsed since the first call to the function. On either system time.time() will return seconds passed since the epoch. </p>\n\n<p>If you're writing code that's meant only for Windows, either will work (though you'll use the two differently - no subtraction is necessary for time.clock()). If this is going to run on a Unix system or you want code that is guaranteed to be portable, you will want to use time.time().</p>\n" }, { "answer_id": 85642, "author": "Justin Sheehy", "author_id": 11944, "author_profile": "https://Stackoverflow.com/users/11944", "pm_score": 3, "selected": false, "text": "<p>The difference is very platform-specific.</p>\n\n<p>clock() is very different on Windows than on Linux, for example.</p>\n\n<p>For the sort of examples you describe, you probably want the \"timeit\" module instead.</p>\n" }, { "answer_id": 87039, "author": "Jake", "author_id": 10675, "author_profile": "https://Stackoverflow.com/users/10675", "pm_score": 2, "selected": false, "text": "<p>To the best of my understanding, time.clock() has as much precision as your system will allow it.</p>\n" }, { "answer_id": 2246226, "author": "Seba", "author_id": 271241, "author_profile": "https://Stackoverflow.com/users/271241", "pm_score": 4, "selected": false, "text": "<p>One thing to keep in mind:\n Changing the system time affects <code>time.time()</code> but not <code>time.clock()</code>.</p>\n\n<p>I needed to control some automatic tests executions. If one step of the test case took more than a given amount of time, that TC was aborted to go on with the next one.</p>\n\n<p>But sometimes a step needed to change the system time (to check the scheduler module of the application under test), so after setting the system time a few hours in the future, the TC timeout expired and the test case was aborted. I had to switch from <code>time.time()</code> to <code>time.clock()</code> to handle this properly.</p>\n" }, { "answer_id": 21178451, "author": "bestwolf1983", "author_id": 3205257, "author_profile": "https://Stackoverflow.com/users/3205257", "pm_score": 4, "selected": false, "text": "<p><code>time()</code> has better precision than <code>clock()</code> on Linux. <code>clock()</code> only has precision less than 10 ms. While <code>time()</code> gives prefect precision.\nMy test is on CentOS 6.4, python 2.6</p>\n\n<pre><code>using time():\n\n1 requests, response time: 14.1749382019 ms\n2 requests, response time: 8.01301002502 ms\n3 requests, response time: 8.01491737366 ms\n4 requests, response time: 8.41021537781 ms\n5 requests, response time: 8.38804244995 ms\n</code></pre>\n\n<p><code>using clock():</code></p>\n\n<pre><code>1 requests, response time: 10.0 ms\n2 requests, response time: 0.0 ms \n3 requests, response time: 0.0 ms\n4 requests, response time: 10.0 ms\n5 requests, response time: 0.0 ms \n6 requests, response time: 0.0 ms\n7 requests, response time: 0.0 ms \n8 requests, response time: 0.0 ms\n</code></pre>\n" }, { "answer_id": 21374146, "author": "Hill", "author_id": 3239341, "author_profile": "https://Stackoverflow.com/users/3239341", "pm_score": -1, "selected": false, "text": "<p>Comparing test result between Ubuntu Linux and Windows 7.</p>\n\n<p><strong>On Ubuntu</strong></p>\n\n<pre><code>&gt;&gt;&gt; start = time.time(); time.sleep(0.5); (time.time() - start)\n0.5005500316619873\n</code></pre>\n\n<p><strong>On Windows 7</strong></p>\n\n<pre><code>&gt;&gt;&gt; start = time.time(); time.sleep(0.5); (time.time() - start)\n0.5\n</code></pre>\n" }, { "answer_id": 35929913, "author": "Nurul Akter Towhid", "author_id": 4294015, "author_profile": "https://Stackoverflow.com/users/4294015", "pm_score": 3, "selected": false, "text": "<p>I use this code to compare 2 methods .My OS is windows 8 , processor core i5 , RAM 4GB</p>\n<pre><code>import time\n\ndef t_time():\n start=time.time()\n time.sleep(0.1)\n return (time.time()-start)\n\n\ndef t_clock():\n start=time.clock()\n time.sleep(0.1)\n return (time.clock()-start)\n\n\n\n\ncounter_time=0\ncounter_clock=0\n\nfor i in range(1,100):\n counter_time += t_time()\n\n for i in range(1,100):\n counter_clock += t_clock()\n\nprint &quot;time() =&quot;,counter_time/100\nprint &quot;clock() =&quot;,counter_clock/100\n</code></pre>\n<p>output:</p>\n<pre><code>time() = 0.0993799996376\n\nclock() = 0.0993572257367\n</code></pre>\n" }, { "answer_id": 40677139, "author": "dsgdfg", "author_id": 2133240, "author_profile": "https://Stackoverflow.com/users/2133240", "pm_score": 1, "selected": false, "text": "<p>Right answer : <strong>They're both the same length of a fraction.</strong></p>\n\n<p>But which faster if <code>subject</code> is <code>time</code> ?</p>\n\n<p><strong>A little test case</strong> :</p>\n\n<pre><code>import timeit\nimport time\n\nclock_list = []\ntime_list = []\n\ntest1 = \"\"\"\ndef test(v=time.clock()):\n s = time.clock() - v\n\"\"\"\n\ntest2 = \"\"\"\ndef test(v=time.time()):\n s = time.time() - v\n\"\"\"\ndef test_it(Range) :\n for i in range(Range) :\n clk = timeit.timeit(test1, number=10000)\n clock_list.append(clk)\n tml = timeit.timeit(test2, number=10000)\n time_list.append(tml)\n\ntest_it(100)\n\nprint \"Clock Min: %f Max: %f Average: %f\" %(min(clock_list), max(clock_list), sum(clock_list)/float(len(clock_list)))\nprint \"Time Min: %f Max: %f Average: %f\" %(min(time_list), max(time_list), sum(time_list)/float(len(time_list)))\n</code></pre>\n\n<p>I am not work an Swiss labs but I've tested.. </p>\n\n<p><strong>Based of this question : <code>time.clock()</code> is better than <code>time.time()</code></strong></p>\n\n<p>Edit : <code>time.clock()</code> is internal counter so can't use outside, got limitations <code>max 32BIT FLOAT</code>, can't continued counting if not store first/last values. Can't merge another one counter... </p>\n" }, { "answer_id": 49667496, "author": "Chris_Rands", "author_id": 6260170, "author_profile": "https://Stackoverflow.com/users/6260170", "pm_score": 3, "selected": false, "text": "<p>As others have noted <code>time.clock()</code> is deprecated in favour of <code>time.perf_counter()</code> or <code>time.process_time()</code>, but Python 3.7 introduces nanosecond resolution timing with <a href=\"https://docs.python.org/3.7/library/time.html#time.perf_counter_ns\" rel=\"noreferrer\"><code>time.perf_counter_ns()</code></a>, <a href=\"https://docs.python.org/3.7/library/time.html#time.process_time_ns\" rel=\"noreferrer\"><code>time.process_time_ns()</code></a>, and <a href=\"https://docs.python.org/3.7/library/time.html#time.time_ns\" rel=\"noreferrer\"><code>time.time_ns()</code></a>, along with 3 other functions.</p>\n\n<p>These 6 new nansecond resolution functions are detailed in <a href=\"https://www.python.org/dev/peps/pep-0564/\" rel=\"noreferrer\">PEP 564</a>:</p>\n\n<blockquote>\n <p><code>time.clock_gettime_ns(clock_id)</code></p>\n \n <p><code>time.clock_settime_ns(clock_id, time:int)</code></p>\n \n <p><code>time.monotonic_ns()</code></p>\n \n <p><code>time.perf_counter_ns()</code></p>\n \n <p><code>time.process_time_ns()</code></p>\n \n <p><code>time.time_ns()</code></p>\n \n <p>These functions are similar to the version without the _ns suffix, but\n return a number of nanoseconds as a Python int.</p>\n</blockquote>\n\n<p>As others have also noted, use the <a href=\"https://docs.python.org/3.7/library/timeit.html\" rel=\"noreferrer\"><code>timeit</code> module</a> to time functions and small code snippets.</p>\n" }, { "answer_id": 62115682, "author": "xjcl", "author_id": 2111778, "author_profile": "https://Stackoverflow.com/users/2111778", "pm_score": 2, "selected": false, "text": "<p><code>time.clock()</code> was removed in Python 3.8 because it had <a href=\"https://docs.python.org/3.7/library/time.html?highlight=time%20clock#time.clock\" rel=\"nofollow noreferrer\">platform-dependent behavior</a>:</p>\n\n<ul>\n<li>On <strong>Unix</strong>, return the current processor time as a floating point number expressed in seconds.</li>\n<li><p>On <strong>Windows</strong>, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number</p>\n\n<pre><code>print(time.clock()); time.sleep(10); print(time.clock())\n# Linux : 0.0382 0.0384 # see Processor Time\n# Windows: 26.1224 36.1566 # see Wall-Clock Time\n</code></pre></li>\n</ul>\n\n<p>So which function to pick instead?</p>\n\n<ul>\n<li><p><strong>Processor Time</strong>: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.</p>\n\n<ul>\n<li>Use <code>time.process_time()</code></li>\n</ul></li>\n<li><p><strong>Wall-Clock Time</strong>: This refers to how much time has passed \"on a clock hanging on the wall\", i.e. outside real time.</p>\n\n<ul>\n<li><p>Use <code>time.perf_counter()</code></p>\n\n<ul>\n<li><code>time.time()</code> also measures wall-clock time but can be reset, so you could go back in time</li>\n<li><code>time.monotonic()</code> cannot be reset (monotonic = only goes forward) but has lower precision than <code>time.perf_counter()</code></li>\n</ul></li>\n</ul></li>\n</ul>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy? for example: ``` start = time.clock() ... do something elapsed = (time.clock() - start) ``` vs. ``` start = time.time() ... do something elapsed = (time.time() - start) ```
As of 3.3, [*time.clock()* is deprecated](https://docs.python.org/3/library/time.html#time.clock), and it's suggested to use **[time.process\_time()](https://docs.python.org/3/library/time.html#time.process_time)** or **[time.perf\_counter()](https://docs.python.org/3/library/time.html#time.perf_counter)** instead. Previously in 2.7, according to the **[time module docs](https://docs.python.org/2.7/library/time.html#time.clock)**: > > **time.clock()** > > > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition > of the meaning of “processor time”, depends on that of the C function > of the same name, but in any case, **this is the function to use for > benchmarking Python or timing algorithms.** > > > On Windows, this function returns wall-clock seconds elapsed since the > first call to this function, as a floating point number, based on the > Win32 function QueryPerformanceCounter(). The resolution is typically > better than one microsecond. > > > Additionally, there is the [timeit](https://docs.python.org/2/library/timeit.html) module for benchmarking code snippets.
85,457
<p>I am trying to inherit from my generated datacontext in LinqToSQL - something like this </p> <pre><code>public class myContext : dbDataContext { public System.Data.Linq.Table&lt;User&gt;() Users { return (from x in base.Users() where x.DeletedOn.HasValue == false select x); } } </code></pre> <p>But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated.</p> <p>Hal</p>
[ { "answer_id": 85507, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 1, "selected": false, "text": "<p>You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where the discriminator column says which goes to which. Then in your code, just reference the Users.OfType ActiveUsers, which will never include anything deleted.</p>\n\n<p>As a side note, how the heck do you do this with markdown?</p>\n\n<pre><code>Users.OfType&lt;ActiveUsers&gt;\n</code></pre>\n\n<p>I can get it in code, but not inline</p>\n" }, { "answer_id": 85540, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>You can use a stored procedure that returns all the mapped columns in the table for all the records that are not marked deleted, then map the LINQ to SQL class to the stored procedure's results. I think you just drag-drop the stored proc in Server Explorer on to the class in the LINQ to SQL designer.</p>\n" }, { "answer_id": 85599, "author": "Kevin Sheffield", "author_id": 590, "author_profile": "https://Stackoverflow.com/users/590", "pm_score": 0, "selected": false, "text": "<p>What I did in this circumstance is I created a repository class that passes back IQueryable but basically is just </p>\n\n<blockquote>\n <p>from t in _db.Table<br>\n select t;</p>\n</blockquote>\n\n<p>this is usually referenced by tableRepository.GetAllXXX(); but you could have a tableRepository.GetAllNonDeletedXXX(); that puts in that preliminary where clause to take out the deleted rows. This would allow you to get back the deleted ones, the undeleted ones and all rows using different methods.</p>\n" }, { "answer_id": 85802, "author": "Hal", "author_id": 16416, "author_profile": "https://Stackoverflow.com/users/16416", "pm_score": 0, "selected": false, "text": "<p>Perhaps my comment to Keven sheffield's response may shed some light on what I am trying to accomplish:</p>\n\n<blockquote>\n <p>I have a similar repository for most\n of my data access, but I am trying to\n be able to traverse my relationships\n and maintain the DeletedOn logic,\n without actually calling any\n additional methods. The objects are\n interrogated (spelling fixed) by a StringTemplate\n processor which can't call methods\n (just props/fields).</p>\n</blockquote>\n\n<p>I will ultimately need this DeletedOn filtering for all of the tables in my application. The inherited class solution from Scott Nichols should work (although I will need to derive a class and relationships for around 30 tables - ouch), although I need to figure out how to check for a null value in my Derived Class Discriminator Value property.</p>\n\n<p>I may just end up extended all my classes specifically for the StringTemplate processing, explicitly adding properties for the relationships I need, I would just love to be able to throw StringTemplate a [user] and have it walk through everything.</p>\n" }, { "answer_id": 85989, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 3, "selected": true, "text": "<p>Another approach would to be use views..</p>\n\n<pre><code>CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0\n</code></pre>\n\n<p>As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context.</p>\n" }, { "answer_id": 88605, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 0, "selected": false, "text": "<p>There are a couple of views we use in associations and they still appear just like any other relationship. We did need to add the associations manually. The only thing I can think to suggest is to take a look at the properties and decorated attributes generated for those classes and associations. </p>\n\n<p>Add a couple tables that have the same relationship and compare those to the view that isn't showing up. </p>\n\n<p>Also, sometimes the refresh on the server explorer connection doesn't seem to work correctly and the entities aren't created correctly initially, unless we remove them from the designer, close the project, then reopen the project and add them again from the server explorer. This is assuming you are using Visual Studio 2008 with the linq to sql .dbml designer.</p>\n" }, { "answer_id": 89144, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 1, "selected": false, "text": "<p>Encapsulate your DataContext so that developers don't use Table in their queries. I have an 'All' property on my repositories that does a similar filtering to what you need. So then queries are like:</p>\n\n<pre><code>from item in All\nwhere ...\nselect item\n</code></pre>\n\n<p>and all might be:</p>\n\n<pre><code>public IQueryable&lt;T&gt; All\n{\n get { return MyDataContext.GetTable&lt;T&gt;.Where(entity =&gt; !entity.DeletedOn.HasValue); }\n}\n</code></pre>\n" }, { "answer_id": 92697, "author": "Hal", "author_id": 16416, "author_profile": "https://Stackoverflow.com/users/16416", "pm_score": 0, "selected": false, "text": "<p>I found the problem that I had with the relationships/associations not showing in the views. It seems that you have to go through each class in the dbml and set a primary key for views as it is unable to extract that information from the schema. I am in the process of setting the primary keys now and am planning to go the view route to isolate only non-deleted items.</p>\n\n<p>Thanks and I will update more later.</p>\n" } ]
2008/09/17
[ "https://Stackoverflow.com/questions/85457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16416/" ]
I am trying to inherit from my generated datacontext in LinqToSQL - something like this ``` public class myContext : dbDataContext { public System.Data.Linq.Table<User>() Users { return (from x in base.Users() where x.DeletedOn.HasValue == false select x); } } ``` But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated. Hal
Another approach would to be use views.. ``` CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0 ``` As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context.