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
225,394
<p>I have a List of strings that is regenerated every 5 seconds. I want to create a Context Menu and set its items dynamically using this list. The problem is that I don't have even a clue how to do that and manage the Click action for every item generated (which should use the same method with different parameter DoSomething("item_name")).</p> <p>How should I do this?</p> <p>Thanks for your time. Best regards.</p>
[ { "answer_id": 225514, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 5, "selected": true, "text": "<p>So, you can clear the items from the context menu with:</p>\n\n<pre><code>myContextMenuStrip.Items.Clear();\n</code></pre>\n\n<p>You can add an item by calling:</p>\n\n<pre><code>myContextMenuStrip.Items.Add(myString);\n</code></pre>\n\n<p>The context menu has an ItemClicked event. Your handler could look like so:</p>\n\n<pre><code>private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)\n{\n DoSomething(e.ClickedItem.Text);\n}\n</code></pre>\n\n<p>Seems to work OK for me. Let me know if I misunderstood your question.</p>\n" }, { "answer_id": 41850885, "author": "tomloprod", "author_id": 4359029, "author_profile": "https://Stackoverflow.com/users/4359029", "pm_score": 1, "selected": false, "text": "<p>Another alternative using a <code>ToolStripMenuItem</code> object:</p>\n\n<pre><code>//////////// Create a new \"ToolStripMenuItem\" object:\nToolStripMenuItem newMenuItem= new ToolStripMenuItem();\n\n//////////// Set a name, for identification purposes:\nnewMenuItem.Name = \"nameOfMenuItem\";\n\n//////////// Sets the text that will appear in the new context menu option:\nnewMenuItem.Text = \"This is another option!\";\n\n//////////// Add this new item to your context menu:\nmyContextMenuStrip.Items.Add(newMenuItem);\n</code></pre>\n\n<p><br>\nInside the <code>ItemClicked</code> event of your <code>myContextMenuStrip</code>, you can check which option has been chosen (<em>based on the name property of the menu item</em>)</p>\n\n<pre><code>private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)\n{\n ToolStripItem item = e.ClickedItem;\n\n //////////// This will show \"nameOfMenuItem\":\n MessageBox.Show(item.Name, \"And the clicked option is...\");\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
I have a List of strings that is regenerated every 5 seconds. I want to create a Context Menu and set its items dynamically using this list. The problem is that I don't have even a clue how to do that and manage the Click action for every item generated (which should use the same method with different parameter DoSomething("item\_name")). How should I do this? Thanks for your time. Best regards.
So, you can clear the items from the context menu with: ``` myContextMenuStrip.Items.Clear(); ``` You can add an item by calling: ``` myContextMenuStrip.Items.Add(myString); ``` The context menu has an ItemClicked event. Your handler could look like so: ``` private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { DoSomething(e.ClickedItem.Text); } ``` Seems to work OK for me. Let me know if I misunderstood your question.
225,432
<p>With VS2005, I want to create a DLL and automatically export all symbols without adding <code>__declspec(dllexport)</code> everywhere, and without hand-creating <code>.def</code> files. Is there a way to do this?</p>
[ { "answer_id": 225457, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": -1, "selected": false, "text": "<p>No, you will need a macro that resolves to <code>__declspec(dllexport)</code> when it's included by the .cpp file that implements the exported functions, and resolves to <code>__declspec(dllimport)</code> otherwise.</p>\n" }, { "answer_id": 226017, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 6, "selected": false, "text": "<p>It can be done...</p>\n\n<p>The way we do it here is to use the /DEF option of the linker to pass a <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/module-definition-dot-def-files?view=vs-2017\" rel=\"noreferrer\">\"module definition file\"</a> containing a list of our exports. I see from your question that you know about these files. However, we do not do it by hand. The list of exports itself is created by the <a href=\"http://msdn.microsoft.com/en-us/library/c1h23y6c.aspx\" rel=\"noreferrer\">dumpbin</a> /LINKERMEMBER command, and manipulating the output via a simple script to the format of a module definition file.</p>\n\n<p>It is a lot of work to setup, but it allows us to compile code created without dllexport declarations for Unix on Windows.</p>\n" }, { "answer_id": 731767, "author": "user72260", "author_id": 72260, "author_profile": "https://Stackoverflow.com/users/72260", "pm_score": 3, "selected": false, "text": "<p>I've written a small program to parse the output of \"dumpbin /linkermember\" on the .lib file. I have upwards of 8,000 function references to export from one DLL. </p>\n\n<p>The problem with doing it on a DLL is that you have to link the DLL without the exported definitions once to create the .lib file, then generate the .def which means you now have to relink the DLL again with the .def file to actually have the references exported. </p>\n\n<p>Working with static libraries is easier. Compile all your sources into static libs, run dumbin, generate a .def with your little program, then link the libs together into a DLL now that the export names are available.</p>\n\n<p>Unfortunately my company won't allow me to show you the source. The work involved is recognizing which \"public symbols\" in the dump output are not needed in your def file. You have to throw away a lot of those references, NULL_IMPORT_DESCRIPTOR, NULL_THUNK_DATA, __imp*, etc.</p>\n" }, { "answer_id": 32284832, "author": "Maks", "author_id": 3001953, "author_profile": "https://Stackoverflow.com/users/3001953", "pm_score": 7, "selected": true, "text": "<h2>Short answer</h2>\n\n<p>You can do it with help of the new version of the CMake (any version cmake-3.3.20150721-g9cd2f-win32-x86.exe or higher).</p>\n\n<p>Currently it's in the dev branch.\nLater, the feature will be added in the release version of the cmake-3.4.</p>\n\n<p>Link to the cmake dev: </p>\n\n<p><a href=\"http://www.cmake.org/files/dev/\" rel=\"noreferrer\">cmake_dev</a></p>\n\n<p>Link to an article which describe the technic:</p>\n\n<p><a href=\"https://blog.kitware.com/create-dlls-on-windows-without-declspec-using-new-cmake-export-all-feature/\" rel=\"noreferrer\">Create dlls on Windows without declspec() using new CMake export all feature</a></p>\n\n<p>Link to an example project:</p>\n\n<p><a href=\"https://bitbucket.org/vlasovmaksim/cmake_windows_export_all_symbols/overview\" rel=\"noreferrer\">cmake_windows_export_all_symbols</a></p>\n\n<hr>\n\n<h2>Long answer</h2>\n\n<p><em>Caution:</em>\nAll information below is related to the MSVC compiler or Visual Studio.</p>\n\n<p>If you use other compilers like gcc on Linux or MinGW gcc compiler on Windows you don't have linking errors due to not exported symbols, because gcc compiler export all symbols in a dynamic library (dll) by default instead of MSVC or Intel windows compilers.</p>\n\n<p>In windows you have to explicitly export symbol from a dll.</p>\n\n<p>More info about this is provided by links: </p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/z4zxe9k8.aspx\" rel=\"noreferrer\">Exporting from a DLL</a></p>\n\n<p><a href=\"http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL\" rel=\"noreferrer\">HowTo: Export C++ classes from a DLL</a></p>\n\n<p>So if you want to export all symbols from dll with MSVC (Visual Studio compiler) you have two options: </p>\n\n<ul>\n<li>Use the keyword __declspec(dllexport) in the class/function's definition.</li>\n<li>Create a module definition (.def) file and use the .def file when building the DLL.</li>\n</ul>\n\n<hr>\n\n<p><em>1. Use the keyword __declspec(dllexport) in the class/function's definition</em></p>\n\n<hr>\n\n<p><em>1.1. Add \"__declspec(dllexport) / __declspec(dllimport)\" macros to a class or method you want to use. So if you want to export all classes you should add this macros to all of them</em></p>\n\n<p>More info about this is provided by link:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/a90k134d.aspx\" rel=\"noreferrer\">Exporting from a DLL Using __declspec(dllexport)</a></p>\n\n<p>Example of usage (replace \"Project\" by real project name):</p>\n\n<pre><code>// ProjectExport.h\n\n#ifndef __PROJECT_EXPORT_H\n#define __PROJECT_EXPORT_H\n\n#ifdef USEPROJECTLIBRARY\n#ifdef PROJECTLIBRARY_EXPORTS \n#define PROJECTAPI __declspec(dllexport)\n#else\n#define PROJECTAPI __declspec(dllimport)\n#endif\n#else\n#define PROJECTAPI\n#endif\n\n#endif\n</code></pre>\n\n<p>Then add \"PROJECTAPI\" to all classes.\nDefine \"USEPROJECTLIBRARY\" only if you want export/import symbols from dll.\nDefine \"PROJECTLIBRARY_EXPORTS\" for the dll.</p>\n\n<p>Example of class export:</p>\n\n<pre><code>#include \"ProjectExport.h\"\n\nnamespace hello {\n class PROJECTAPI Hello {} \n}\n</code></pre>\n\n<p>Example of function export:</p>\n\n<pre><code>#include \"ProjectExport.h\"\n\nPROJECTAPI void HelloWorld();\n</code></pre>\n\n<p><em>Caution:</em> don't forget to include \"ProjectExport.h\" file.</p>\n\n<hr>\n\n<p><em>1.2. Export as C functions.\nIf you use C++ compiler for compilation code is written on C, you could add extern \"C\" in front of a function to eliminate name mangling</em></p>\n\n<p>More info about C++ name mangling is provided by link:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/deaxefa7.aspx\" rel=\"noreferrer\">Name Decoration</a></p>\n\n<p>Example of usage:</p>\n\n<pre><code>extern \"C\" __declspec(dllexport) void HelloWorld();\n</code></pre>\n\n<p>More info about this is provided by link:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/wf2w9f6x.aspx\" rel=\"noreferrer\">Exporting C++ Functions for Use in C-Language Executables</a></p>\n\n<hr>\n\n<p><em>2. Create a module definition (.def) file and use the .def file when building the DLL</em></p>\n\n<p>More info about this is provided by link:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/d91k01sh.aspx\" rel=\"noreferrer\">Exporting from a DLL Using DEF Files</a></p>\n\n<p>Further I describe three approach about how to create .def file.</p>\n\n<hr>\n\n<p><em>2.1. Export C functions</em></p>\n\n<p>In this case you could simple add function declarations in the .def file by hand.</p>\n\n<p>Example of usage:</p>\n\n<pre><code>extern \"C\" void HelloWorld();\n</code></pre>\n\n<p>Example of .def file (__cdecl naming convention):</p>\n\n<pre><code>EXPORTS \n_HelloWorld\n</code></pre>\n\n<hr>\n\n<p><em>2.2. Export symbols from static library</em></p>\n\n<p>I tried approach suggested by \"user72260\".</p>\n\n<p>He said:</p>\n\n<ul>\n<li>Firstly, you could create static library.</li>\n<li>Then use \"dumpbin /LINKERMEMBER\" to export all symbols from static library.</li>\n<li>Parse the output.</li>\n<li>Put all results in a .def file.</li>\n<li>Create dll with the .def file.</li>\n</ul>\n\n<p>I used this approach, but it's not very convinient to always create two builds (one as a static and the other as a dynamic library). However, I have to admit, this approach really works.</p>\n\n<hr>\n\n<p><em>2.3. Export symbols from .obj files or with help of the CMake</em></p>\n\n<hr>\n\n<p><em>2.3.1. With CMake usage</em></p>\n\n<p><em>Important notice:</em> You don't need any export macros to a classes or functions!</p>\n\n<p><em>Important notice:</em> You can't use /GL (<a href=\"https://msdn.microsoft.com/en-us/library/0zza0de8.aspx\" rel=\"noreferrer\">Whole Program Optimization</a>) when use this approach!</p>\n\n<ul>\n<li>Create CMake project based on the \"CMakeLists.txt\" file.</li>\n<li>Add the following line to the \"CMakeLists.txt\" file:\nset(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)</li>\n<li>Then create Visual Studio project with help of \"CMake (cmake-gui)\".</li>\n<li>Compile the project.</li>\n</ul>\n\n<p>Example of usage:</p>\n\n<p><em>Root folder</em></p>\n\n<p>CMakeLists.txt (Root folder)</p>\n\n<pre><code>cmake_minimum_required(VERSION 2.6)\nproject(cmake_export_all)\n\nset(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)\n\nset(dir ${CMAKE_CURRENT_SOURCE_DIR})\nset(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"${dir}/bin\")\n\nset(SOURCE_EXE main.cpp)\n\ninclude_directories(foo)\n\nadd_executable(main ${SOURCE_EXE})\n\nadd_subdirectory(foo)\n\ntarget_link_libraries(main foo)\n</code></pre>\n\n<p>main.cpp (Root folder)</p>\n\n<pre><code>#include \"foo.h\"\n\nint main() {\n HelloWorld();\n\n return 0;\n}\n</code></pre>\n\n<p><em>Foo folder (Root folder / Foo folder)</em></p>\n\n<p>CMakeLists.txt (Foo folder)</p>\n\n<pre><code>project(foo)\n\nset(SOURCE_LIB foo.cpp)\n\nadd_library(foo SHARED ${SOURCE_LIB})\n</code></pre>\n\n<p>foo.h (Foo folder)</p>\n\n<pre><code>void HelloWorld();\n</code></pre>\n\n<p>foo.cpp (Foo folder)</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nvoid HelloWorld() {\n std::cout &lt;&lt; \"Hello World!\" &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>Link to the example project again:</p>\n\n<p><a href=\"https://bitbucket.org/vlasovmaksim/cmake_windows_export_all_symbols/overview\" rel=\"noreferrer\">cmake_windows_export_all_symbols</a></p>\n\n<p>CMake uses the different from \"2.2. Export symbols from static library\" approach. </p>\n\n<p>It does the following:</p>\n\n<p>1) Create \"objects.txt\" file in the build directory with information of .obj files are used in a dll.</p>\n\n<p>2) Compile the dll, that is create .obj files.</p>\n\n<p>3) Based on \"objects.txt\" file information extract all symbols from .obj file.</p>\n\n<p>Example of usage:</p>\n\n<pre><code>DUMPBIN /SYMBOLS example.obj &gt; log.txt\n</code></pre>\n\n<p>More info about this is provided by link:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/b842y285.aspx\" rel=\"noreferrer\">/SYMBOLS</a></p>\n\n<p>4) Parse extracted from .obj file information.</p>\n\n<p>In my opinion I would use calling convection, for example \"__cdecl/__fastcall\", \"SECTx/UNDEF\" symbol field (the third column), \"External/Static\" symbol field (the fifth column), \"??\", \"?\" information for parsing an .obj files.</p>\n\n<p>I don't know how exactly CMake parse an .obj file.\nHowever, CMake is open source, so you could find out if it's interested for you.</p>\n\n<p>Link to the CMake project:</p>\n\n<p><a href=\"https://github.com/Kitware/CMake\" rel=\"noreferrer\">CMake_github</a></p>\n\n<p>5) Put all exported symbols in a .def file.</p>\n\n<p>6) Link a dll with usage of a .def created file.</p>\n\n<p>Steps 4)-5), that is parse .obj files and create a .def file before linking and using the .def file CMake does with help of \"Pre-Link event\".\nWhile \"Pre-Link event\" fires you could call any program you want.\nSo in case of \"CMake usage\" \"Pre-Link event\" call the CMake with the following information about where to put the .def file and where the \"objects.txt\" file and with argument \"-E __create_def\".\nYou could check this information by creating CMake Visusal Studio project with \"set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)\" and then check the \".vcxproj\" project file for dll.</p>\n\n<p>If you try to compile a project without \"set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)\" or with \"set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS OFF)\" you will get linking errors, due to the fact that symbols are not exported from a dll.</p>\n\n<p>More info about this is provided by link:</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/e85wte0k.aspx\" rel=\"noreferrer\">Understanding Custom Build Steps and Build Events</a></p>\n\n<hr>\n\n<p><em>2.3.2. Without CMake usage</em></p>\n\n<p>You simple could create a small program for parsing .obj file by youself without CMake usege. Hovewer, I have to admit that CMake is very usefull program especially for cross-platform development.</p>\n" }, { "answer_id": 49891803, "author": "Sergey", "author_id": 246605, "author_profile": "https://Stackoverflow.com/users/246605", "pm_score": 2, "selected": false, "text": "<p>Thanks @Maks for the <a href=\"https://stackoverflow.com/a/32284832/246605\">detailed answer</a>.</p>\n\n<p>Below is an example of what I used in Pre-Link event to generate def file from obj. I hope it will be helpful for someone.</p>\n\n<pre><code>dumpbin /SYMBOLS $(Platform)\\$(Configuration)\\mdb.obj | findstr /R \"().*External.*mdb_.*\" &gt; $(Platform)\\$(Configuration)\\mdb_symbols\n(echo EXPORTS &amp; for /F \"usebackq tokens=2 delims==|\" %%E in (`type $(Platform)\\$(Configuration)\\mdb_symbols`) do @echo %%E) &gt; $(Platform)\\$(Configuration)\\lmdb.def\n</code></pre>\n\n<p>Basically I just took one of objects (mdb.obj) and grepped mdb_* functions. Then parsed output to keep just names taking into account amount of spaces for indentation (one after splitting into tokens and another in echo. I don't know if it's matter though).</p>\n\n<p>Real world script probably will kind of more complex though.</p>\n" }, { "answer_id": 54067711, "author": "jww", "author_id": 608639, "author_profile": "https://Stackoverflow.com/users/608639", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>I want to create a DLL and automatically export all symbols without adding __declspec(dllexport) everywhere and without hand-creating .def files. Is threre a way to do this?</p>\n</blockquote>\n\n<p>This is a late answer, but it provides the details for Maks's answer in Section (2). It also avoids scripts and uses a C++ program called <code>dump2def</code>. The source code for <code>dump2def</code> is below.</p>\n\n<p>Finally, the steps below assume you are working from a Visual Studio <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/tools/developer-command-prompt-for-vs\" rel=\"noreferrer\">Developer Prompt</a>, which is a Windows Terminal where <code>vcvarsall.bat</code> has been run. You need to ensure the build tools like <code>cl.exe</code>, <code>lib.exe</code>, <code>link.exe</code> and <code>nmake.exe</code> are on-path.</p>\n\n<blockquote>\n <p>More info about this is provided by link:</p>\n \n <p><a href=\"https://msdn.microsoft.com/en-us/library/d91k01sh.aspx\" rel=\"noreferrer\">Exporting from a DLL Using DEF\n Files</a><br>\n ...</p>\n</blockquote>\n\n<p>The instruction below use:</p>\n\n<ul>\n<li><code>static.lib</code> - static library archive (*.a file on Linux)</li>\n<li><code>dynamic.dll</code> - dynamic library (*.so file on Linux)</li>\n<li><code>import.lib</code> - dynamic library (import library on Windows)</li>\n</ul>\n\n<p>Also note that though you are exporting everything from the DLL, clients still must use <code>declspec(dllimport)</code> on all symbols (classes, functions and data) that they use. Also see on MSDN.</p>\n\n<p>First, take your objects and create a static archive:</p>\n\n<pre class=\"lang-nmake prettyprint-override\"><code>AR = lib.exe\nARFLAGS = /nologo\n\nCXX_SRCS = a.cpp b.cpp c.cpp ...\nLIB_OBJS = a.obj b.obj c.obj ...\n\nstatic.lib: $(LIB_OBJS)\n $(AR) $(ARFLAGS) $(LIB_OBJS) /out:$@\n</code></pre>\n\n<p>Second, run <code>dumpbin.exe /LINKERMEMEBER</code> on the archive to create a <code>*.dump</code> file:</p>\n\n<pre class=\"lang-nmake prettyprint-override\"><code>dynamic.dump:\n dumpbin /LINKERMEMBER static.lib &gt; dynamic.dump\n</code></pre>\n\n<p>Third, run <code>dump2def.exe</code> on the <code>*.dump</code> file to produce the <code>*.def</code> file. The source code for <code>dump2def.exe</code> is below.</p>\n\n<pre class=\"lang-nmake prettyprint-override\"><code>dynamic.def: static.lib dynamic.dump\n dump2def.exe dynamic.dump dynamic.def\n</code></pre>\n\n<p>Fourth, build the DLL:</p>\n\n<pre class=\"lang-nmake prettyprint-override\"><code>LD = link.exe\nLDFLAGS = /OPT:REF /MACHINE:X64\nLDLIBS = kernel32.lib\n\ndynamic.dll: $(LIB_OBJS) dynamic.def\n $(LD) $(LDFLAGS) /DLL /DEF:dynamic.def /IGNORE:4102 $(LIB_OBJS) $(LDLIBS) /out:$@\n</code></pre>\n\n<p><code>/IGNORE:4102</code> is used to avoid this warning. It is expected in this case:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>dynamic.def : warning LNK4102: export of deleting destructor 'public: virtual v\noid * __ptr64 __cdecl std::exception::`scalar deleting destructor'(unsigned int)\n __ptr64'; image may not run correctly\n</code></pre>\n\n<p>When the <code>dynamic.dll</code> recipe is invoked, it creates a <code>dynamic.lib</code> import file and <code>dynamic.exp</code> file, too:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt; cls &amp;&amp; nmake /f test.nmake dynamic.dll\n...\nCreating library dynamic.lib and object dynamic.exp\n</code></pre>\n\n<p>And:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> C:\\Users\\Test\\testdll&gt;dir *.lib *.dll *.def *.exp\n Volume in drive C is Windows\n Volume Serial Number is CC36-23BE\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:33 PM 71,501,578 static.lib\n01/06/2019 08:33 PM 11,532,052 dynamic.lib\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:35 PM 5,143,552 dynamic.dll\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:33 PM 1,923,070 dynamic.def\n\n Directory of C:\\Users\\Test\\testdll\n\n01/06/2019 08:35 PM 6,937,789 dynamic.exp\n 5 File(s) 97,038,041 bytes\n 0 Dir(s) 139,871,186,944 bytes free\n</code></pre>\n\n<p>Gluing it together here is what the Nmake makefile looks like. It is part of a <a href=\"https://github.com/weidai11/cryptopp/blob/master/cryptest.nmake\" rel=\"noreferrer\">real Nmake file</a>:</p>\n\n<pre class=\"lang-nmake prettyprint-override\"><code>all: test.exe\n\ntest.exe: pch.pch static.lib $(TEST_OBJS)\n $(LD) $(LDFLAGS) $(TEST_OBJS) static.lib $(LDLIBS) /out:$@\n\nstatic.lib: $(LIB_OBJS)\n $(AR) $(ARFLAGS) $(LIB_OBJS) /out:$@\n\ndynamic.map:\n $(LD) $(LDFLAGS) /DLL /MAP /MAPINFO:EXPORTS $(LIB_OBJS) $(LDLIBS) /out:dynamic.dll\n\ndynamic.dump:\n dumpbin.exe /LINKERMEMBER static.lib /OUT:dynamic.dump\n\ndynamic.def: static.lib dynamic.dump\n dump2def.exe dynamic.dump\n\ndynamic.dll: $(LIB_OBJS) dynamic.def\n $(LD) $(LDFLAGS) /DLL /DEF:dynamic.def /IGNORE:4102 $(LIB_OBJS) $(LDLIBS) /out:$@\n\nclean:\n $(RM) /F /Q pch.pch $(LIB_OBJS) pch.obj static.lib $(TEST_OBJS) test.exe *.pdb\n</code></pre>\n\n<hr>\n\n<p>And here is the source code for <code>dump2def.exe</code>:</p>\n\n<pre class=\"lang-cxx prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;set&gt;\n\ntypedef std::set&lt;std::string&gt; SymbolMap;\n\nvoid PrintHelpAndExit(int code)\n{\n std::cout &lt;&lt; \"dump2def - create a module definitions file from a dumpbin file\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \" Written and placed in public domain by Jeffrey Walton\" &lt;&lt; std::endl;\n std::cout &lt;&lt; std::endl;\n\n std::cout &lt;&lt; \"Usage: \" &lt;&lt; std::endl;\n\n std::cout &lt;&lt; \" dump2def &lt;infile&gt;\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \" - Create a def file from &lt;infile&gt; and write it to a file with\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \" the same name as &lt;infile&gt; but using the .def extension\" &lt;&lt; std::endl;\n\n std::cout &lt;&lt; \" dump2def &lt;infile&gt; &lt;outfile&gt;\" &lt;&lt; std::endl;\n std::cout &lt;&lt; \" - Create a def file from &lt;infile&gt; and write it to &lt;outfile&gt;\" &lt;&lt; std::endl;\n\n std::exit(code);\n}\n\nint main(int argc, char* argv[])\n{\n // ******************** Handle Options ******************** //\n\n // Convenience item\n std::vector&lt;std::string&gt; opts;\n for (size_t i=0; i&lt;argc; ++i)\n opts.push_back(argv[i]);\n\n // Look for help\n std::string opt = opts.size() &lt; 3 ? \"\" : opts[1].substr(0,2);\n if (opt == \"/h\" || opt == \"-h\" || opt == \"/?\" || opt == \"-?\")\n PrintHelpAndExit(0);\n\n // Add &lt;outfile&gt; as needed\n if (opts.size() == 2)\n {\n std::string outfile = opts[1];\n std::string::size_type pos = outfile.length() &lt; 5 ? std::string::npos : outfile.length() - 5;\n if (pos == std::string::npos || outfile.substr(pos) != \".dump\")\n PrintHelpAndExit(1);\n\n outfile.replace(pos, 5, \".def\");\n opts.push_back(outfile);\n }\n\n // Check or exit\n if (opts.size() != 3)\n PrintHelpAndExit(1);\n\n // ******************** Read MAP file ******************** //\n\n SymbolMap symbols;\n\n try\n {\n std::ifstream infile(opts[1].c_str());\n std::string::size_type pos;\n std::string line;\n\n // Find start of the symbol table\n while (std::getline(infile, line))\n {\n pos = line.find(\"public symbols\");\n if (pos == std::string::npos) { continue; } \n\n // Eat the whitespace after the table heading\n infile &gt;&gt; std::ws;\n break;\n }\n\n while (std::getline(infile, line))\n {\n // End of table\n if (line.empty()) { break; }\n\n std::istringstream iss(line);\n std::string address, symbol;\n iss &gt;&gt; address &gt;&gt; symbol;\n\n symbols.insert(symbol);\n }\n }\n catch (const std::exception&amp; ex)\n {\n std::cerr &lt;&lt; \"Unexpected exception:\" &lt;&lt; std::endl;\n std::cerr &lt;&lt; ex.what() &lt;&lt; std::endl;\n std::cerr &lt;&lt; std::endl;\n\n PrintHelpAndExit(1);\n }\n\n // ******************** Write DEF file ******************** //\n\n try\n {\n std::ofstream outfile(opts[2].c_str());\n\n // Library name, cryptopp.dll\n std::string name = opts[2];\n std::string::size_type pos = name.find_last_of(\".\");\n\n if (pos != std::string::npos)\n name.erase(pos);\n\n outfile &lt;&lt; \"LIBRARY \" &lt;&lt; name &lt;&lt; std::endl;\n outfile &lt;&lt; \"DESCRIPTION \\\"Crypto++ Library\\\"\" &lt;&lt; std::endl; \n outfile &lt;&lt; \"EXPORTS\" &lt;&lt; std::endl;\n outfile &lt;&lt; std::endl;\n\n outfile &lt;&lt; \"\\t;; \" &lt;&lt; symbols.size() &lt;&lt; \" symbols\" &lt;&lt; std::endl;\n\n // Symbols from our object files\n SymbolMap::const_iterator it = symbols.begin();\n for ( ; it != symbols.end(); ++it)\n outfile &lt;&lt; \"\\t\" &lt;&lt; *it &lt;&lt; std::endl;\n }\n catch (const std::exception&amp; ex)\n {\n std::cerr &lt;&lt; \"Unexpected exception:\" &lt;&lt; std::endl;\n std::cerr &lt;&lt; ex.what() &lt;&lt; std::endl;\n std::cerr &lt;&lt; std::endl;\n\n PrintHelpAndExit(1);\n } \n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 58958294, "author": "Alexander Samoylov", "author_id": 4807875, "author_profile": "https://Stackoverflow.com/users/4807875", "pm_score": 1, "selected": false, "text": "<p>Perhaps somebody finds useful my Python script for converting .dump to .def.</p>\n\n<pre><code>import sys, os\nfunctions = []\nstartPoint = False\n# Exclude standard API like sprintf to avoid multiple definition link error\nexcluded_functions = [ 'sprintf', 'snprintf', 'sscanf', 'fprintf' ]\n\nif len(sys.argv) &lt; 2:\n print('Usage: %s &lt;Input .dump file&gt; &lt;Output .def file&gt;.' % sys.argv[0])\n print('Example: %s myStaticLib.dump exports.def' % sys.argv[0])\n sys.exit(1)\nprint('%s: Processing %s to %s' % (sys.argv[0], sys.argv[1], sys.argv[2]))\n\nfin = open(sys.argv[1], 'r')\nlines = fin.readlines()\nfin.close()\n\n# Reading\nfor l in lines:\n l_str = l.strip()\n if (startPoint == True) and (l_str == 'Summary'): # end point\n break\n if (startPoint == False) and (\"public symbols\" in l_str):\n startPoint = True\n continue\n if (startPoint == True) and l_str is not '':\n funcName = l_str.split(' ')[-1]\n if funcName not in excluded_functions:\n functions.append(\" \" + funcName)\n# Writing\nfout = open(sys.argv[2], 'w')\nfout.write('EXPORTS\\n')\nfor f in functions:\n fout.write('%s\\n' % f)\nfout.close()\n</code></pre>\n\n<p>With this script you can get the .def file for your .lib in two steps:</p>\n\n<pre><code>dumpbin /LINKERMEMBER:1 myStaticLib.lib &gt; myExports.dump\npython dump2def.py myExports.dump myExports.def\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14443/" ]
With VS2005, I want to create a DLL and automatically export all symbols without adding `__declspec(dllexport)` everywhere, and without hand-creating `.def` files. Is there a way to do this?
Short answer ------------ You can do it with help of the new version of the CMake (any version cmake-3.3.20150721-g9cd2f-win32-x86.exe or higher). Currently it's in the dev branch. Later, the feature will be added in the release version of the cmake-3.4. Link to the cmake dev: [cmake\_dev](http://www.cmake.org/files/dev/) Link to an article which describe the technic: [Create dlls on Windows without declspec() using new CMake export all feature](https://blog.kitware.com/create-dlls-on-windows-without-declspec-using-new-cmake-export-all-feature/) Link to an example project: [cmake\_windows\_export\_all\_symbols](https://bitbucket.org/vlasovmaksim/cmake_windows_export_all_symbols/overview) --- Long answer ----------- *Caution:* All information below is related to the MSVC compiler or Visual Studio. If you use other compilers like gcc on Linux or MinGW gcc compiler on Windows you don't have linking errors due to not exported symbols, because gcc compiler export all symbols in a dynamic library (dll) by default instead of MSVC or Intel windows compilers. In windows you have to explicitly export symbol from a dll. More info about this is provided by links: [Exporting from a DLL](https://msdn.microsoft.com/en-us/library/z4zxe9k8.aspx) [HowTo: Export C++ classes from a DLL](http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL) So if you want to export all symbols from dll with MSVC (Visual Studio compiler) you have two options: * Use the keyword \_\_declspec(dllexport) in the class/function's definition. * Create a module definition (.def) file and use the .def file when building the DLL. --- *1. Use the keyword \_\_declspec(dllexport) in the class/function's definition* --- *1.1. Add "\_\_declspec(dllexport) / \_\_declspec(dllimport)" macros to a class or method you want to use. So if you want to export all classes you should add this macros to all of them* More info about this is provided by link: [Exporting from a DLL Using \_\_declspec(dllexport)](https://msdn.microsoft.com/en-us/library/a90k134d.aspx) Example of usage (replace "Project" by real project name): ``` // ProjectExport.h #ifndef __PROJECT_EXPORT_H #define __PROJECT_EXPORT_H #ifdef USEPROJECTLIBRARY #ifdef PROJECTLIBRARY_EXPORTS #define PROJECTAPI __declspec(dllexport) #else #define PROJECTAPI __declspec(dllimport) #endif #else #define PROJECTAPI #endif #endif ``` Then add "PROJECTAPI" to all classes. Define "USEPROJECTLIBRARY" only if you want export/import symbols from dll. Define "PROJECTLIBRARY\_EXPORTS" for the dll. Example of class export: ``` #include "ProjectExport.h" namespace hello { class PROJECTAPI Hello {} } ``` Example of function export: ``` #include "ProjectExport.h" PROJECTAPI void HelloWorld(); ``` *Caution:* don't forget to include "ProjectExport.h" file. --- *1.2. Export as C functions. If you use C++ compiler for compilation code is written on C, you could add extern "C" in front of a function to eliminate name mangling* More info about C++ name mangling is provided by link: [Name Decoration](https://msdn.microsoft.com/en-us/library/deaxefa7.aspx) Example of usage: ``` extern "C" __declspec(dllexport) void HelloWorld(); ``` More info about this is provided by link: [Exporting C++ Functions for Use in C-Language Executables](https://msdn.microsoft.com/en-us/library/wf2w9f6x.aspx) --- *2. Create a module definition (.def) file and use the .def file when building the DLL* More info about this is provided by link: [Exporting from a DLL Using DEF Files](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) Further I describe three approach about how to create .def file. --- *2.1. Export C functions* In this case you could simple add function declarations in the .def file by hand. Example of usage: ``` extern "C" void HelloWorld(); ``` Example of .def file (\_\_cdecl naming convention): ``` EXPORTS _HelloWorld ``` --- *2.2. Export symbols from static library* I tried approach suggested by "user72260". He said: * Firstly, you could create static library. * Then use "dumpbin /LINKERMEMBER" to export all symbols from static library. * Parse the output. * Put all results in a .def file. * Create dll with the .def file. I used this approach, but it's not very convinient to always create two builds (one as a static and the other as a dynamic library). However, I have to admit, this approach really works. --- *2.3. Export symbols from .obj files or with help of the CMake* --- *2.3.1. With CMake usage* *Important notice:* You don't need any export macros to a classes or functions! *Important notice:* You can't use /GL ([Whole Program Optimization](https://msdn.microsoft.com/en-us/library/0zza0de8.aspx)) when use this approach! * Create CMake project based on the "CMakeLists.txt" file. * Add the following line to the "CMakeLists.txt" file: set(CMAKE\_WINDOWS\_EXPORT\_ALL\_SYMBOLS ON) * Then create Visual Studio project with help of "CMake (cmake-gui)". * Compile the project. Example of usage: *Root folder* CMakeLists.txt (Root folder) ``` cmake_minimum_required(VERSION 2.6) project(cmake_export_all) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) set(dir ${CMAKE_CURRENT_SOURCE_DIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${dir}/bin") set(SOURCE_EXE main.cpp) include_directories(foo) add_executable(main ${SOURCE_EXE}) add_subdirectory(foo) target_link_libraries(main foo) ``` main.cpp (Root folder) ``` #include "foo.h" int main() { HelloWorld(); return 0; } ``` *Foo folder (Root folder / Foo folder)* CMakeLists.txt (Foo folder) ``` project(foo) set(SOURCE_LIB foo.cpp) add_library(foo SHARED ${SOURCE_LIB}) ``` foo.h (Foo folder) ``` void HelloWorld(); ``` foo.cpp (Foo folder) ``` #include <iostream> void HelloWorld() { std::cout << "Hello World!" << std::endl; } ``` Link to the example project again: [cmake\_windows\_export\_all\_symbols](https://bitbucket.org/vlasovmaksim/cmake_windows_export_all_symbols/overview) CMake uses the different from "2.2. Export symbols from static library" approach. It does the following: 1) Create "objects.txt" file in the build directory with information of .obj files are used in a dll. 2) Compile the dll, that is create .obj files. 3) Based on "objects.txt" file information extract all symbols from .obj file. Example of usage: ``` DUMPBIN /SYMBOLS example.obj > log.txt ``` More info about this is provided by link: [/SYMBOLS](https://msdn.microsoft.com/en-us/library/b842y285.aspx) 4) Parse extracted from .obj file information. In my opinion I would use calling convection, for example "\_\_cdecl/\_\_fastcall", "SECTx/UNDEF" symbol field (the third column), "External/Static" symbol field (the fifth column), "??", "?" information for parsing an .obj files. I don't know how exactly CMake parse an .obj file. However, CMake is open source, so you could find out if it's interested for you. Link to the CMake project: [CMake\_github](https://github.com/Kitware/CMake) 5) Put all exported symbols in a .def file. 6) Link a dll with usage of a .def created file. Steps 4)-5), that is parse .obj files and create a .def file before linking and using the .def file CMake does with help of "Pre-Link event". While "Pre-Link event" fires you could call any program you want. So in case of "CMake usage" "Pre-Link event" call the CMake with the following information about where to put the .def file and where the "objects.txt" file and with argument "-E \_\_create\_def". You could check this information by creating CMake Visusal Studio project with "set(CMAKE\_WINDOWS\_EXPORT\_ALL\_SYMBOLS ON)" and then check the ".vcxproj" project file for dll. If you try to compile a project without "set(CMAKE\_WINDOWS\_EXPORT\_ALL\_SYMBOLS ON)" or with "set(CMAKE\_WINDOWS\_EXPORT\_ALL\_SYMBOLS OFF)" you will get linking errors, due to the fact that symbols are not exported from a dll. More info about this is provided by link: [Understanding Custom Build Steps and Build Events](https://msdn.microsoft.com/en-us/library/e85wte0k.aspx) --- *2.3.2. Without CMake usage* You simple could create a small program for parsing .obj file by youself without CMake usege. Hovewer, I have to admit that CMake is very usefull program especially for cross-platform development.
225,471
<p>I have an <code>ActiveRecord</code> model, <code>Foo</code>, which has a <code>name</code> field. I'd like users to be able to search by name, but I'd like the search to ignore case and any accents. Thus, I'm also storing a <code>canonical_name</code> field against which to search:</p> <pre><code>class Foo validates_presence_of :name before_validate :set_canonical_name private def set_canonical_name self.canonical_name ||= canonicalize(self.name) if self.name end def canonicalize(x) x.downcase. # something here end end </code></pre> <p>I need to fill in the "something here" to replace the accented characters. Is there anything better than</p> <pre><code>x.downcase.gsub(/[àáâãäå]/,'a').gsub(/æ/,'ae').gsub(/ç/, 'c').gsub(/[èéêë]/,'e').... </code></pre> <p>And, for that matter, since I'm not on Ruby 1.9, I can't put those Unicode literals in my code. The actual regular expressions will look much uglier.</p>
[ { "answer_id": 225508, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>You probably want Unicode decomposition (\"NFD\"). After decomposing the string, just filter out anything not in [A-Za-z]. æ will decompose to \"ae\", ã to \"a~\" (approximately - the diacritical will become a separate character) so the filtering leaves a reasonable approximation.</p>\n" }, { "answer_id": 225601, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 1, "selected": false, "text": "<p>iconv:</p>\n\n<p><a href=\"http://groups.google.com/group/ruby-talk-google/browse_frm/thread/8064dcac15d688ce\" rel=\"nofollow noreferrer\">http://groups.google.com/group/ruby-talk-google/browse_frm/thread/8064dcac15d688ce</a>?</p>\n\n<p>=============</p>\n\n<p>a perl module which i can't understand:</p>\n\n<p><a href=\"http://www.ahinea.com/en/tech/accented-translate.html\" rel=\"nofollow noreferrer\">http://www.ahinea.com/en/tech/accented-translate.html</a></p>\n\n<p>============</p>\n\n<p>brute force (there's a lot of htose critters!:</p>\n\n<p><a href=\"http://projects.jkraemer.net/acts_as_ferret/wiki#UTF-8support\" rel=\"nofollow noreferrer\">http://projects.jkraemer.net/acts_as_ferret/wiki#UTF-8support</a></p>\n\n<p><a href=\"http://snippets.dzone.com/posts/show/2384\" rel=\"nofollow noreferrer\">http://snippets.dzone.com/posts/show/2384</a></p>\n" }, { "answer_id": 226090, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>Convert the text to normalization form D, remove all codepoints with unicode category non spacing mark (Mn), and convert it back to normalization form C. This will strip all diacritics, and your problem is reduced to a case insensitive search.</p>\n\n<p>See <a href=\"http://www.siao2.com/2005/02/19/376617.aspx\" rel=\"nofollow noreferrer\">http://www.siao2.com/2005/02/19/376617.aspx</a> and <a href=\"http://www.siao2.com/2007/05/14/2629747.aspx\" rel=\"nofollow noreferrer\">http://www.siao2.com/2007/05/14/2629747.aspx</a> for details.</p>\n" }, { "answer_id": 228871, "author": "Jonke", "author_id": 15638, "author_profile": "https://Stackoverflow.com/users/15638", "pm_score": 3, "selected": false, "text": "<p>I think that you maybe don't really what to go down that path. If you are developing for a market that has these kind of letters your users probably will think you are a sort of ...<em>pip</em>. \nBecause 'å' isn't even close to 'a' in any meaning to a user.\nTake a different road and read up about searching in a non-ascii way. This is just one of those cases someone invented unicode and <a href=\"http://msdn.microsoft.com/en-us/library/ms187582.aspx\" rel=\"nofollow noreferrer\">collation</a>.</p>\n\n<p><strong>A very late PS</strong>:</p>\n\n<p><a href=\"http://www.w3.org/International/wiki/Case_folding\" rel=\"nofollow noreferrer\">http://www.w3.org/International/wiki/Case_folding</a>\n<a href=\"http://www.w3.org/TR/charmod-norm/#sec-WhyNormalization\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/charmod-norm/#sec-WhyNormalization</a></p>\n\n<p>Besides that I have no ide way the link to collation go to a msdn page but I leave it there. It should have been <a href=\"http://www.unicode.org/reports/tr10/\" rel=\"nofollow noreferrer\">http://www.unicode.org/reports/tr10/</a> </p>\n" }, { "answer_id": 292598, "author": "unexist", "author_id": 18179, "author_profile": "https://Stackoverflow.com/users/18179", "pm_score": 7, "selected": true, "text": "<p>Rails has already a builtin for normalizing, you just have to use this to normalize your string to form KD and then remove the other chars (i.e. accent marks) like this:</p>\n\n<pre><code>&gt;&gt; \"àáâãäå\".mb_chars.normalize(:kd).gsub(/[^\\x00-\\x7F]/n,'').downcase.to_s\n=&gt; \"aaaaaa\"\n</code></pre>\n" }, { "answer_id": 474053, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "<p>The key is to use two columns in your database: <code>canonical_text</code> and <code>original_text</code>. Use <code>original_text</code> for display and <code>canonical_text</code> for searches. That way, if a user searches for \"Visual Cafe,\" she sees the \"Visual Café\" result. If she <em>really</em> wants a different item called \"Visual Cafe,\" it can be saved separately.</p>\n\n<p>To get the canonical_text characters in a Ruby 1.8 source file, do something like this:</p>\n\n<pre><code>register_replacement([0x008A].pack('U'), 'S')\n</code></pre>\n" }, { "answer_id": 694292, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>lol.. i just tryed this.. and it is working.. iam still not pretty sure why.. but when i use this 4 lines of code:</p>\n\n<ul>\n<li>str = str.gsub(/[^a-zA-Z0-9 ]/,\"\")</li>\n<li>str = str.gsub(/[ ]+/,\" \")</li>\n<li>str = str.gsub(/ /,\"-\")</li>\n<li>str = str.downcase</li>\n</ul>\n\n<p>it automaticly removes any accent from filenames.. which i was trying to remove(accent from filenames and renaming them than) hope it helped :)</p>\n" }, { "answer_id": 3594796, "author": "Kris", "author_id": 22237, "author_profile": "https://Stackoverflow.com/users/22237", "pm_score": 0, "selected": false, "text": "<p>For anyone reading this wanting to strip all non-ascii characters <a href=\"http://www.jroller.com/obie/tags/unicode\" rel=\"nofollow noreferrer\">this</a> might be useful, I used the first example successfully.</p>\n" }, { "answer_id": 7160536, "author": "Mark Wilden", "author_id": 535425, "author_profile": "https://Stackoverflow.com/users/535425", "pm_score": 7, "selected": false, "text": "<p><code>ActiveSupport::Inflector.transliterate</code> (requires Rails 2.2.1+ and Ruby 1.9 or 1.8.7)</p>\n\n<p>example: </p>\n\n<p><code>&gt;&gt; ActiveSupport::Inflector.transliterate(\"àáâãäå\").to_s\n=&gt; \"aaaaaa\"</code></p>\n" }, { "answer_id": 8870902, "author": "Cheng", "author_id": 115005, "author_profile": "https://Stackoverflow.com/users/115005", "pm_score": 3, "selected": false, "text": "<p>Decompose the string and remove <a href=\"http://ruby.runpaint.org/regexps\" rel=\"noreferrer\">non-spacing marks</a> from it.</p>\n\n<pre><code>irb -ractive_support/all\n&gt; \"àáâãäå\".mb_chars.normalize(:kd).gsub(/\\p{Mn}/, '')\naaaaaa\n</code></pre>\n\n<p>You may also need this if used in a .rb file.</p>\n\n<pre><code># coding: utf-8\n</code></pre>\n\n<p>the <code>normalize(:kd)</code> part here splits out diacriticals where possible (ex: the \"n with tilda\" single character is split into an n followed by a combining diacritical tilda character), and the <code>gsub</code> part then removes all the diacritical characters.</p>\n" }, { "answer_id": 12354036, "author": "fguillen", "author_id": 316700, "author_profile": "https://Stackoverflow.com/users/316700", "pm_score": 4, "selected": false, "text": "<p>I have tried a lot of this approaches but they were not achieving one or several of these requirements:</p>\n\n<ul>\n<li>Respect spaces</li>\n<li>Respect 'ñ' character</li>\n<li>Respect case (I know is not a requirement for the original question but is not difficult to move an string to <em>lowcase</em>)</li>\n</ul>\n\n<p>Has been this:</p>\n\n<pre><code># coding: utf-8\nstring.tr(\n \"ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž\",\n \"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz\"\n)\n</code></pre>\n\n<p>– <a href=\"http://blog.slashpoundbang.com/post/12938588984/remove-all-accents-and-diacritics-from-string-in-ruby\" rel=\"nofollow noreferrer\">http://blog.slashpoundbang.com/post/12938588984/remove-all-accents-and-diacritics-from-string-in-ruby</a></p>\n\n<p>You have to modify a little bit the character list to respect 'ñ' character but is an easy job.</p>\n" }, { "answer_id": 12493448, "author": "eoghan.ocarragain", "author_id": 1036021, "author_profile": "https://Stackoverflow.com/users/1036021", "pm_score": 0, "selected": false, "text": "<p>I had problems getting the foo.mb_chars.normalize(:kd).gsub(/[^\\x00-\\x7F]/n,'').downcase.to_s solution to work. I'm not using Rails and there was some conflict with my activesupport/ruby versions that I couldn't get to the bottom of.</p>\n\n<p>Using the ruby-unf gem seems to be a good substitute:</p>\n\n<pre><code>require 'unf'\nfoo.to_nfd.gsub(/[^\\x00-\\x7F]/n,'').downcase\n</code></pre>\n\n<p>As far as I can tell this does the same thing as .mb_chars.normalize(:kd). Is this correct? Thanks!</p>\n" }, { "answer_id": 16273726, "author": "Sudhir Jonathan", "author_id": 73831, "author_profile": "https://Stackoverflow.com/users/73831", "pm_score": 2, "selected": false, "text": "<p><em>This assumes you use Rails.</em></p>\n\n<pre><code>\"anything\".parameterize.underscore.humanize.downcase\n</code></pre>\n\n<p>Given your requirements, this is probably what I'd do... I think it's neat, simple and will stay up to date in future versions of Rails and Ruby.</p>\n\n<p>Update: dgilperez pointed out that <code>parameterize</code> takes a separator argument, so <code>\"anything\".parameterize(\" \")</code> (deprecated) or <code>\"anything\".parameterize(separator: \" \")</code> is shorter and cleaner.</p>\n" }, { "answer_id": 17809800, "author": "Dorian", "author_id": 407213, "author_profile": "https://Stackoverflow.com/users/407213", "pm_score": 4, "selected": false, "text": "<p>My answer: the <a href=\"http://apidock.com/rails/ActiveSupport/Inflector/parameterize\" rel=\"nofollow noreferrer\">String#parameterize</a> method:</p>\n<pre><code>&quot;Le cœur de la crémiére&quot;.parameterize\n=&gt; &quot;le-coeur-de-la-cremiere&quot;\n</code></pre>\n<p>For non-Rails programs:</p>\n<p>Install activesupport: <code>gem install activesupport</code> then:</p>\n<pre><code>require 'active_support/inflector'\n\n&quot;a&amp;]'s--3\\014\\xC2àáâã3D&quot;.parameterize\n# =&gt; &quot;a-s-3-3d&quot;\n</code></pre>\n" }, { "answer_id": 20586777, "author": "Diego Moreira", "author_id": 957737, "author_profile": "https://Stackoverflow.com/users/957737", "pm_score": 5, "selected": false, "text": "<p>Better yet is to use I18n:</p>\n\n<pre><code>1.9.3-p392 :001 &gt; require \"i18n\"\n =&gt; false\n1.9.3-p392 :002 &gt; I18n.transliterate(\"Olá Mundo!\")\n =&gt; \"Ola Mundo!\"\n</code></pre>\n" }, { "answer_id": 53686995, "author": "user2553863", "author_id": 2553863, "author_profile": "https://Stackoverflow.com/users/2553863", "pm_score": 0, "selected": false, "text": "<p><strong>If you are using PostgreSQL</strong> => 9.4 as your DB adapter, maybe you could add in a migration it's <a href=\"https://www.postgresql.org/docs/9.6/unaccent.html\" rel=\"nofollow noreferrer\">\"unaccent\" extension</a> that I think does what you want, like this:</p>\n\n<pre><code>def self.up\n enable_extension \"unaccent\" # No falla si ya existe\nend\n</code></pre>\n\n<p>In order to test, in the console:</p>\n\n<pre><code>2.3.1 :045 &gt; ActiveRecord::Base.connection.execute(\"SELECT unaccent('unaccent', 'àáâãäåÁÄ')\").first\n =&gt; {\"unaccent\"=&gt;\"aaaaaaAA\"}\n</code></pre>\n\n<p>Notice there is case sensitive up to now.</p>\n\n<p>Then, maybe use it in a scope, like:</p>\n\n<pre><code>scope :with_canonical_name, -&gt; (name) {\n where(\"unaccent(foos.name) iLIKE unaccent('#{name}')\")\n}\n</code></pre>\n\n<p>The iLIKE operator makes the search case insensitive. There is another approach, using <a href=\"https://www.postgresql.org/docs/9.3/citext.html\" rel=\"nofollow noreferrer\">citext</a> data type. <a href=\"https://stackoverflow.com/a/41691993/2553863\">Here</a> is a discussion about this two approaches. Notice also that use of PosgreSQL's lower() function <a href=\"https://www.postgresql.org/docs/9.3/citext.html\" rel=\"nofollow noreferrer\">is not recommended</a>.</p>\n\n<p>This will save you some DB space, since you will no longer require the cannonical_name field, and perhaps make your model simpler, at the cost of some extra processing in each query, in an amount depending of whether you are using iLIKE or citext, and your dataset.</p>\n\n<p><strong>If you are using MySQL</strong> maybe you can <a href=\"https://stackoverflow.com/a/4813651/2553863\">use this simple solution</a>, but I have not tested it.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
I have an `ActiveRecord` model, `Foo`, which has a `name` field. I'd like users to be able to search by name, but I'd like the search to ignore case and any accents. Thus, I'm also storing a `canonical_name` field against which to search: ``` class Foo validates_presence_of :name before_validate :set_canonical_name private def set_canonical_name self.canonical_name ||= canonicalize(self.name) if self.name end def canonicalize(x) x.downcase. # something here end end ``` I need to fill in the "something here" to replace the accented characters. Is there anything better than ``` x.downcase.gsub(/[àáâãäå]/,'a').gsub(/æ/,'ae').gsub(/ç/, 'c').gsub(/[èéêë]/,'e').... ``` And, for that matter, since I'm not on Ruby 1.9, I can't put those Unicode literals in my code. The actual regular expressions will look much uglier.
Rails has already a builtin for normalizing, you just have to use this to normalize your string to form KD and then remove the other chars (i.e. accent marks) like this: ``` >> "àáâãäå".mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n,'').downcase.to_s => "aaaaaa" ```
225,481
<p>I'm using T4 for generating repositories for LINQ to Entities entities. </p> <p>The repository contains (amongst other things) a List method suitable for paging. The documentation for <a href="http://msdn.microsoft.com/en-us/library/bb738474.aspx" rel="nofollow noreferrer">Supported and Unsupported Methods</a> does not mention it, but you can't "call" <code>Skip</code> on a unordered <code>IQueryable</code>. It will raise the following exception:</p> <blockquote> <p>System.NotSupportedException: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'..</p> </blockquote> <p>I solved it by allowing to define a default sorting via a partial method. But I'm having problems checking if the expression tree indeed contains an <code>OrderBy</code>.</p> <p>I've reduced the problem to as less code as possible:</p> <pre><code>public partial class Repository { partial void ProvideDefaultSorting(ref IQueryable&lt;Category&gt; currentQuery); public IQueryable&lt;Category&gt; List(int startIndex, int count) { IQueryable&lt;Category&gt; query = List(); ProvideDefaultSorting(ref query); if (!IsSorted(query)) { query = query.OrderBy(c =&gt; c.CategoryID); } return query.Skip(startIndex).Take(count); } public IQueryable&lt;Category&gt; List(string sortExpression, int startIndex, int count) { return List(sortExpression).Skip(startIndex).Take(count); } public IQueryable&lt;Category&gt; List(string sortExpression) { return AddSortingToTheExpressionTree(List(), sortExpression); } public IQueryable&lt;Category&gt; List() { NorthwindEntities ent = new NorthwindEntities(); return ent.Categories; } private Boolean IsSorted(IQueryable&lt;Category&gt; query) { return query is IOrderedQueryable&lt;Category&gt;; } } public partial class Repository { partial void ProvideDefaultSorting(ref IQueryable&lt;Category&gt; currentQuery) { currentQuery = currentQuery.Where(c =&gt; c.CategoryName.Contains(" ")); // no sorting.. } } </code></pre> <p>This is not my real implementation!</p> <p>But my <strong>question</strong> is, how could I implement the <code>IsSorted</code> method? The problem is that LINQ to Entities query's are always of the type <code>ObjectQuery</code>, which implements <code>IOrderedQueryable</code>.</p> <p>So how should I make sure an <code>OrderBy</code> method is present in the expression tree? Is the only option to parse the tree?</p> <p><strong>Update</strong><br> I've added two other overloads to make clear that it's not about how to add sorting support to the repository, but how to check if the <code>ProvideDefaultSorting</code> partial method has indeed added an <code>OrderBy</code> to the expression tree.</p> <p>The problem is, the first partial class is generate by a template and the implementation of the second part of the partial class is made by a team member at another time. You can compare it with the way the .NET Entity Framework generates the EntityContext, it allows extension points for other developers. So I want to try to make it robust and not crash when the <code>ProvideDefaultSorting</code> is not implemented correctly.</p> <p>So maybe the question is more, how can I confirm that the <code>ProvideDefaultSorting</code> did indeed add sorting to the expression tree.</p> <p><strong>Update 2</strong><br> The new question was answered, and accepted, I think I should change the title to match the question more. Or should I leave the current title because it will lead people with the same problem to this solution?</p>
[ { "answer_id": 225660, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 1, "selected": false, "text": "<p>I'm afraid it's a bit harder than that. You see, the Entity Framework will, in certain circumstances, <a href=\"http://msdn.microsoft.com/en-us/library/bb896317.aspx#OrderingInfoLost\" rel=\"nofollow noreferrer\">silently ignore an OrderBy.</a> So it isn't enough to just look for an OrderBy in the expression tree. The OrderBy has to be in the \"right\" place, and the definition of the \"right\" place is an implementation detail of the Entity Framework.</p>\n\n<p>As you may have guessed by now, I'm in the same place as you are; I'm using the entity repository pattern and doing a Take/Skip on the presentation layer. The solution I have used, which is perhaps not ideal, but good enough for what I'm doing, is to not do any ordering until the last possible moment, to ensure that the OrderBy is always the last thing into the expression tree. So any action which is going to do a Take/Skip (directly or indirectly) inserts an OrderBy first. The code is structured such that this can only happen once.</p>\n" }, { "answer_id": 225749, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Paging depends on Ordering in a strong way. Why not tightly couple the operations? Here's one way to do that:</p>\n\n<p>Support objects</p>\n\n<pre><code>public interface IOrderByExpression&lt;T&gt;\n{\n ApplyOrdering(ref IQueryable&lt;T&gt; query);\n}\n\npublic class OrderByExpression&lt;T, U&gt; : IOrderByExpression&lt;T&gt;\n{\n public IQueryable&lt;T&gt; ApplyOrderBy(ref IQueryable&lt;T&gt; query)\n {\n query = query.OrderBy(exp);\n }\n //TODO OrderByDescending, ThenBy, ThenByDescending methods.\n\n private Expression&lt;Func&lt;T, U&gt;&gt; exp = null;\n\n //TODO bool descending?\n public OrderByExpression (Expression&lt;Func&lt;T, U&gt;&gt; myExpression)\n {\n exp = myExpression;\n }\n}\n</code></pre>\n\n<p>The method under discussion:</p>\n\n<pre><code>public IQueryable&lt;Category&gt; List(int startIndex, int count, IOrderByExpression&lt;Category&gt; ordering)\n{\n NorthwindEntities ent = new NorthwindEntities();\n IQueryable&lt;Category&gt; query = ent.Categories;\n if (ordering == null)\n {\n ordering = new OrderByExpression&lt;Category, int&gt;(c =&gt; c.CategoryID)\n }\n ordering.ApplyOrdering(ref query);\n\n return query.Skip(startIndex).Take(count);\n}\n</code></pre>\n\n<p>Some time later, calling the method:</p>\n\n<pre><code>var query = List(20, 20, new OrderByExpression&lt;Category, string&gt;(c =&gt; c.CategoryName));\n</code></pre>\n" }, { "answer_id": 226349, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<pre><code> ProvideDefaultSorting(ref query);\n if (!IsSorted(query))\n {\n query = query.OrderBy(c =&gt; c.CategoryID);\n }\n</code></pre>\n\n<p>Change to:</p>\n\n<pre><code> //apply a default ordering\n query = query.OrderBy(c =&gt; c.CategoryID);\n //add to the ordering\n ProvideDefaultSorting(ref query);\n</code></pre>\n\n<p>It's not a perfect solution.</p>\n\n<p>It doesn't solve the \"filter in the ordering function\" problem you've stated. It does solve \"I forgot to implement ordering\" or \"I choose not to order\".</p>\n\n<p>I tested this solution in LinqToSql:</p>\n\n<pre><code> public void OrderManyTimes()\n {\n DataClasses1DataContext myDC = new DataClasses1DataContext();\n var query = myDC.Customers.OrderBy(c =&gt; c.Field3);\n query = query.OrderBy(c =&gt; c.Field2);\n query = query.OrderBy(c =&gt; c.Field1);\n\n Console.WriteLine(myDC.GetCommand(query).CommandText);\n\n }\n</code></pre>\n\n<p>Generates (note the reverse order of orderings):</p>\n\n<pre><code>SELECT Field1, Field2, Field3\nFROM [dbo].[Customers] AS [t0]\nORDER BY [t0].[Field1], [t0].[Field2], [t0].[Field3]\n</code></pre>\n" }, { "answer_id": 226700, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": "<p>You can address this in the return type of ProvideDefaultSorting. This code does not build:</p>\n\n<pre><code> public IOrderedQueryable&lt;int&gt; GetOrderedQueryable()\n {\n IQueryable&lt;int&gt; myInts = new List&lt;int&gt;() { 3, 4, 1, 2 }.AsQueryable&lt;int&gt;();\n return myInts.Where(i =&gt; i == 2);\n }\n</code></pre>\n\n<p>This code builds, but is insidious and the coder gets what they deserve.</p>\n\n<pre><code> public IOrderedQueryable&lt;int&gt; GetOrderedQueryable()\n {\n IQueryable&lt;int&gt; myInts = new List&lt;int&gt;() { 3, 4, 1, 2 }.AsQueryable&lt;int&gt;();\n return myInts.Where(i =&gt; i == 2) as IOrderedQueryable&lt;int&gt;;\n }\n</code></pre>\n\n<hr>\n\n<p>Same story with ref (this does not build):</p>\n\n<pre><code> public void GetOrderedQueryable(ref IOrderedQueryable&lt;int&gt; query)\n {\n query = query.Where(i =&gt; i == 2);\n }\n</code></pre>\n" }, { "answer_id": 227160, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "<p>Thanks to David B I've got a the following solution. (I had to add detection for the situation where the partial method was not executed or just returned it's parameter).</p>\n\n<pre><code>public partial class Repository\n{\n partial void ProvideDefaultSorting(ref IOrderedQueryable&lt;Category&gt; currentQuery);\n\n public IQueryable&lt;Category&gt; List(int startIndex, int count)\n {\n NorthwindEntities ent = new NorthwindEntities();\n IOrderedQueryable&lt;Category&gt; query = ent.CategorySet;\n var oldQuery = query;\n ProvideDefaultSorting(ref query);\n if (oldQuery.Equals(query)) // the partial method did nothing with the query, or just didn't exist\n {\n query = query.OrderBy(c =&gt; c.CategoryID);\n }\n return query.Skip(startIndex).Take(count);\n }\n // the rest.. \n}\n\npublic partial class Repository\n{\n partial void ProvideDefaultSorting(ref IOrderedQueryable&lt;Category&gt; currentQuery)\n {\n currentQuery = currentQuery.Where(c =&gt; c.CategoryName.Contains(\" \")).OrderBy(c =&gt; c.CategoryName); // compile time forced sotring\n }\n}\n</code></pre>\n\n<p>It ensures at compile time that if the partial method is implemented, it should at least keep it an IOrderdQueryable.</p>\n\n<p>And when the partial method is not implemented or just returns its parameter, the query will not be changed, and that will use the fallback sort.</p>\n" }, { "answer_id": 6062395, "author": "John Kaster", "author_id": 74137, "author_profile": "https://Stackoverflow.com/users/74137", "pm_score": 0, "selected": false, "text": "<p>I have implemented a solution that sorts whatever collection by its primary key as the default sort order is not specified. Perhaps that will work for you.</p>\n\n<p>See <a href=\"http://johnkaster.wordpress.com/2011/05/19/a-bug-fix-for-system-linq-dynamic-and-a-solution-for-the-entity-framework-4-skip-problem/\" rel=\"nofollow\">http://johnkaster.wordpress.com/2011/05/19/a-bug-fix-for-system-linq-dynamic-and-a-solution-for-the-entity-framework-4-skip-problem/</a> for the discussion and the general-purpose code. (And an incidental bug fix for Dynamic LINQ.)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11098/" ]
I'm using T4 for generating repositories for LINQ to Entities entities. The repository contains (amongst other things) a List method suitable for paging. The documentation for [Supported and Unsupported Methods](http://msdn.microsoft.com/en-us/library/bb738474.aspx) does not mention it, but you can't "call" `Skip` on a unordered `IQueryable`. It will raise the following exception: > > System.NotSupportedException: The method 'Skip' is only supported for > sorted input in LINQ to Entities. The method 'OrderBy' must be called before > the method 'Skip'.. > > > I solved it by allowing to define a default sorting via a partial method. But I'm having problems checking if the expression tree indeed contains an `OrderBy`. I've reduced the problem to as less code as possible: ``` public partial class Repository { partial void ProvideDefaultSorting(ref IQueryable<Category> currentQuery); public IQueryable<Category> List(int startIndex, int count) { IQueryable<Category> query = List(); ProvideDefaultSorting(ref query); if (!IsSorted(query)) { query = query.OrderBy(c => c.CategoryID); } return query.Skip(startIndex).Take(count); } public IQueryable<Category> List(string sortExpression, int startIndex, int count) { return List(sortExpression).Skip(startIndex).Take(count); } public IQueryable<Category> List(string sortExpression) { return AddSortingToTheExpressionTree(List(), sortExpression); } public IQueryable<Category> List() { NorthwindEntities ent = new NorthwindEntities(); return ent.Categories; } private Boolean IsSorted(IQueryable<Category> query) { return query is IOrderedQueryable<Category>; } } public partial class Repository { partial void ProvideDefaultSorting(ref IQueryable<Category> currentQuery) { currentQuery = currentQuery.Where(c => c.CategoryName.Contains(" ")); // no sorting.. } } ``` This is not my real implementation! But my **question** is, how could I implement the `IsSorted` method? The problem is that LINQ to Entities query's are always of the type `ObjectQuery`, which implements `IOrderedQueryable`. So how should I make sure an `OrderBy` method is present in the expression tree? Is the only option to parse the tree? **Update** I've added two other overloads to make clear that it's not about how to add sorting support to the repository, but how to check if the `ProvideDefaultSorting` partial method has indeed added an `OrderBy` to the expression tree. The problem is, the first partial class is generate by a template and the implementation of the second part of the partial class is made by a team member at another time. You can compare it with the way the .NET Entity Framework generates the EntityContext, it allows extension points for other developers. So I want to try to make it robust and not crash when the `ProvideDefaultSorting` is not implemented correctly. So maybe the question is more, how can I confirm that the `ProvideDefaultSorting` did indeed add sorting to the expression tree. **Update 2** The new question was answered, and accepted, I think I should change the title to match the question more. Or should I leave the current title because it will lead people with the same problem to this solution?
You can address this in the return type of ProvideDefaultSorting. This code does not build: ``` public IOrderedQueryable<int> GetOrderedQueryable() { IQueryable<int> myInts = new List<int>() { 3, 4, 1, 2 }.AsQueryable<int>(); return myInts.Where(i => i == 2); } ``` This code builds, but is insidious and the coder gets what they deserve. ``` public IOrderedQueryable<int> GetOrderedQueryable() { IQueryable<int> myInts = new List<int>() { 3, 4, 1, 2 }.AsQueryable<int>(); return myInts.Where(i => i == 2) as IOrderedQueryable<int>; } ``` --- Same story with ref (this does not build): ``` public void GetOrderedQueryable(ref IOrderedQueryable<int> query) { query = query.Where(i => i == 2); } ```
225,496
<p>Today I changed the application pool identity of our ASP.NET application from "Network Service" to a domain user.</p> <p>I added the user to the local group "IIS_WPG", done a iisreset just in case, and everything works fine with IE6 and Firefox 3.0</p> <p>But when I go to the website with IE7, an authentication popup appears, I type my credentials, and then :</p> <pre><code>HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials. Internet Information Services (IIS) </code></pre> <p>Any ideas ?</p>
[ { "answer_id": 228254, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 3, "selected": true, "text": "<p>Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly.</p>\n\n<p>Running as Network Service, your Kerberos SPNs should attached to the machine account. As a domain account, the SPN's need to be on that account.</p>\n\n<p>As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for \"kerberos HotFix\"</p>\n\n<p>To turn off Kerberos for the site:</p>\n\n<p>cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders \"NTLM\"</p>\n\n<p>Where ### is the SiteID from the MetaBase.</p>\n" }, { "answer_id": 228760, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 0, "selected": false, "text": "<p>You can try to disable \"Enable integrated authentication\" in Options, Advanced Settings.\nBut I don't know if there isn't some side effects.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971/" ]
Today I changed the application pool identity of our ASP.NET application from "Network Service" to a domain user. I added the user to the local group "IIS\_WPG", done a iisreset just in case, and everything works fine with IE6 and Firefox 3.0 But when I go to the website with IE7, an authentication popup appears, I type my credentials, and then : ``` HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials. Internet Information Services (IIS) ``` Any ideas ?
Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly. Running as Network Service, your Kerberos SPNs should attached to the machine account. As a domain account, the SPN's need to be on that account. As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for "kerberos HotFix" To turn off Kerberos for the site: cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders "NTLM" Where ### is the SiteID from the MetaBase.
225,513
<p>Is there any way to display scrollabletext in loose xaml? The equivalent in HTML would be </p> <pre><code>&lt;div style="overflow:scroll"&gt;some long bit of text here&lt;/div&gt; </code></pre> <p>Can you do this in loose xaml? </p> <p>From my experiments so far it seems that in loose xaml:</p> <ol> <li>You cannot use TextBox -- it must be TextBlock. </li> <li>TextBlock doesn't seem to have any styling settings which would make it scrollable.</li> <li>ScrollViewer doesn't seem to be allowed in loose xaml.</li> </ol> <p>Any help gratefully appreciated.</p>
[ { "answer_id": 228254, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 3, "selected": true, "text": "<p>Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly.</p>\n\n<p>Running as Network Service, your Kerberos SPNs should attached to the machine account. As a domain account, the SPN's need to be on that account.</p>\n\n<p>As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for \"kerberos HotFix\"</p>\n\n<p>To turn off Kerberos for the site:</p>\n\n<p>cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders \"NTLM\"</p>\n\n<p>Where ### is the SiteID from the MetaBase.</p>\n" }, { "answer_id": 228760, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 0, "selected": false, "text": "<p>You can try to disable \"Enable integrated authentication\" in Options, Advanced Settings.\nBut I don't know if there isn't some side effects.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there any way to display scrollabletext in loose xaml? The equivalent in HTML would be ``` <div style="overflow:scroll">some long bit of text here</div> ``` Can you do this in loose xaml? From my experiments so far it seems that in loose xaml: 1. You cannot use TextBox -- it must be TextBlock. 2. TextBlock doesn't seem to have any styling settings which would make it scrollable. 3. ScrollViewer doesn't seem to be allowed in loose xaml. Any help gratefully appreciated.
Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly. Running as Network Service, your Kerberos SPNs should attached to the machine account. As a domain account, the SPN's need to be on that account. As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for "kerberos HotFix" To turn off Kerberos for the site: cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders "NTLM" Where ### is the SiteID from the MetaBase.
225,542
<p>I have a Makefile that starts by running a tool before applying the build rules (which this tool writes for me). If this tool, which is a python script, exits with a non-null status code, I want GNU Make to stop right there and not go on with building the program.</p> <p>Currently, I do something like this (top level, i.e. column 1):</p> <pre><code>$(info Generating build rules...) $(shell python collect_sources.py) include BuildRules.mk </code></pre> <p>But this does not stop make if <code>collect_sources.py</code> exits with a status code of 1. This also captures the standard output of <code>collect_sources.py</code> but does not print it out, so I have the feeling I'm looking in the wrong direction.</p> <p>If at all possible, the solution should even work when a simple MS-DOS shell is the standard system shell.</p> <p>Any suggestion?</p>
[ { "answer_id": 225626, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 3, "selected": false, "text": "<p>There might be a better way, but I tried the following and it works:</p>\n\n<pre><code>$(if $(shell if your_command; then echo ok; fi), , $(error your_command failed))\n</code></pre>\n\n<p>Here I did assume that <code>your_command</code> does not give any output, but it shouldn't be hard to work around such a situation.</p>\n\n<p>Edit: To make it work with the default Windows shell (and probably any decent shell) you could write <code>your_command &amp;&amp; echo ok</code> instead of the <code>if</code> within the <code>shell</code> function. I do not think this is possible for (older) DOS shells. For these you probably want to adapt <code>your_command</code> or write a wrapper script to print something on error (or success).</p>\n" }, { "answer_id": 226974, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>You should use a regular target to create BuildRules.mk:</p>\n\n<pre><code>BuildRules.mk: collect_sources.py\n python $&lt; &gt;$@\n\ninclude BuildRules.mk\n</code></pre>\n\n<p>This is the standard trick to use when automatically generating dependencies.</p>\n" }, { "answer_id": 227035, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": -1, "selected": false, "text": "<p>Make sure you're not invoking make/gmake with the -k option.</p>\n" }, { "answer_id": 230444, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 3, "selected": true, "text": "<p>Ok, here's my own solution, which is unfortunately not based on the status code of the collect_sources.py script, but which Works For Me (TM) and lets me see any output that the script produces:</p>\n\n<pre><code>SHELL_OUTPUT := $(shell python collect_sources.py 2&gt;&amp;1)\nifeq ($(filter error: [Errno %],$(SHELL_OUTPUT)),)\n $(info $(SHELL_OUTPUT))\nelse\n $(error $(SHELL_OUTPUT))\nendif\n</code></pre>\n\n<p>The script is written so that any error produces an output beginning with <code>\"collect_sources: error:\"</code>. Additionally, if python cannot find or execute the given script, it outputs an error message containing the message <code>\"[Errno 2]\"</code> or similar. So this little piece of code just captures the output (redirecting stderr to stdout) and searches for error messages. If none is found, it simply uses <code>$(info)</code> to print the output, otherwise it uses <code>$(error)</code>, which effectively makes Make stop.</p>\n\n<p>Note that the indentation in the <code>ifeq ... endif</code> is done with spaces. If tabs are used, Make thinks you're trying to invoke a command and complains about it.</p>\n" }, { "answer_id": 49963856, "author": "Alex Cohn", "author_id": 192373, "author_profile": "https://Stackoverflow.com/users/192373", "pm_score": 0, "selected": false, "text": "<p>Fixing <a href=\"https://stackoverflow.com/a/226974/192373\">https://stackoverflow.com/a/226974/192373</a></p>\n\n<pre><code>.PHONY: BuildRules.mk\n\nBuildRules.mk: collect_sources.py\n echo Generating build rules...)\n python $&lt; &gt;$@\n $(MAKE) -f BuildRules.mk\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ]
I have a Makefile that starts by running a tool before applying the build rules (which this tool writes for me). If this tool, which is a python script, exits with a non-null status code, I want GNU Make to stop right there and not go on with building the program. Currently, I do something like this (top level, i.e. column 1): ``` $(info Generating build rules...) $(shell python collect_sources.py) include BuildRules.mk ``` But this does not stop make if `collect_sources.py` exits with a status code of 1. This also captures the standard output of `collect_sources.py` but does not print it out, so I have the feeling I'm looking in the wrong direction. If at all possible, the solution should even work when a simple MS-DOS shell is the standard system shell. Any suggestion?
Ok, here's my own solution, which is unfortunately not based on the status code of the collect\_sources.py script, but which Works For Me (TM) and lets me see any output that the script produces: ``` SHELL_OUTPUT := $(shell python collect_sources.py 2>&1) ifeq ($(filter error: [Errno %],$(SHELL_OUTPUT)),) $(info $(SHELL_OUTPUT)) else $(error $(SHELL_OUTPUT)) endif ``` The script is written so that any error produces an output beginning with `"collect_sources: error:"`. Additionally, if python cannot find or execute the given script, it outputs an error message containing the message `"[Errno 2]"` or similar. So this little piece of code just captures the output (redirecting stderr to stdout) and searches for error messages. If none is found, it simply uses `$(info)` to print the output, otherwise it uses `$(error)`, which effectively makes Make stop. Note that the indentation in the `ifeq ... endif` is done with spaces. If tabs are used, Make thinks you're trying to invoke a command and complains about it.
225,545
<p>I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread? Remember I have no access to WinForm application.</p>
[ { "answer_id": 225556, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 5, "selected": true, "text": "<p>An easy solution in this case is to declare a static control in the library assembly that is created on the Main UI thread. If you want to detect if the library is called from the main thread, then use the following</p>\n\n<pre><code>if (MyLibraryControl.InvokeRequired)\n //do your thing here\n</code></pre>\n" }, { "answer_id": 225565, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>The simplest option (if you have a form/control handy) is to check InvokeRequired.</p>\n\n<p>In the absence if that, you could try using <code>SynchronizationContext</code> to simulate a Post or Send, checking what thread that happens on? Calling Send or Post will switch to the UI thread.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30343/" ]
I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread? Remember I have no access to WinForm application.
An easy solution in this case is to declare a static control in the library assembly that is created on the Main UI thread. If you want to detect if the library is called from the main thread, then use the following ``` if (MyLibraryControl.InvokeRequired) //do your thing here ```
225,548
<p>Where can I find algorithms for image distortions? There are so much info of Blur and other classic algorithms but so little of more complex ones. In particular, I am interested in swirl effect image distortion algorithm.</p>
[ { "answer_id": 225575, "author": "Chris Johnson", "author_id": 23732, "author_profile": "https://Stackoverflow.com/users/23732", "pm_score": 6, "selected": true, "text": "<p>I can't find any references, but I can give a basic idea of how distortion effects work.</p>\n\n<p>The key to the distortion is a function which takes two coordinates (x,y) in the distorted image, and transforms them to coordinates (u,v) in the original image. This specifies the inverse function of the distortion, since it takes the distorted image back to the original image</p>\n\n<p>To generate the distorted image, one loops over x and y, calculates the point (u,v) from (x,y) using the inverse distortion function, and sets the colour components at (x,y) to be the same as those at (u,v) in the original image. One ususally uses interpolation (e.g. <a href=\"http://en.wikipedia.org/wiki/Bilinear_interpolation\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Bilinear_interpolation</a> ) to determine the colour at (u,v), since (u,v) usually does not lie exactly on the centre of a pixel, but rather at some fractional point between pixels.</p>\n\n<p>A swirl is essentially a rotation, where the angle of rotation is dependent on the distance from the centre of the image. An example would be:</p>\n\n<pre><code>a = amount of rotation\nb = size of effect\n\nangle = a*exp(-(x*x+y*y)/(b*b))\nu = cos(angle)*x + sin(angle)*y\nv = -sin(angle)*x + cos(angle)*y\n</code></pre>\n\n<p>Here, I assume for simplicity that the centre of the swirl is at (0,0). The swirl can be put anywhere by subtracting the swirl position coordinates from x and y before the distortion function, and adding them to u and v after it.</p>\n\n<p>There are various swirl effects around: some (like the above) swirl only a localised area, and have the amount of swirl decreasing towards the edge of the image. Others increase the swirling towards the edge of the image. This sort of thing can be done by playing about with the angle= line, e.g.</p>\n\n<pre><code>angle = a*(x*x+y*y)\n</code></pre>\n" }, { "answer_id": 225576, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"http://www.imagemagick.org/script/index.php\" rel=\"nofollow noreferrer\">ImageMagick</a>. It's a image conversion and editing toolkit and has interfaces for all popular languages.</p>\n\n<p>The -displace operator can create swirls with the correct displacement map.</p>\n\n<p>If you are for some reason not satisfied with the ImageMagick interface, you can always take a look at the source code of the filters and go from there.</p>\n" }, { "answer_id": 225585, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>The swirl and others like it are a matrix transformation on the pixel locations. You make a new image and get the color from a position on the image that you get from multiplying the current position by a matrix.</p>\n\n<p>The matrix is dependent on the current position.</p>\n\n<p>here is a good CodeProject showing how to do it</p>\n\n<p><a href=\"http://www.codeproject.com/KB/GDI-plus/displacementfilters.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/GDI-plus/displacementfilters.aspx</a></p>\n" }, { "answer_id": 226574, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": false, "text": "<p>There is a Java implementation of lot of image filters/effects at <a href=\"http://www.jhlabs.com/ip/filters/index.html\" rel=\"noreferrer\" title=\"Jerry&#39;s Java Image Processing Pages\">Jerry's Java Image Filters</a>. Maybe you can take inspiration from there.</p>\n" }, { "answer_id": 1558293, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>there has a new graphic library have many feature</p>\n\n<p><a href=\"http://code.google.com/p/picasso-graphic/\" rel=\"nofollow noreferrer\">http://code.google.com/p/picasso-graphic/</a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25194/" ]
Where can I find algorithms for image distortions? There are so much info of Blur and other classic algorithms but so little of more complex ones. In particular, I am interested in swirl effect image distortion algorithm.
I can't find any references, but I can give a basic idea of how distortion effects work. The key to the distortion is a function which takes two coordinates (x,y) in the distorted image, and transforms them to coordinates (u,v) in the original image. This specifies the inverse function of the distortion, since it takes the distorted image back to the original image To generate the distorted image, one loops over x and y, calculates the point (u,v) from (x,y) using the inverse distortion function, and sets the colour components at (x,y) to be the same as those at (u,v) in the original image. One ususally uses interpolation (e.g. <http://en.wikipedia.org/wiki/Bilinear_interpolation> ) to determine the colour at (u,v), since (u,v) usually does not lie exactly on the centre of a pixel, but rather at some fractional point between pixels. A swirl is essentially a rotation, where the angle of rotation is dependent on the distance from the centre of the image. An example would be: ``` a = amount of rotation b = size of effect angle = a*exp(-(x*x+y*y)/(b*b)) u = cos(angle)*x + sin(angle)*y v = -sin(angle)*x + cos(angle)*y ``` Here, I assume for simplicity that the centre of the swirl is at (0,0). The swirl can be put anywhere by subtracting the swirl position coordinates from x and y before the distortion function, and adding them to u and v after it. There are various swirl effects around: some (like the above) swirl only a localised area, and have the amount of swirl decreasing towards the edge of the image. Others increase the swirling towards the edge of the image. This sort of thing can be done by playing about with the angle= line, e.g. ``` angle = a*(x*x+y*y) ```
225,550
<p>I'm filtering the messages that come to a form with PreFilterMessage like this:</p> <p><code>print("code sample");</code></p> <pre><code> public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_KEYDOWN &amp;&amp; (int)m.WParam == VK_ESCAPE) { this.Close(); return true; } return false; } </code></pre> <p><code>print("code sample");</code></p> <p>but the matter is that form closes only for the first time. After reopening a form it won't close anymore by pressing ESC.</p> <p>How can I accomplish this?</p> <p>Thanks</p>
[ { "answer_id": 225584, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 1, "selected": false, "text": "<p>I don't know if this fits with what you are doing. I usually set Form.CancelButton to the close or cancel button on my form, and it will automatically call the button OnClick when the user hits Esc on the keyboard.</p>\n" }, { "answer_id": 232390, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 0, "selected": false, "text": "<p>According to MSDN</p>\n\n<blockquote>\n <p>The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection. </p>\n</blockquote>\n\n<p>If you Indeed shown you form using <code>ShowDialog()</code>, then calling <code>Close()</code> doesn't dispose off your form. You could still be able to \"reopen\" it later, and probably taht's what you're doing. I'm suspecting that you might have distrupted <code>PreFilterMessage()</code> when you first close it. Have you check if the message loop is still working? Or you should actually do <code>this.Visible = false;</code> or <code>Control.Hide</code>, </p>\n\n<blockquote>\n <p>When the Close method is called on a Form displayed as a modeless window, you cannot call the Show method to make the form visible, because the form's resources have already been released. To hide a form and then make it visible, use the Control..::.Hide method.</p>\n</blockquote>\n\n<p>since you need to \"reopen\" it later. If you are actually expecting the form dispose off, and show a new instance later, then manually call dispose on it, after closing</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm filtering the messages that come to a form with PreFilterMessage like this: `print("code sample");` ``` public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_KEYDOWN && (int)m.WParam == VK_ESCAPE) { this.Close(); return true; } return false; } ``` `print("code sample");` but the matter is that form closes only for the first time. After reopening a form it won't close anymore by pressing ESC. How can I accomplish this? Thanks
I don't know if this fits with what you are doing. I usually set Form.CancelButton to the close or cancel button on my form, and it will automatically call the button OnClick when the user hits Esc on the keyboard.
225,560
<p>I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the <a href="http://us3.php.net/array" rel="nofollow noreferrer">Array Functions</a>, I didn't see one that provides the functionality I need.</p> <p>I have an array (in my case, numerically indexed) that I want to scan for a particular value and, if it's there, remove it. And then, when all instances of that value have been removed, I want to rearrange the array using <a href="http://us3.php.net/manual/en/function.array-values.php" rel="nofollow noreferrer">array_values</a>.</p>
[ { "answer_id": 225566, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://de.php.net/array_diff\" rel=\"nofollow noreferrer\"><code>array_diff</code></a> is what you want.</p>\n\n<pre><code>$array1 = array(\"a\" =&gt; \"green\", \"red\", \"blue\", \"red\");\n$array2 = array(\"b\" =&gt; \"green\", \"yellow\", \"red\");\n$result = array_diff($array1, $array2);\n</code></pre>\n\n<p>Result: <code>\"blue\"</code>.</p>\n" }, { "answer_id": 225632, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 2, "selected": false, "text": "<p>Just to add to this... </p>\n\n<p>array_diff appears to show elements in the first array which don't appear in the second array. It doesn't show those elements which only appear in one or the other array. </p>\n\n<p>e.g. </p>\n\n<pre><code>&lt;?\n$test = \"hello\";\n$array1 = array(\"a\" =&gt; \"green\", \"red\", \"bicycle\", \"red\");\n$array2 = array(\"b\" =&gt; \"green\", \"yellow\", \"red\", \"blue\", \"yellow\", \"pink\");\n$result = array_diff($array1, $array2);\nprint_r ($result);\n?&gt; \n</code></pre>\n\n<p>returns </p>\n\n<pre><code>Array\n(\n [1] =&gt; bicycle\n)\n</code></pre>\n" }, { "answer_id": 225906, "author": "Jrgns", "author_id": 6681, "author_profile": "https://Stackoverflow.com/users/6681", "pm_score": 0, "selected": false, "text": "<p>I like the array_diff function, but I have my one scripted one if you dont want to pass down an array:</p>\n\n<pre><code>function array_unset_value($value, &amp;$array) {\n $key = array_search($value, $array);\n while ($key !== false) {\n unset($array[$key]);\n $key = array_search($value, $array);\n }\n}\n</code></pre>\n" }, { "answer_id": 225911, "author": "Jon", "author_id": 17526, "author_profile": "https://Stackoverflow.com/users/17526", "pm_score": 0, "selected": false, "text": "<p>array_filter does this for you. You just need to provide a filter callback function:</p>\n\n<pre><code>function myFilter($Value){\n if($Value == 'red'){\n return false;\n }\n return true;\n}\n\n$Values = array(\"a\" =&gt; \"green\", \"red\", \"bicycle\", \"red\");\n\n$Values = array_filter($Values, 'myFilter');\n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>array {\n [\"a\"] =&gt; \"green\"\n [1] =&gt; \"bicycle\"\n}\n</code></pre>\n\n<p>The filter function should return true for values you want to keep and false for those you wish to remove. Then just go ahead and use array_values to re-index the array. e.g.</p>\n\n<pre><code>$Values = array_values(array_filter($Values, 'myFilter'));\n</code></pre>\n\n<p>If you are doing this within an object and you want to call a filter method within the object you can use this form for the callback:</p>\n\n<pre><code>array_filter($Values, array($this,'myFilter'));\n</code></pre>\n" }, { "answer_id": 5018290, "author": "Igor M. - PortalPress.org", "author_id": 545672, "author_profile": "https://Stackoverflow.com/users/545672", "pm_score": 0, "selected": false, "text": "<p>Rebuild this \"impossible\" function, I'd suggest :<BR>\nfunction pf_cleanarray($arraytoclean=false,$to_explode=false,$delimiter=false) {\n/* PortalPress.org 2011 [maintain this comment, please] - cleans up an array upto to NULL or makes an array with content; use with care and better not use on even length depending [associative] arrays<BR>\n<BR>\n<BR>\nIt looks terrible, I know, especially without indent on Stackoverflow. But when rebuilding, it can be a very useful, dynamic tool, using just the simplest functions, so you will be able to manipulate keys and values at will on a multi-array. The keyfunction is to delete empty values or make an array with explode, that's clean, but with a little trouble, it can be made into a function that eliminates the elements depending on key or value. - Igor M. -\n<BR>\n<BR>\nSimple example:<BR>\n$A[0][0][0][0][0][0]=\"A\";<BR>\n$A[1][0][0][0][0][0]=\"\";<BR>\n$A[2][0][0][0][0][0]=\"\";<BR>\n$A[0][0][0][0][0][1]=\"\";<BR>\n$A[1][0][0][0][0][1]=\"\";<BR>\n$A[2][0][0][0][0][1]=\"\";<BR>\n$A[0][0][0][0][0][2]=\"\";<BR>\n$A[1][0][0][0][0][2]=\"\";<BR>\n$A[2][0][0][0][0][2]=\"\";<BR>\n$A[0][0][0][0][0][3]=\"\";<BR>\n$A[1][0][0][0][0][3]=\"\";<BR>\n$A[2][0][0][0][0][3]=\"\";<BR>\n$A[0][0][0][0][0][4]=\"\";<BR>\n$A[1][0][0][0][0][4]=\"\";<BR>\n$A[2][0][0][0][0][4]=\"\";<BR>\n$A[0][0][0][0][0][5]=\"\";<BR>\n$A[1][0][0][0][0][5]=\"A\";<BR>\n$A[2][0][0][0][0][5]=\"\";<BR>\nThe $A array:\nArray([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>A[1]=>[2]=>[3]=>[4]=>[5]=>)))))<BR>\n [1]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>[1]=>[2]=>[3]=>[4]=>[5]=>A)))))<BR>\n [2]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>[1]=>[2]=>[3]=>[4]=>[5]=>))))))<BR>\nResults in $A:<BR>\nArray([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>A)))))<BR>\n [1]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>Array([0]=>A))))))<BR>\n*/<BR>\nif($arraytoclean===0 || $arraytoclean) {<BR>\n if(!is_array($arraytoclean)) {<BR>\n if($to_explode &amp;&amp; $delimiter) {<BR>\n $arraytoclean=explode($delimiter,$arraytoclean);<BR>\n } else {<BR>\n $arraytoclean=Array($arraytoclean);<BR>\n }<BR>\n }<BR>\n $nZx=0;<BR>\n $keyarray=array_keys($arraytoclean);<BR>\n for($nYx=0;$nYx\n $keydigit=true;<BR>\n if($keyarray[$nYx]!==$nYx) {<BR>\n $keydigit=false;<BR>\n break;<BR>\n }<BR>\n }<BR>\n for($nYx=0;$nYx\n if(!is_array($arraytoclean[$keyarray[$nYx]])) {<BR>\n if($arraytoclean[$keyarray[$nYx]]) {<BR>\n if(!isset($retarraytoclean)) {<BR>\n $retarraytoclean=Array();<BR>\n }<BR>\n $retarraytoclean[(($keydigit) ? $nZx : $keyarray[$nYx])]=$arraytoclean[$keyarray[$nYx]];<BR>\n $nZx++;<BR>\n }<BR>\n } else {<BR>\n $temparr=pf_cleanarray($arraytoclean[$keyarray[$nYx]]);<BR>\n if($temparr) {<BR>\n if(!isset($retarraytoclean)) {<BR>\n $retarraytoclean=Array();<BR>\n }<BR>\n $retarraytoclean[(($keydigit) ? $nZx : $keyarray[$nYx])]=$temparr;<BR>\n $nZx++;<BR>\n }<BR>\n }<BR>\n }<BR>\n}<BR>\nif(isset($retarraytoclean)) {<BR>\n return($retarraytoclean);<BR>\n} else {<BR>\n return(NULL);<BR>\n}<BR>\n}<BR></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the [Array Functions](http://us3.php.net/array), I didn't see one that provides the functionality I need. I have an array (in my case, numerically indexed) that I want to scan for a particular value and, if it's there, remove it. And then, when all instances of that value have been removed, I want to rearrange the array using [array\_values](http://us3.php.net/manual/en/function.array-values.php).
[`array_diff`](http://de.php.net/array_diff) is what you want. ``` $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); ``` Result: `"blue"`.
225,563
<p>I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely <strong>different parts of the DOM</strong> and mostly positioned using float.</p> <p>All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").</p> <p>Best would be something like this:</p> <pre><code>var distance = getDistance(element1, element2); </code></pre> <p>or in jQuery notation:</p> <pre><code>var distance = $(element1).distanceTo($(element2)); </code></pre>
[ { "answer_id": 225596, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 6, "selected": true, "text": "<p>I never used jQuery, just looked up API, so I can assume you can do the following:</p>\n\n<pre>\nvar o1 = $(element1).offset();\nvar o2 = $(element2).offset();\nvar dx = o1.left - o2.left;\nvar dy = o1.top - o2.top;\nvar distance = Math.sqrt(dx * dx + dy * dy);\n</pre>\n" }, { "answer_id": 225628, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 1, "selected": false, "text": "<p>Using pure javascript.</p>\n\n<pre><code>var dx = obj1.offsetLeft - obj2.offsetLeft;\nvar dy = obj1.offsetTop - obj2.offsetTop;\nvar distance = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2));\n</code></pre>\n" }, { "answer_id": 225760, "author": "Claudio", "author_id": 30122, "author_profile": "https://Stackoverflow.com/users/30122", "pm_score": 1, "selected": false, "text": "<p>What about the following?</p>\n\n<pre><code>var isIE = navigator.appName.indexOf(\"Microsoft\") != -1;\n\nfunction getDistance(obj1, obj2){\n var obj1 = document.getElementById(obj1);\n var obj2 = document.getElementById(obj2);\n var pos1 = getRelativePos(obj1);\n var pos2 = getRelativePos(obj2);\n var dx = pos1.offsetLeft - pos2.offsetLeft;\n var dy = pos1.offsetTop - pos2.offsetTop;\n return {x:dx, y:dy};\n}\nfunction getRelativePos(obj){\nvar pos = {offsetLeft:0,offsetTop:0};\nwhile(obj!=null){\n pos.offsetLeft += obj.offsetLeft;\n pos.offsetTop += obj.offsetTop;\n obj = isIE ? obj.parentElement : obj.offsetParent;\n}\nreturn pos;\n}\n//\nvar obj = getDistance(\"element1\",\"element2\")\nalert(obj.x+\" | \"+obj.y);\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22592/" ]
I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely **different parts of the DOM** and mostly positioned using float. All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever"). Best would be something like this: ``` var distance = getDistance(element1, element2); ``` or in jQuery notation: ``` var distance = $(element1).distanceTo($(element2)); ```
I never used jQuery, just looked up API, so I can assume you can do the following: ``` var o1 = $(element1).offset(); var o2 = $(element2).offset(); var dx = o1.left - o2.left; var dy = o1.top - o2.top; var distance = Math.sqrt(dx * dx + dy * dy); ```
225,598
<p>This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at..</p> <p>For example, compared to..</p> <ul> <li><a href="http://phpundercontrol.org/about.html" rel="noreferrer">phpUnderControl</a></li> <li><a href="http://jenkins-ci.org/content/about-jenkins-ci" rel="noreferrer">Jenkins</a> <ul> <li><a href="http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson" rel="noreferrer">Hudson</a></li> </ul></li> <li><a href="http://cruisecontrolrb.thoughtworks.com/" rel="noreferrer">CruiseControl.rb</a></li> </ul> <p>..and others, <a href="http://buildbot.python.org/stable/" rel="noreferrer">BuildBot</a> looks rather.. archaic</p> <p>I'm currently playing with Hudson, but it is very Java-centric (although with <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html" rel="noreferrer">this guide</a>, I found it easier to setup than BuildBot, and produced more info)</p> <p>Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes?</p> <hr> <p><strong>Update:</strong> Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with <a href="http://jenkins-ci.org" rel="noreferrer">Jenkins</a> is different.</p> <p><strong><em>Update:</em></strong> After trying a few alternatives, I think I'll stick with Hudson. <a href="http://integrityapp.com/" rel="noreferrer">Integrity</a> was nice and simple, but quite limited. I think <a href="http://buildbot.net/trac" rel="noreferrer">Buildbot</a> is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it.</p> <p>Setting Hudson up for a Python project was pretty simple:</p> <ul> <li>Download Hudson from <a href="http://hudson-ci.org/" rel="noreferrer">http://hudson-ci.org/</a></li> <li>Run it with <code>java -jar hudson.war</code></li> <li>Open the web interface on the default address of <code>http://localhost:8080</code></li> <li>Go to Manage Hudson, Plugins, click "Update" or similar</li> <li>Install the Git plugin (I had to set the <code>git</code> path in the Hudson global preferences)</li> <li>Create a new project, enter the repository, SCM polling intervals and so on</li> <li>Install <code>nosetests</code> via <code>easy_install</code> if it's not already</li> <li>In the a build step, add <code>nosetests --with-xunit --verbose</code></li> <li>Check "Publish JUnit test result report" and set "Test report XMLs" to <code>**/nosetests.xml</code></li> </ul> <p>That's all that's required. You can setup email notifications, and <a href="http://wiki.hudson-ci.org/display/HUDSON/Plugins" rel="noreferrer">the plugins</a> are worth a look. A few I'm currently using for Python projects:</p> <ul> <li><a href="http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin" rel="noreferrer">SLOCCount plugin</a> to count lines of code (and graph it!) - you need to install <a href="http://www.dwheeler.com/sloccount/" rel="noreferrer">sloccount</a> separately</li> <li><a href="http://wiki.hudson-ci.org/display/HUDSON/Violations" rel="noreferrer">Violations</a> to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build)</li> <li><a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin" rel="noreferrer">Cobertura</a> can parse the coverage.py output. Nosetest can gather coverage while running your tests, using <code>nosetests --with-coverage</code> (this writes the output to <code>**/coverage.xml</code>)</li> </ul>
[ { "answer_id": 225788, "author": "edomaur", "author_id": 14262, "author_profile": "https://Stackoverflow.com/users/14262", "pm_score": 3, "selected": false, "text": "<p>Don't know if it would do : <a href=\"http://bitten.edgewall.org/\" rel=\"noreferrer\">Bitten</a> is made by the guys who write Trac and is integrated with Trac. <a href=\"http://gump.apache.org/\" rel=\"noreferrer\">Apache Gump</a> is the CI tool used by Apache. It is written in Python.</p>\n" }, { "answer_id": 228196, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 3, "selected": false, "text": "<p>We've had great success with <a href=\"http://www.jetbrains.com/teamcity/\" rel=\"noreferrer\">TeamCity</a> as our CI server and using nose as our test runner. <a href=\"http://pypi.python.org/pypi/teamcity-nose\" rel=\"noreferrer\">Teamcity plugin for nosetests</a> gives you count pass/fail, readable display for failed test( that can be E-Mailed). You can even see details of the test failures while you stack is running. </p>\n\n<p>If of course supports things like running on multiple machines, and it's much simpler to setup and maintain than buildbot.</p>\n" }, { "answer_id": 667800, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 6, "selected": true, "text": "<p>You might want to check out <a href=\"http://somethingaboutorange.com/mrl/projects/nose/\" rel=\"noreferrer\">Nose</a> and <a href=\"http://nose.readthedocs.org/en/latest/plugins/xunit.html\" rel=\"noreferrer\">the Xunit output plugin</a>. You can have it run your unit tests, and coverage checks with this command:</p>\n\n<pre><code>nosetests --with-xunit --enable-cover\n</code></pre>\n\n<p>That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting.</p>\n\n<p>Similarly you can capture the output of pylint using the <a href=\"https://wiki.jenkins-ci.org/display/JENKINS/Violations\" rel=\"noreferrer\">violations plugin for Jenkins</a></p>\n" }, { "answer_id": 2026520, "author": "Noufal Ibrahim", "author_id": 229602, "author_profile": "https://Stackoverflow.com/users/229602", "pm_score": 3, "selected": false, "text": "<p>Buildbot's waterfall page can be considerably prettified. Here's a nice example <a href=\"http://build.chromium.org/buildbot/waterfall/waterfall\" rel=\"noreferrer\">http://build.chromium.org/buildbot/waterfall/waterfall</a></p>\n" }, { "answer_id": 2213516, "author": "Allen", "author_id": 205103, "author_profile": "https://Stackoverflow.com/users/205103", "pm_score": 0, "selected": false, "text": "<p>We have used bitten quite a bit. It is pretty and integrates well with Trac, but it is a pain in the butt to customize if you have any nonstandard workflow. Also there just aren't as many plugins as there are for the more popular tools. Currently we are evaluating Hudson as a replacement.</p>\n" }, { "answer_id": 2535738, "author": "Diego Carrion", "author_id": 303924, "author_profile": "https://Stackoverflow.com/users/303924", "pm_score": 2, "selected": false, "text": "<p>Signal is another option. You can know more about it and watch a video also <a href=\"http://www.diegocarrion.com/2009/10/30/really-easy-continuous-integration-with-signal/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 5119040, "author": "Nick Holden", "author_id": 441462, "author_profile": "https://Stackoverflow.com/users/441462", "pm_score": 3, "selected": false, "text": "<p>I guess this thread is quite old but here is my take on it with hudson:</p>\n\n<p>I decided to go with pip and set up a repo (the painful to get working but nice looking eggbasket), which hudson auto uploads to with a successful tests. Here is my rough and ready script for use with a hudson config execute script like: /var/lib/hudson/venv/main/bin/hudson_script.py -w $WORKSPACE -p my.package -v $BUILD_NUMBER, just put in **/coverage.xml, pylint.txt and nosetests.xml in the config bits:</p>\n\n<pre><code>#!/var/lib/hudson/venv/main/bin/python\nimport os\nimport re\nimport subprocess\nimport logging\nimport optparse\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n#venvDir = \"/var/lib/hudson/venv/main/bin/\"\n\nUPLOAD_REPO = \"http://ldndev01:3442\"\n\ndef call_command(command, cwd, ignore_error_code=False):\n try:\n logging.info(\"Running: %s\" % command)\n status = subprocess.call(command, cwd=cwd, shell=True)\n if not ignore_error_code and status != 0:\n raise Exception(\"Last command failed\")\n\n return status\n\n except:\n logging.exception(\"Could not run command %s\" % command)\n raise\n\ndef main():\n usage = \"usage: %prog [options]\"\n parser = optparse.OptionParser(usage)\n parser.add_option(\"-w\", \"--workspace\", dest=\"workspace\",\n help=\"workspace folder for the job\")\n parser.add_option(\"-p\", \"--package\", dest=\"package\",\n help=\"the package name i.e., back_office.reconciler\")\n parser.add_option(\"-v\", \"--build_number\", dest=\"build_number\",\n help=\"the build number, which will get put at the end of the package version\")\n options, args = parser.parse_args()\n\n if not options.workspace or not options.package:\n raise Exception(\"Need both args, do --help for info\")\n\n venvDir = options.package + \"_venv/\"\n\n #find out if venv is there\n if not os.path.exists(venvDir):\n #make it\n call_command(\"virtualenv %s --no-site-packages\" % venvDir,\n options.workspace)\n\n #install the venv/make sure its there plus install the local package\n call_command(\"%sbin/pip install -e ./ --extra-index %s\" % (venvDir, UPLOAD_REPO),\n options.workspace)\n\n #make sure pylint, nose and coverage are installed\n call_command(\"%sbin/pip install nose pylint coverage epydoc\" % venvDir,\n options.workspace)\n\n #make sure we have an __init__.py\n #this shouldn't be needed if the packages are set up correctly\n #modules = options.package.split(\".\")\n #if len(modules) &gt; 1: \n # call_command(\"touch '%s/__init__.py'\" % modules[0], \n # options.workspace)\n #do the nosetests\n test_status = call_command(\"%sbin/nosetests %s --with-xunit --with-coverage --cover-package %s --cover-erase\" % (venvDir,\n options.package.replace(\".\", \"/\"),\n options.package),\n options.workspace, True)\n #produce coverage report -i for ignore weird missing file errors\n call_command(\"%sbin/coverage xml -i\" % venvDir,\n options.workspace)\n #move it so that the code coverage plugin can find it\n call_command(\"mv coverage.xml %s\" % (options.package.replace(\".\", \"/\")),\n options.workspace)\n #run pylint\n call_command(\"%sbin/pylint --rcfile ~/pylint.rc -f parseable %s &gt; pylint.txt\" % (venvDir, \n options.package),\n options.workspace, True)\n\n #remove old dists so we only have the newest at the end\n call_command(\"rm -rfv %s\" % (options.workspace + \"/dist\"),\n options.workspace)\n\n #if the build passes upload the result to the egg_basket\n if test_status == 0:\n logging.info(\"Success - uploading egg\")\n upload_bit = \"upload -r %s/upload\" % UPLOAD_REPO\n else:\n logging.info(\"Failure - not uploading egg\")\n upload_bit = \"\"\n\n #create egg\n call_command(\"%sbin/python setup.py egg_info --tag-build=.0.%s --tag-svn-revision --tag-date sdist %s\" % (venvDir,\n options.build_number,\n upload_bit),\n options.workspace)\n\n call_command(\"%sbin/epydoc --html --graph all %s\" % (venvDir, options.package),\n options.workspace)\n\n logging.info(\"Complete\")\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>When it comes to deploying stuff you can do something like:</p>\n\n<pre><code>pip -E /location/of/my/venv/ install my_package==X.Y.Z --extra-index http://my_repo\n</code></pre>\n\n<p>And then people can develop stuff using:</p>\n\n<pre><code>pip -E /location/of/my/venv/ install -e ./ --extra-index http://my_repo\n</code></pre>\n\n<p>This stuff assumes you have a repo structure per package with a setup.py and dependencies all set up then you can just check out the trunk and run this stuff on it.</p>\n\n<p>I hope this helps someone out.</p>\n\n<p>------update---------</p>\n\n<p>I've added epydoc which fits in really nicely with hudson. Just add javadoc to your config with the html folder</p>\n\n<p>Note that pip doesn't support the -E flag properly these days, so you have to create your venv separately</p>\n" }, { "answer_id": 6511097, "author": "Russ", "author_id": 465838, "author_profile": "https://Stackoverflow.com/users/465838", "pm_score": 3, "selected": false, "text": "<p>Atlassian's <a href=\"http://www.atlassian.com/software/bamboo\" rel=\"noreferrer\">Bamboo</a> is also definitely worth checking out. The entire Atlassian suite (JIRA, Confluence, FishEye, etc) is pretty sweet.</p>\n" }, { "answer_id": 8572594, "author": "edomaur", "author_id": 14262, "author_profile": "https://Stackoverflow.com/users/14262", "pm_score": 2, "selected": false, "text": "<p>another one : <a href=\"https://www.shiningpanda.com/\" rel=\"nofollow\">Shining Panda</a> is a hosted tool for python</p>\n" }, { "answer_id": 10363583, "author": "Alex Dupuy", "author_id": 18829, "author_profile": "https://Stackoverflow.com/users/18829", "pm_score": 2, "selected": false, "text": "<p>If you're considering hosted CI solution, and doing open source, you should look into <a href=\"http://travis-ci.org/\" rel=\"nofollow\">Travis CI</a> as well - it has very nice integration with GitHub. While it started as a Ruby tool, they have <a href=\"http://about.travis-ci.org/blog/announcing_python_and_perl_support_on_travis_ci/\" rel=\"nofollow\">added Python support</a> a while ago.</p>\n" }, { "answer_id": 13293540, "author": "Paul Biggar", "author_id": 104021, "author_profile": "https://Stackoverflow.com/users/104021", "pm_score": 2, "selected": false, "text": "<p>I would consider <a href=\"https://circleci.com\" rel=\"nofollow\">CircleCi</a> - it has great Python support, and very pretty output.</p>\n" }, { "answer_id": 25107219, "author": "yegor256", "author_id": 187141, "author_profile": "https://Stackoverflow.com/users/187141", "pm_score": 0, "selected": false, "text": "<p>Check <a href=\"http://www.rultor.com\" rel=\"nofollow\">rultor.com</a>. As <a href=\"http://www.yegor256.com/2014/07/29/docker-in-rultor.html\" rel=\"nofollow\">this article</a> explains, it uses Docker for every build. Thanks to that, you can configure whatever you like inside your Docker image, including Python.</p>\n" }, { "answer_id": 27134619, "author": "Jelle", "author_id": 313357, "author_profile": "https://Stackoverflow.com/users/313357", "pm_score": 1, "selected": false, "text": "<p>continuum's <a href=\"http://docs.binstar.org/draft/examples.html#SubmitABuildFromGithub\" rel=\"nofollow\">binstar</a> now is able to trigger builds from github and can compile for linux, osx and windows ( 32 / 64 ). the neat thing is that it really allows you to closely couple distribution and continuous integration. That's crossing the t's and dotting the I's of Integration. The site, workflow and tools are really polished and AFAIK conda is the most robust and pythonic way to distributing complex python modules, where you need to wrap <em>and</em> distribute C/C++/Fotran libraries.</p>\n" }, { "answer_id": 32852066, "author": "Dwight Spencer", "author_id": 522599, "author_profile": "https://Stackoverflow.com/users/522599", "pm_score": 0, "selected": false, "text": "<p>Little disclaimer, I've actually had to build a solution like this for a client that wanted a way to automatically test and deploy <em>any</em> code on a git push plus manage the issue tickets via git notes. This also lead to my work on the <a href=\"https://github.com/denzuko/AIMS\" rel=\"nofollow\">AIMS project</a>.</p>\n\n<p>One could easily just setup a bare node system that has a build user and manage their build through <code>make(1)</code>, <code>expect(1)</code>, <code>crontab(1)</code>/<code>systemd.unit(5)</code>, and <code>incrontab(1)</code>. One could even go a step further and use ansible and celery for distributed builds with a gridfs/nfs file store.</p>\n\n<p>Although, I would not expect anyone other than a Graybeard UNIX guy or Principle level engineer/architect to actually go this far. Just makes for a nice idea and potential learning experience since a build server is nothing more than a way to arbitrarily execute scripted tasks in an automated fashion.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. * [phpUnderControl](http://phpundercontrol.org/about.html) * [Jenkins](http://jenkins-ci.org/content/about-jenkins-ci) + [Hudson](http://blogs.oracle.com/arungupta/entry/top_10_features_of_hudson) * [CruiseControl.rb](http://cruisecontrolrb.thoughtworks.com/) ..and others, [BuildBot](http://buildbot.python.org/stable/) looks rather.. archaic I'm currently playing with Hudson, but it is very Java-centric (although with [this guide](http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html), I found it easier to setup than BuildBot, and produced more info) Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes? --- **Update:** Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with [Jenkins](http://jenkins-ci.org) is different. ***Update:*** After trying a few alternatives, I think I'll stick with Hudson. [Integrity](http://integrityapp.com/) was nice and simple, but quite limited. I think [Buildbot](http://buildbot.net/trac) is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it. Setting Hudson up for a Python project was pretty simple: * Download Hudson from <http://hudson-ci.org/> * Run it with `java -jar hudson.war` * Open the web interface on the default address of `http://localhost:8080` * Go to Manage Hudson, Plugins, click "Update" or similar * Install the Git plugin (I had to set the `git` path in the Hudson global preferences) * Create a new project, enter the repository, SCM polling intervals and so on * Install `nosetests` via `easy_install` if it's not already * In the a build step, add `nosetests --with-xunit --verbose` * Check "Publish JUnit test result report" and set "Test report XMLs" to `**/nosetests.xml` That's all that's required. You can setup email notifications, and [the plugins](http://wiki.hudson-ci.org/display/HUDSON/Plugins) are worth a look. A few I'm currently using for Python projects: * [SLOCCount plugin](http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin) to count lines of code (and graph it!) - you need to install [sloccount](http://www.dwheeler.com/sloccount/) separately * [Violations](http://wiki.hudson-ci.org/display/HUDSON/Violations) to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build) * [Cobertura](http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin) can parse the coverage.py output. Nosetest can gather coverage while running your tests, using `nosetests --with-coverage` (this writes the output to `**/coverage.xml`)
You might want to check out [Nose](http://somethingaboutorange.com/mrl/projects/nose/) and [the Xunit output plugin](http://nose.readthedocs.org/en/latest/plugins/xunit.html). You can have it run your unit tests, and coverage checks with this command: ``` nosetests --with-xunit --enable-cover ``` That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting. Similarly you can capture the output of pylint using the [violations plugin for Jenkins](https://wiki.jenkins-ci.org/display/JENKINS/Violations)
225,617
<p>I'm trying to get this piece of code working a little better. I suspect it's the loop reading one byte at a time. I couldn't find another way of doing this with gzip decompression. Implementing a <code>StreamReader</code> is fine, but it returns a string which I can't pass to the decompression stream.</p> <p>Is there a better way?</p> <pre><code>byte[] bufffer = null; List&lt;byte&gt; resourceBytes = new List&lt;byte&gt;(); int byteValue = 0; WebResource resource = new WebResource(); HttpWebResponse webResponse = null; try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(resourceUri); webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); webRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); webRequest.UserAgent = agent; webRequest.Accept = "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1"; webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.Referer = resourceUri.OriginalString; webRequest.Timeout = 5000; webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream webStream = webResponse.GetResponseStream(); if (!string.IsNullOrEmpty(webResponse.ContentEncoding)) { if (webResponse.ContentEncoding.ToLower().Contains("gzip")) { webStream = new GZipStream(webStream, CompressionMode.Decompress); } else if (webResponse.ContentEncoding.ToLower().Contains("deflate")) { webStream = new DeflateStream(webStream, CompressionMode.Decompress); } } do { byteValue = webStream.ReadByte(); if (byteValue != -1) { resourceBytes.Add((byte)byteValue); } } while (byteValue != -1); //Free up resources webStream.Close(); webResponse.Close(); bufffer = resourceBytes.ToArray(); </code></pre>
[ { "answer_id": 225620, "author": "jmcd", "author_id": 2285, "author_profile": "https://Stackoverflow.com/users/2285", "pm_score": 1, "selected": false, "text": "<p>Is the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx\" rel=\"nofollow noreferrer\">WebClient</a> class no use for what you want to do?</p>\n" }, { "answer_id": 225622, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>If you want the response as a string you can do this.</p>\n\n<pre><code>String ReponseText;\n\nIO.StreamReader ResponseReader = New IO.StreamReader(webStream );\nReponseText= ResponseReader.ReadToEnd();\n</code></pre>\n\n<p>If you want an actual Byte Array do this (Sorry, Don't feel like converting to C# for this one)</p>\n\n<pre><code>'Declare Array Same size as response\nDim ResponseData(webStream .Length) As Byte \n'Read all the data at once\nwebStream.Read(ResponseData, 0, webStream .Length)\n</code></pre>\n" }, { "answer_id": 225634, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>I'd agree with jmcd that WebClient would be far simpler, in particular WebClient.DownloadData.</p>\n\n<p>re the actual question, the problem is that you are reading single bytes, when you should probably have a fixed buffer, and loop - i.e.</p>\n\n<pre><code>int bytesRead;\nbyte[] buffer = new byte[1024];\nwhile((bytesRead = webStream.Read(buffer, 0, buffer.Length)) &gt; 0) {\n // process \"bytesRead\" worth of data from \"buffer\"\n}\n</code></pre>\n\n<p>[edit to add emphasis] The important bit is that you <em>only</em> process \"bytesRead\" worth of data each time; everything beyond there is garbage.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
I'm trying to get this piece of code working a little better. I suspect it's the loop reading one byte at a time. I couldn't find another way of doing this with gzip decompression. Implementing a `StreamReader` is fine, but it returns a string which I can't pass to the decompression stream. Is there a better way? ``` byte[] bufffer = null; List<byte> resourceBytes = new List<byte>(); int byteValue = 0; WebResource resource = new WebResource(); HttpWebResponse webResponse = null; try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(resourceUri); webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); webRequest.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); webRequest.UserAgent = agent; webRequest.Accept = "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1"; webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.Referer = resourceUri.OriginalString; webRequest.Timeout = 5000; webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream webStream = webResponse.GetResponseStream(); if (!string.IsNullOrEmpty(webResponse.ContentEncoding)) { if (webResponse.ContentEncoding.ToLower().Contains("gzip")) { webStream = new GZipStream(webStream, CompressionMode.Decompress); } else if (webResponse.ContentEncoding.ToLower().Contains("deflate")) { webStream = new DeflateStream(webStream, CompressionMode.Decompress); } } do { byteValue = webStream.ReadByte(); if (byteValue != -1) { resourceBytes.Add((byte)byteValue); } } while (byteValue != -1); //Free up resources webStream.Close(); webResponse.Close(); bufffer = resourceBytes.ToArray(); ```
I'd agree with jmcd that WebClient would be far simpler, in particular WebClient.DownloadData. re the actual question, the problem is that you are reading single bytes, when you should probably have a fixed buffer, and loop - i.e. ``` int bytesRead; byte[] buffer = new byte[1024]; while((bytesRead = webStream.Read(buffer, 0, buffer.Length)) > 0) { // process "bytesRead" worth of data from "buffer" } ``` [edit to add emphasis] The important bit is that you *only* process "bytesRead" worth of data each time; everything beyond there is garbage.
225,637
<p>I recently installed RailRoad gem to generate an .svg diagram of my app's models and controllers.</p> <p>The rake task keeps breaking with a similar error:</p> <pre><code>1.8/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:263:in `load_missing_constant': uninitialized constant </code></pre> <p>I tried the rake task on 2 seperate apps and the error keeps appearing with a different "constant" name.</p> <p>Anyone using it with similar problems?</p>
[ { "answer_id": 225837, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 2, "selected": false, "text": "<p>I'm running it without any problems (though I did have to make a quick edit as it was representing the crows feet the wrong way).</p>\n\n<p>This problem <a href=\"http://rubyforge.org/tracker/index.php?func=detail&amp;aid=21153&amp;group_id=3383&amp;atid=12998\" rel=\"nofollow noreferrer\">also appears to be in their tracker</a>. I would go ahead and add your stack trace to that ticket as well. I'm curious if it's your version of ActiveSupport? Bur your version and the version in use are both displaying the same problem so there's got to be a similarity somewhere.</p>\n" }, { "answer_id": 2822679, "author": "Ivan", "author_id": 394133, "author_profile": "https://Stackoverflow.com/users/394133", "pm_score": 0, "selected": false, "text": "<p>could you post the full stack trace? I wonder if you had the same problem as me today: </p>\n\n<pre><code>user@laptop:11:15 AM:rails_app&gt; rake doc:diagrams\n(in /Users/ivan/Sites/lqas)\nrailroad -i -l -a -m -M | dot -Tsvg | sed 's/font-size:14.00/font-size:11.00/g' &gt; doc/models.svg\nrailroad -i -l -C | neato -Tsvg | sed 's/font-size:14.00/font-size:11.00/g' &gt; doc/controllers.svg\nError loading controller classes.\n (Are you running railroad on the aplication's root directory?)\n\n/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- app/controllers/application.rb (MissingSourceFile)\n from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'\n from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'\n from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:521:in `new_constants_in'\n from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/lib/railroad/controllers_diagram.rb:39:in `load_classes'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/lib/railroad/app_diagram.rb:21:in `initialize'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/lib/railroad/controllers_diagram.rb:14:in `initialize'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/bin/railroad:38:in `new'\n from /usr/local/lib/ruby/gems/1.8/gems/railroad-0.5.0/bin/railroad:38\n from /usr/local/bin/railroad:19:in `load'\n from /usr/local/bin/railroad:19\n</code></pre>\n\n<p>I had to comment out the line in lib/railroad/controllers_diagram.rb where it looks for applicaton.rb instead of application_controller.rb as it's now called.</p>\n" }, { "answer_id": 3664263, "author": "Cameron Walsh", "author_id": 441996, "author_profile": "https://Stackoverflow.com/users/441996", "pm_score": 2, "selected": true, "text": "<p>Ivan, and others, try using Bryan Larsen's version from Github: <a href=\"http://github.com/bryanlarsen/railroad\" rel=\"nofollow noreferrer\">http://github.com/bryanlarsen/railroad</a></p>\n" }, { "answer_id": 13154238, "author": "whizcreed", "author_id": 718087, "author_profile": "https://Stackoverflow.com/users/718087", "pm_score": 0, "selected": false, "text": "<p>I banged my head around to get railroad working finally came across <a href=\"https://github.com/bryanlarsen/railroad\" rel=\"nofollow\">rails-erd gem</a>. It woked like a charm. Would recommend it to all facing issues with railroad.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449483/" ]
I recently installed RailRoad gem to generate an .svg diagram of my app's models and controllers. The rake task keeps breaking with a similar error: ``` 1.8/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:263:in `load_missing_constant': uninitialized constant ``` I tried the rake task on 2 seperate apps and the error keeps appearing with a different "constant" name. Anyone using it with similar problems?
Ivan, and others, try using Bryan Larsen's version from Github: <http://github.com/bryanlarsen/railroad>
225,666
<p>I have a CompositeControl that contains a DropDownList.</p> <p>I have set the AutoPostBack property of the DropDownList to true.</p> <p>On the page, I have:</p> <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel" runat="server"&gt; &lt;ContentTemplate&gt; &lt;MyControl:Control ID="CustomControl" runat="server" /&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p>I've also tried setting <strong>ChildrenAsTriggers="true"</strong> and <strong>UpdateMode="Always,"</strong> but neither resolved the problem.</p> <p>The problem is that the UpdatePanel is not intercepting the CompositeControl's DropDownList's post back. (A full POST is being performed when the DropDownList is changed)</p> <p>How can I get the UpdatePanel to handle the postback?</p> <p>Thanks!</p> <p><strong>Edit -- Requested Info</strong></p> <p>Country and states are both DropDownLists in the CompositeControl.</p> <pre><code>country.SelectedIndexChanged += new EventHandler(country_SelectedIndexChanged); protected void country_SelectedIndexChanged(Object sender, EventArgs e) { states.DataSource = XXX; states.DataBind(); } </code></pre>
[ { "answer_id": 225926, "author": "Programmin Tool", "author_id": 21691, "author_profile": "https://Stackoverflow.com/users/21691", "pm_score": 3, "selected": true, "text": "<p>Ok so this may not be the best answer, but I think the problem you're having it that the UpdatePanel just can't see the child control's event. Good news is, it's easy to fix. Say you have a control (CatchMyEvent, which by the way is a crazy clever name) and it has a DropDownList on it. Now you want the parent page to see the SelectedIndexChanged event fire on that list and update a label to match the SelectedItem.Text. As it is, the parent can't really do that. So let's change that:</p>\n\n<pre><code>public partial class CatchMyEvent : System.Web.UI.UserControl\n{\n public delegate void ChangedIndex(object sender, EventArgs e);\n public event ChangedIndex SelectedIndexChanged;\n\n protected override void OnInit(EventArgs e)\n {\n base.OnInit(e);\n dropDownListThrow.SelectedIndexChanged += new EventHandler(dropDownListThrow_SelectedIndexChanged);\n labelOutput.Text = \"no\";\n }\n\n public void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e)\n {\n labelOutput.Text = ((DropDownList)sender).SelectedItem.Text;\n if(SelectedIndexChanged != null)\n {\n SelectedIndexChanged(sender, e);\n }\n }\n}\n</code></pre>\n\n<p>Basically all I did is have the control capture the DropDownList's SelectedIndexChanged event and fired it so that any parent page or control could see it. Essentially all I've done is passed it on. Now on the parent page, it's really easy to capture.</p>\n\n<p>You just need to add an UpdatePanel with a trigger that holds:</p>\n\n<pre><code>&lt;asp:AsyncPostBackTrigger ControlID=\"catchMyEventMain\" EventName=\"SelectedIndexChanged\" /&gt;\n</code></pre>\n\n<p>...and of course add this to the code behind for the parent page:</p>\n\n<pre><code>protected override void OnInit(EventArgs e)\n{\n base.OnInit(e);\n catchMyEventMain.SelectedIndexChanged += dropDownListThrow_SelectedIndexChanged;\n}\n\npublic void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e)\n{ \n labelSelectedValue.Text = ((DropDownList)sender).SelectedItem.Text;\n}\n</code></pre>\n\n<p>Where the label is the before mentioned label. And then let the magic happen.</p>\n\n<p>Also two notes:</p>\n\n<p>1) Don't be an idiot like I was when testing this and forget to set the AutoPostBack property on the DropDownList to true.</p>\n\n<p>2) Make sure the label is in the UpdatePanel's ContentTemplate.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 349430, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I made the following at the end of the BuildControlHierarchy:</p>\n\n<pre><code> ...\n if (DesignMode || Page == null) return;\n\n var sm = ScriptManager.GetCurrent(Page);\n if (sm == null)\n {\n throw new MissingFieldException(\"The ScriptManager is needed on the page!\");\n }\n sm.RegisterAsyncPostBackControl(&lt;control which initiates async postback&gt;);\n</code></pre>\n" }, { "answer_id": 3501091, "author": "tomfanning", "author_id": 17971, "author_profile": "https://Stackoverflow.com/users/17971", "pm_score": 0, "selected": false, "text": "<p>Just make sure every control in your whole hierarchy has an ID set.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/2158033/asp-compositecontrol-scriptmanager\">this question</a>.</p>\n" }, { "answer_id": 18518507, "author": "Finster", "author_id": 2730467, "author_profile": "https://Stackoverflow.com/users/2730467", "pm_score": 2, "selected": false, "text": "<p>I had repeating child controls (textbox and labels) in a ListView, inside an UpdatePanel.</p>\n\n<p>Changing the textbox would cause a full (synch) postback.</p>\n\n<p>I added the PAGE element (the first line in the .aspx page) : ClientIDMode=\"AutoID\"</p>\n\n<p>This fixed the problem for me, and now only the UpdatePanel refreshes - as desired.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8797/" ]
I have a CompositeControl that contains a DropDownList. I have set the AutoPostBack property of the DropDownList to true. On the page, I have: ``` <asp:UpdatePanel ID="UpdatePanel" runat="server"> <ContentTemplate> <MyControl:Control ID="CustomControl" runat="server" /> </ContentTemplate> </asp:UpdatePanel> ``` I've also tried setting **ChildrenAsTriggers="true"** and **UpdateMode="Always,"** but neither resolved the problem. The problem is that the UpdatePanel is not intercepting the CompositeControl's DropDownList's post back. (A full POST is being performed when the DropDownList is changed) How can I get the UpdatePanel to handle the postback? Thanks! **Edit -- Requested Info** Country and states are both DropDownLists in the CompositeControl. ``` country.SelectedIndexChanged += new EventHandler(country_SelectedIndexChanged); protected void country_SelectedIndexChanged(Object sender, EventArgs e) { states.DataSource = XXX; states.DataBind(); } ```
Ok so this may not be the best answer, but I think the problem you're having it that the UpdatePanel just can't see the child control's event. Good news is, it's easy to fix. Say you have a control (CatchMyEvent, which by the way is a crazy clever name) and it has a DropDownList on it. Now you want the parent page to see the SelectedIndexChanged event fire on that list and update a label to match the SelectedItem.Text. As it is, the parent can't really do that. So let's change that: ``` public partial class CatchMyEvent : System.Web.UI.UserControl { public delegate void ChangedIndex(object sender, EventArgs e); public event ChangedIndex SelectedIndexChanged; protected override void OnInit(EventArgs e) { base.OnInit(e); dropDownListThrow.SelectedIndexChanged += new EventHandler(dropDownListThrow_SelectedIndexChanged); labelOutput.Text = "no"; } public void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e) { labelOutput.Text = ((DropDownList)sender).SelectedItem.Text; if(SelectedIndexChanged != null) { SelectedIndexChanged(sender, e); } } } ``` Basically all I did is have the control capture the DropDownList's SelectedIndexChanged event and fired it so that any parent page or control could see it. Essentially all I've done is passed it on. Now on the parent page, it's really easy to capture. You just need to add an UpdatePanel with a trigger that holds: ``` <asp:AsyncPostBackTrigger ControlID="catchMyEventMain" EventName="SelectedIndexChanged" /> ``` ...and of course add this to the code behind for the parent page: ``` protected override void OnInit(EventArgs e) { base.OnInit(e); catchMyEventMain.SelectedIndexChanged += dropDownListThrow_SelectedIndexChanged; } public void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e) { labelSelectedValue.Text = ((DropDownList)sender).SelectedItem.Text; } ``` Where the label is the before mentioned label. And then let the magic happen. Also two notes: 1) Don't be an idiot like I was when testing this and forget to set the AutoPostBack property on the DropDownList to true. 2) Make sure the label is in the UpdatePanel's ContentTemplate. Hope this helps.
225,675
<p>I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. <a href="http://www.python.org/~jeremy/weblog/040204.html" rel="noreferrer">Jeremy Hylton's blog post</a> is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. </p> <p>Here is an (overcomplicated?) example. If people have a simpler one that demos it, I'd like to hear it. The issue: the list comprehensions using next() are filled with the result from the last iteration. </p> <p><strong>edit</strong>: The Problem:</p> <p>What exactly is going on with this, and how do I fix this? Do I have to use a standard for loop? Clearly the function is running the correct number of times, but the list comprehensions end up with the <em>final</em> value instead of the result of each loop.</p> <p>Some hypotheses:</p> <ul> <li>generators?</li> <li>lazy filling of list comprehensions?</li> </ul> <p><strong>code</strong></p> <pre><code>import itertools def digit(n): digit_list = [ (x,False) for x in xrange(1,n+1)] digit_list[0] = (1,True) return itertools.cycle ( digit_list) </code></pre> <pre> >>> D = digit(5) >>> [D.next() for x in range(5)] ## This list comprehension works as expected [(1, True), (2, False), (3, False), (4, False), (5, False)] </pre> <pre><code>class counter(object): def __init__(self): self.counter = [ digit(4) for ii in range(2) ] self.totalcount=0 self.display = [0,] * 2 def next(self): self.totalcount += 1 self.display[-1] = self.counter[-1].next()[0] print self.totalcount, self.display return self.display def next2(self,*args): self._cycle(1) self.totalcount += 1 print self.totalcount, self.display return self.display def _cycle(self,digit): d,first = self.counter[digit].next() #print digit, d, first #print self._display self.display[digit] = d if first and digit &gt; 0: self._cycle(digit-1) C = counter() [C.next() for x in range(5)] [C.next2() for x in range(5)] </code></pre> <p><strong>OUTPUT</strong></p> <pre> In [44]: [C.next() for x in range(6)] 1 [0, 1] 2 [0, 2] 3 [0, 3] 4 [0, 4] 5 [0, 1] 6 [0, 2] Out[44]: [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]] In [45]: [C.next2() for x in range(6)] 7 [0, 3] 8 [0, 4] 9 [1, 1] 10 [1, 2] 11 [1, 3] 12 [1, 4] Out[45]: [[1, 4], [1, 4], [1, 4], [1, 4], [1, 4], [1, 4]] # this should be: [[0,3],[0,4]....[1,4]] or similar </pre>
[ { "answer_id": 225801, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 5, "selected": true, "text": "<p>The problem is that with <code>return self.display</code> you return a <em>reference</em> to this list (not a copy). So what you end up with is a list where each element is a reference to self.display. To illustrate, look at the following:</p>\n\n<pre><code>&gt;&gt;&gt; a = [1,2]\n&gt;&gt;&gt; b = [a,a]\n&gt;&gt;&gt; b\n[[1, 2], [1, 2]]\n&gt;&gt;&gt; a.append(3)\n&gt;&gt;&gt; b\n[[1, 2, 3], [1, 2, 3]]\n</code></pre>\n\n<p>You probably want to use something like <code>return self.display[:]</code>.</p>\n" }, { "answer_id": 231613, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Mind if i refactor this a bit?</p>\n\n<pre><code>def digit(n):\n for i in itertools.count():\n yield (i%n+1, not i%n)\n</code></pre>\n\n<p>But actually you don't need that one, if you implement the whole thing as a simple iterator:</p>\n\n<pre><code>def counter(digits, base):\n counter = [0] * digits\n\n def iterator():\n for total in itertools.count(1):\n for i in range(len(counter)):\n counter[i] = (counter[i] + 1) % base\n if counter[i]:\n break\n print total, list(reversed(counter))\n yield list(reversed(counter))\n\n return iterator()\n\nc = counter(2, 4)\nprint list(itertools.islice(c, 10))\n</code></pre>\n\n<p>If you want to get rid of the print (debugging, is it?), go with a while-loop.</p>\n\n<p>This incindentally also solves your initial problem, because <code>reversed</code> returns a copy of the list.</p>\n\n<p>Oh, and it's zero-based now ;)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15842/" ]
I believe I'm getting bitten by some combination of nested scoping rules and list comprehensions. [Jeremy Hylton's blog post](http://www.python.org/~jeremy/weblog/040204.html) is suggestive about the causes, but I don't really understand CPython's implementation well-enough to figure out how to get around this. Here is an (overcomplicated?) example. If people have a simpler one that demos it, I'd like to hear it. The issue: the list comprehensions using next() are filled with the result from the last iteration. **edit**: The Problem: What exactly is going on with this, and how do I fix this? Do I have to use a standard for loop? Clearly the function is running the correct number of times, but the list comprehensions end up with the *final* value instead of the result of each loop. Some hypotheses: * generators? * lazy filling of list comprehensions? **code** ``` import itertools def digit(n): digit_list = [ (x,False) for x in xrange(1,n+1)] digit_list[0] = (1,True) return itertools.cycle ( digit_list) ``` ``` >>> D = digit(5) >>> [D.next() for x in range(5)] ## This list comprehension works as expected [(1, True), (2, False), (3, False), (4, False), (5, False)] ``` ``` class counter(object): def __init__(self): self.counter = [ digit(4) for ii in range(2) ] self.totalcount=0 self.display = [0,] * 2 def next(self): self.totalcount += 1 self.display[-1] = self.counter[-1].next()[0] print self.totalcount, self.display return self.display def next2(self,*args): self._cycle(1) self.totalcount += 1 print self.totalcount, self.display return self.display def _cycle(self,digit): d,first = self.counter[digit].next() #print digit, d, first #print self._display self.display[digit] = d if first and digit > 0: self._cycle(digit-1) C = counter() [C.next() for x in range(5)] [C.next2() for x in range(5)] ``` **OUTPUT** ``` In [44]: [C.next() for x in range(6)] 1 [0, 1] 2 [0, 2] 3 [0, 3] 4 [0, 4] 5 [0, 1] 6 [0, 2] Out[44]: [[0, 2], [0, 2], [0, 2], [0, 2], [0, 2], [0, 2]] In [45]: [C.next2() for x in range(6)] 7 [0, 3] 8 [0, 4] 9 [1, 1] 10 [1, 2] 11 [1, 3] 12 [1, 4] Out[45]: [[1, 4], [1, 4], [1, 4], [1, 4], [1, 4], [1, 4]] # this should be: [[0,3],[0,4]....[1,4]] or similar ```
The problem is that with `return self.display` you return a *reference* to this list (not a copy). So what you end up with is a list where each element is a reference to self.display. To illustrate, look at the following: ``` >>> a = [1,2] >>> b = [a,a] >>> b [[1, 2], [1, 2]] >>> a.append(3) >>> b [[1, 2, 3], [1, 2, 3]] ``` You probably want to use something like `return self.display[:]`.
225,686
<p>I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?</p> <p>The interface I would like is something like:</p> <pre><code>var x = Foo.Instance; var y = Foo.Instance; // x == y ... x.Release(); // this causes the next Foo.Instance to return a fresh object // also, it assumes no further operations on x/y will be performed. </code></pre> <p>Note - the pattern has to be thread-safe, of course.</p> <p><strong>Edit</strong> - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.</p> <p>I would also prefer a pattern that can be reused, if possible.</p>
[ { "answer_id": 225695, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>At that point I don't think I'd really consider it to be a singleton any more, to be honest.</p>\n\n<p>In particular, if a client uses a singleton they're really not going to expect that they have to dispose of it, and they'd be surprised if someone else did.</p>\n\n<p>What's your production code going to do?</p>\n\n<p>EDIT: If you really, really need this for unit tests and <em>only</em> for unit tests (which sounds questionable in terms of design, to be frank) then you could always fiddle with the field using reflection. It would be nicer to work out whether it should <em>really</em> be a singleton or whether it should <em>really</em> be disposable though - the two very rarely go together.</p>\n" }, { "answer_id": 225747, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>You could use a nested lazy singleton (See <a href=\"http://www.yoda.arachsys.com/csharp/singleton.html\" rel=\"nofollow noreferrer\">here</a>) with some simple modifications:</p>\n\n<pre><code>public sealed class Singleton : IDisposable\n{\n Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n if (!Nested.released)\n return Nested.instance;\n else\n throw new ObjectDisposedException();\n }\n }\n\n public void Dispose()\n {\n disposed = true;\n // Do release stuff here\n }\n\n private bool disposed = false;\n\n class Nested\n {\n // Explicit static constructor to tell C# compiler\n // not to mark type as beforefieldinit\n static Nested()\n {\n }\n\n internal static readonly Singleton instance = new Singleton();\n }\n}\n</code></pre>\n\n<p>Remember to throw ObjectDisposedException in all public methods/properties of the object if it has been disposed.</p>\n\n<p>You should also, provide a finalizer method for the object, in case Dispose doesn't get called. See how to correctly implement IDisposable <a href=\"http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 225758, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 0, "selected": false, "text": "<p>If the class implements IDisposable (as you imply it does) then just call x.Dispose()</p>\n" }, { "answer_id": 225761, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<pre><code> public class Foo : IDisposable\n { [ThreadStatic] static Foo _instance = null;\n\n private Foo() {IsReleased = false;}\n\n public static Foo Instance\n { get\n { if (_instance == null) _instance = new Foo();\n return _instance;\n }\n }\n\n public void Release()\n { IsReleased = true;\n Foo._instance = null;\n }\n\n void IDisposable.Dispose() { Release(); }\n\n public bool IsReleased { get; private set;}\n\n }\n</code></pre>\n" }, { "answer_id": 225762, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "<p>For unit tests you could use a \"manual\" instance (but you would need a way to instantiate the object).</p>\n\n<p>In your case, probably you should better use the factory pattern (abstract/method - whichever is the best for your case), combined with a singleton.</p>\n\n<p>If you want to test if the singleton has disposed properly of the used objects (in unit test), then use the Factory method, otherwise use the singleton pattern.</p>\n\n<p>By the way, if you don't have access to the singleton source code or you are not allowed to modify it, you would better wrap it to another singleton, and provide all the logic from the new one (more like a proxy). It sounds like overkill, but it could be a viable solution.</p>\n\n<p>Also, in order to be able to control the access to it, provide a factory, and let the clients get the new object only if the object hasn't been disposed.</p>\n" }, { "answer_id": 225775, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 2, "selected": false, "text": "<p>Singletons should not be Disposable. Period. If someone calls Dispose prematurely, your application is screwed until it restarts. </p>\n" }, { "answer_id": 225850, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 5, "selected": true, "text": "<p>Mark <code>Release</code> as <code>internal</code> and use the <code>InternalsVisibleTo</code> attribute to expose it only to your unit testing assembly. You can either do that, or if you're wary someone in your own assembly will call it, you can mark it as <code>private</code> and access it using reflection.</p>\n\n<p>Use a finalizer in your singleton that calls the <code>Dispose</code> method on the singleton instance.</p>\n\n<p>In production code, only the unloading of an <code>AppDomain</code> will cause the disposal of the singleton. In the testing code, you can initiate a call to <code>Release</code> yourself.</p>\n" }, { "answer_id": 750268, "author": "Boris Lipschitz", "author_id": 87475, "author_profile": "https://Stackoverflow.com/users/87475", "pm_score": 0, "selected": false, "text": "<p>Another option to make a disposable Singleton is to use SandCastle's <em>[Singleton]</em> atribute for your class, then Castle framework takes care of disposing all disposable Singleton objects</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton? The interface I would like is something like: ``` var x = Foo.Instance; var y = Foo.Instance; // x == y ... x.Release(); // this causes the next Foo.Instance to return a fresh object // also, it assumes no further operations on x/y will be performed. ``` Note - the pattern has to be thread-safe, of course. **Edit** - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it. I would also prefer a pattern that can be reused, if possible.
Mark `Release` as `internal` and use the `InternalsVisibleTo` attribute to expose it only to your unit testing assembly. You can either do that, or if you're wary someone in your own assembly will call it, you can mark it as `private` and access it using reflection. Use a finalizer in your singleton that calls the `Dispose` method on the singleton instance. In production code, only the unloading of an `AppDomain` will cause the disposal of the singleton. In the testing code, you can initiate a call to `Release` yourself.
225,699
<p>Does anyone know if you can programmatically open a .webarchive on the iPhone? A .webarchive is Safari's way of packaging up a webpage and it's associated resources into a single file.</p> <p>I tried creating one and browsing to a link to one in mobile safari, but it didn't work....</p> <p>Note: I was kind of hoping this could be done without a 3rd party app, as it'd be a nice way to package up a WebApp for use on the iphone without needing a third party tool. </p>
[ { "answer_id": 225718, "author": "J Francis", "author_id": 19169, "author_profile": "https://Stackoverflow.com/users/19169", "pm_score": 0, "selected": false, "text": "<p>AirSharing on the iPhone will open webarchive files, but I've no idea if they are doing it all themselves or using native webarchive support.</p>\n\n<p>See <a href=\"http://www.avatron.com/products/\" rel=\"nofollow noreferrer\">http://www.avatron.com/products/</a></p>\n" }, { "answer_id": 225751, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "<p>a .webarchive is just a plist; theoretically, you could read it using NSPropertyListSerialization and then build a local file structure on the phone, then pump that into a UIWebView. Or use AirSharing.</p>\n" }, { "answer_id": 4952387, "author": "Duck", "author_id": 316469, "author_profile": "https://Stackoverflow.com/users/316469", "pm_score": 5, "selected": true, "text": "<p>webarchive is supported on iOS. Just load it on UIWebView. It just works!</p>\n\n<p>for loading a webarchive on your bundle, just do</p>\n\n<pre><code>NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@\"myFile\"\n withExtension:@\"webarchive\"];\n\n[webView loadRequest:[NSURLRequest requestWithURL:fileURL]];\n</code></pre>\n\n<p>webview is your UIWebview</p>\n" }, { "answer_id": 6589723, "author": "Obliquely", "author_id": 531205, "author_profile": "https://Stackoverflow.com/users/531205", "pm_score": 2, "selected": false, "text": "<p>Expanding a little on suggestions above, if you just want to grab the HTML, the following code snippet may be a good starting point. By inspecting the webMainResource dictionary you can extract other material too, such as images.</p>\n\n<pre><code>#define WEB_ARCHIVE @\"Apple Web Archive pasteboard type\"\n\n- (NSString*) htmlStringFromPasteboard;\n{\n NSData* archiveData = [[UIPasteboard generalPasteboard] valueForPasteboardType:WEB_ARCHIVE];\n\n if (archiveData)\n {\n NSError* error = nil;\n id webArchive = [NSPropertyListSerialization propertyListWithData:archiveData options:NSPropertyListImmutable format:NULL error:&amp;error];\n\n if (error)\n {\n return [NSString stringWithFormat:@\"Error: '%@'\", [error localizedDescription]];\n }\n NSDictionary* webMainResource = [webArchive objectForKey:@\"WebMainResource\"];\n NSData * webResourceData = [webMainResource objectForKey:@\"WebResourceData\"];\n\n NSString* string = [[NSString alloc] initWithData:webResourceData encoding:NSUTF8StringEncoding];\n\n return [string autorelease];\n }\n\n return @\"No WebArchive data on the pasteboard just now\";\n\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26510/" ]
Does anyone know if you can programmatically open a .webarchive on the iPhone? A .webarchive is Safari's way of packaging up a webpage and it's associated resources into a single file. I tried creating one and browsing to a link to one in mobile safari, but it didn't work.... Note: I was kind of hoping this could be done without a 3rd party app, as it'd be a nice way to package up a WebApp for use on the iphone without needing a third party tool.
webarchive is supported on iOS. Just load it on UIWebView. It just works! for loading a webarchive on your bundle, just do ``` NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"myFile" withExtension:@"webarchive"]; [webView loadRequest:[NSURLRequest requestWithURL:fileURL]]; ``` webview is your UIWebview
225,700
<p>I am developing a website and for the main navigation, I was thinking it would be a good idea to include the title attribute.</p> <pre><code>&lt;a href="/results/" title="Results"&gt;Results&lt;/a&gt; </code></pre> <p>Is this a good thing to do? Also, is it good for SEO and accessibility?</p>
[ { "answer_id": 225702, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 6, "selected": true, "text": "<p>It is a great thing to do. For accessibility, for SEO, for standards, for good netiquette.<br>\nYou may want to make them slightly more descriptive though: title=\"Results of your Search\" or \"Results of Test #2\"</p>\n" }, { "answer_id": 225706, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "<p>Yes, very important for users of your site using assistive technologies like screenreaders.</p>\n" }, { "answer_id": 225709, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>It also helps if you want to be a bit more verbose and you don't have much space for the real link text.</p>\n" }, { "answer_id": 225712, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 0, "selected": false, "text": "<p>Also, to add to the other answers, if you do any automated testing it's nice to have as many attributes as possible to be able to identify the various widgets.</p>\n" }, { "answer_id": 225715, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://www.netmechanic.com/news/vol2/html_no1.htm\" rel=\"nofollow noreferrer\">this article</a>:</p>\n<blockquote>\n<p>The TITLE attribute is useful in places where your HTML design limits the length of your link text.</p>\n<p>That's often the case for links in a navigation bar, especially if your page has a multi-column layout.</p>\n<p>Try using the TITLE attribute to give your visitors extra navigation information.</p>\n</blockquote>\n<p>There was some concern about the <a href=\"http://www.useit.com/alertbox/980111.html\" rel=\"nofollow noreferrer\">support of this feature</a> in the early days (1998!), but it is now a great way to reinforce the so-called <strong><a href=\"http://www.useit.com/alertbox/20030630.html\" rel=\"nofollow noreferrer\">information scent</a></strong></p>\n" }, { "answer_id": 225750, "author": "Rudi", "author_id": 22830, "author_profile": "https://Stackoverflow.com/users/22830", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://www.w3.org/TR/2007/WD-WCAG20-TECHS-20071211/H33.html\" rel=\"nofollow noreferrer\" title=\"An article from W3C about using titles with links\">H33: Supplementing link text with the title attribute</a>.</p>\n\n<p>It's good to do for the sake of a more semantically meaningful document and potentially adds SEO value, but different browsers have different levels of support for it.</p>\n\n<ul>\n<li>You can't search for title text in a document via the keyboard</li>\n<li>You can't control the appearance, location, or duration of the title element (without replacing titles with some Javascript bastardization)</li>\n<li>People using screen readers might find it awkward to hear both link text and a description of it (although at least with JAWS, you can change a setting to enable / disable this)</li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I am developing a website and for the main navigation, I was thinking it would be a good idea to include the title attribute. ``` <a href="/results/" title="Results">Results</a> ``` Is this a good thing to do? Also, is it good for SEO and accessibility?
It is a great thing to do. For accessibility, for SEO, for standards, for good netiquette. You may want to make them slightly more descriptive though: title="Results of your Search" or "Results of Test #2"
225,711
<p>Any ideas how to stop the system bell from sounding when <kbd>CTRL</kbd>-<kbd>A</kbd> is used to select text in a Winforms application?</p> <p>Here's the problem. Create a Winforms project. Place a text box on the form and add the following event handler on the form to allow <kbd>CTRL</kbd>-<kbd>A</kbd> to select all the text in the textbox (no matter which control has the focus).</p> <pre><code>void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A &amp;&amp; e.Modifiers == Keys.Control) { System.Diagnostics.Debug.WriteLine("Control and A were pressed."); txtContent.SelectionStart = 0; txtContent.SelectionLength = txtContent.Text.Length; txtContent.Focus(); e.Handled = true; } } </code></pre> <p>It works, but despite e.Handled = true, the system bell will sound every time <kbd>CTRL</kbd>-<kbd>A</kbd> is pressed.</p> <hr> <p>Thanks for the reply. </p> <p>KeyPreview on the Form is set to true - but that doesn't stop the system bell from sounding - which is the problem I'm trying to solve - annoying.</p>
[ { "answer_id": 225752, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 1, "selected": false, "text": "<p>This worked for me:</p>\n\n<p>Set the KeyPreview on the Form to True.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 230417, "author": "Blue Waters", "author_id": 30363, "author_profile": "https://Stackoverflow.com/users/30363", "pm_score": 3, "selected": false, "text": "<p>Thanks to an MSDN Forum post - this problem only occurs when textboxes are in multiline mode and you'd like to implement <kbd>Ctrl</kbd>+<kbd>A</kbd> for select all.</p>\n\n<p>Here's the solution</p>\n\n<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n{\n if (keyData == (Keys.A | Keys.Control)) {\n txtContent.SelectionStart = 0;\n txtContent.SelectionLength = txtContent.Text.Length;\n txtContent.Focus();\n return true;\n }\n return base.ProcessCmdKey(ref msg, keyData);\n}\n</code></pre>\n" }, { "answer_id": 493151, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code> private void textBox1_KeyDown(object sender, KeyEventArgs e)\n {\n if (e.Control &amp;&amp; e.KeyCode == Keys.A)\n {\n this.textBox1.SelectAll();\n e.SuppressKeyPress = true;\n }\n }\n</code></pre>\n\n<p>hope this helps</p>\n" }, { "answer_id": 19625057, "author": "Ivan Kochurkin", "author_id": 1046374, "author_profile": "https://Stackoverflow.com/users/1046374", "pm_score": 1, "selected": false, "text": "<p>@H7O solution is good, but I improved it a bit for multiply TextBox components on the form.</p>\n\n<pre><code>private void textBox_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Control &amp;&amp; e.KeyCode == Keys.A)\n {\n ((TextBox)sender).SelectAll();\n e.SuppressKeyPress = true;\n }\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30363/" ]
Any ideas how to stop the system bell from sounding when `CTRL`-`A` is used to select text in a Winforms application? Here's the problem. Create a Winforms project. Place a text box on the form and add the following event handler on the form to allow `CTRL`-`A` to select all the text in the textbox (no matter which control has the focus). ``` void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A && e.Modifiers == Keys.Control) { System.Diagnostics.Debug.WriteLine("Control and A were pressed."); txtContent.SelectionStart = 0; txtContent.SelectionLength = txtContent.Text.Length; txtContent.Focus(); e.Handled = true; } } ``` It works, but despite e.Handled = true, the system bell will sound every time `CTRL`-`A` is pressed. --- Thanks for the reply. KeyPreview on the Form is set to true - but that doesn't stop the system bell from sounding - which is the problem I'm trying to solve - annoying.
``` private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.A) { this.textBox1.SelectAll(); e.SuppressKeyPress = true; } } ``` hope this helps
225,717
<p>Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either <code>int,Int32,uint,short</code> etc.</p> <p>How can I get the actual byte representation? BinaryFormatter.Serialize won't help, since it'll give me more information than I need (it also records type name etc.). The <code>Marshal</code> class does not seem to have facilities to use bytes array (but maybe I'm missing something).</p> <p>Thanks</p>
[ { "answer_id": 225729, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Use BitConverter.GetBytes()</p>\n\n<p>You'll first have to convert the value to it's native type, than use BitConverter to get the bytes:</p>\n\n<pre><code>byte[] Bytes;\n\nif (valType == typeof(int))\n{\n int intVal = (int) GetFieldValue(....);\n Bytes = BitConverter.GetBytes(intVval);\n} \nelse if (valType == typeof(long))\n{\n int lngVal = (long) GetFieldValue(....);\n Bytes = BitConverter.GetBytes(lngVal);\n} else ....\n</code></pre>\n" }, { "answer_id": 225732, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>Do you mean the definitive in-memory representation? BitConverter.GetBytes (with an overload suitably chosen by reflection) will return you <em>a</em> byte representation, but not necessarily what it is currently in memory.</p>\n\n<p>Perhaps if you give more information about why you want this, we'll be better able to help you.</p>\n\n<p>EDIT: I should add that in any sensible case I can think of, BitConverter <em>will</em> give you the same representation as in memory - but there may be odd situations involving endianness and possibly weird architectures with different floating point representations which could give strange results.</p>\n\n<p>EDIT: Here's a complete sample program demonstrating how you might go about it:</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\npublic class Test\n{\n public int x = 300;\n\n static void Main()\n {\n Test instance = new Test();\n FieldInfo field = typeof(Test).GetField(\"x\");\n\n MethodInfo converter = typeof(BitConverter).GetMethod(\"GetBytes\", \n new Type[] {field.FieldType});\n\n if (converter == null)\n {\n Console.WriteLine(\"No BitConverter.GetBytes method found for type \"\n + field.FieldType); \n }\n else\n {\n byte[] bytes = (byte[]) converter.Invoke(null,\n new object[] {field.GetValue(instance) });\n Console.WriteLine(\"Byte array: {0}\", BitConverter.ToString(bytes));\n } \n }\n}\n</code></pre>\n" }, { "answer_id": 225771, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": true, "text": "<p>You may also try code like the following if what you actually want is to transfer structures as a byte array:</p>\n\n<pre><code>int rawsize = Marshal.SizeOf(value);\nbyte[] rawdata = new byte[rawsize];\nGCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);\nMarshal.StructureToPtr(value, handle.AddrOfPinnedObject(), false);\nhandle.Free();\n</code></pre>\n\n<p>This converts the given object <em>value</em> to the byte array rawdata. I've taken this from code I previously wrote, and you may need to adapt it to your needs to make it actually work. I used it for communication with some hardware with user-defined structures, but it should work for built-in types as well (after all, they're structures, aren't they?)</p>\n\n<p>To make structure members properly aligned, use the StructLayout attribute to specify one-byte-alignment:</p>\n\n<pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]\n</code></pre>\n\n<p>And then use the MarshalAs attribute as needed for fields, e.g. for inline arrays:</p>\n\n<pre><code>[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]\nbyte[] _state;\n</code></pre>\n\n<p>The code to get the structure back from the byte array is something like this:</p>\n\n<pre><code>public T GetValue&lt;T&gt;()\n{\n GCHandle handle = GCHandle.Alloc(RawValue, GCHandleType.Pinned);\n T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), \n typeof(T));\n handle.Free();\n return structure;\n}\n</code></pre>\n\n<p>Of course you'll need to know the type you want for this to work.</p>\n\n<p>Note that this will not handle endianness for itself. In my project, most fields were one byte only, so it didn't matter, but for the few fields where it did, I just made the fields private and added public properties that would take care of the endianness (<a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"nofollow noreferrer\">Jon Skeet's link</a> from a comment to his answer may help you, I wrote some utility functions for this since I needed only few).</p>\n\n<p>When I needed this, I created a Message class that would store the raw value (hence the GetValue method, the code at the top is actually the body of a SetValue method) and had some nice convenience method to get the value formatted etc.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either `int,Int32,uint,short` etc. How can I get the actual byte representation? BinaryFormatter.Serialize won't help, since it'll give me more information than I need (it also records type name etc.). The `Marshal` class does not seem to have facilities to use bytes array (but maybe I'm missing something). Thanks
You may also try code like the following if what you actually want is to transfer structures as a byte array: ``` int rawsize = Marshal.SizeOf(value); byte[] rawdata = new byte[rawsize]; GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned); Marshal.StructureToPtr(value, handle.AddrOfPinnedObject(), false); handle.Free(); ``` This converts the given object *value* to the byte array rawdata. I've taken this from code I previously wrote, and you may need to adapt it to your needs to make it actually work. I used it for communication with some hardware with user-defined structures, but it should work for built-in types as well (after all, they're structures, aren't they?) To make structure members properly aligned, use the StructLayout attribute to specify one-byte-alignment: ``` [StructLayout(LayoutKind.Sequential, Pack = 1)] ``` And then use the MarshalAs attribute as needed for fields, e.g. for inline arrays: ``` [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] byte[] _state; ``` The code to get the structure back from the byte array is something like this: ``` public T GetValue<T>() { GCHandle handle = GCHandle.Alloc(RawValue, GCHandleType.Pinned); T structure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return structure; } ``` Of course you'll need to know the type you want for this to work. Note that this will not handle endianness for itself. In my project, most fields were one byte only, so it didn't matter, but for the few fields where it did, I just made the fields private and added public properties that would take care of the endianness ([Jon Skeet's link](http://pobox.com/~skeet/csharp/miscutil) from a comment to his answer may help you, I wrote some utility functions for this since I needed only few). When I needed this, I created a Message class that would store the raw value (hence the GetValue method, the code at the top is actually the body of a SetValue method) and had some nice convenience method to get the value formatted etc.
225,735
<p>Is there an easy way to rename a group of files already contained in a directory, using Python?</p> <p><strong>Example:</strong> I have a directory full of *.doc files and I want to rename them in a consistent way.</p> <blockquote> <p>X.doc -> "new(X).doc"</p> <p>Y.doc -> "new(Y).doc"</p> </blockquote>
[ { "answer_id": 225755, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 3, "selected": false, "text": "<p>Try: <a href=\"http://www.mattweber.org/2007/03/04/python-script-renamepy/\" rel=\"noreferrer\">http://www.mattweber.org/2007/03/04/python-script-renamepy/</a></p>\n\n<blockquote>\n <p>I like to have my music, movie, and\n picture files named a certain way.\n When I download files from the\n internet, they usually don’t follow my\n naming convention. I found myself\n manually renaming each file to fit my\n style. This got old realy fast, so I\n decided to write a program to do it\n for me.</p>\n \n <p>This program can convert the filename\n to all lowercase, replace strings in\n the filename with whatever you want,\n and trim any number of characters from\n the front or back of the filename.</p>\n</blockquote>\n\n<p>The program's source code is also available.</p>\n" }, { "answer_id": 227125, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 8, "selected": true, "text": "<p>Such renaming is quite easy, for example with <a href=\"http://docs.python.org/lib/module-os.html\" rel=\"noreferrer\">os</a> and <a href=\"http://docs.python.org/lib/module-glob.html\" rel=\"noreferrer\">glob</a> modules:</p>\n\n<pre><code>import glob, os\n\ndef rename(dir, pattern, titlePattern):\n for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):\n title, ext = os.path.splitext(os.path.basename(pathAndFilename))\n os.rename(pathAndFilename, \n os.path.join(dir, titlePattern % title + ext))\n</code></pre>\n\n<p>You could then use it in your example like this:</p>\n\n<pre><code>rename(r'c:\\temp\\xx', r'*.doc', r'new(%s)')\n</code></pre>\n\n<p>The above example will convert all <code>*.doc</code> files in <code>c:\\temp\\xx</code> dir to <code>new(%s).doc</code>, where <code>%s</code> is the previous base name of the file (without extension).</p>\n" }, { "answer_id": 227209, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": false, "text": "<p>If you don't mind using regular expressions, then this function would give you much power in renaming files:</p>\n\n<pre><code>import re, glob, os\n\ndef renamer(files, pattern, replacement):\n for pathname in glob.glob(files):\n basename= os.path.basename(pathname)\n new_filename= re.sub(pattern, replacement, basename)\n if new_filename != basename:\n os.rename(\n pathname,\n os.path.join(os.path.dirname(pathname), new_filename))\n</code></pre>\n\n<p>So in your example, you could do (assuming it's the current directory where the files are):</p>\n\n<pre><code>renamer(\"*.doc\", r\"^(.*)\\.doc$\", r\"new(\\1).doc\")\n</code></pre>\n\n<p>but you could also roll back to the initial filenames:</p>\n\n<pre><code>renamer(\"*.doc\", r\"^new\\((.*)\\)\\.doc\", r\"\\1.doc\")\n</code></pre>\n\n<p>and more.</p>\n" }, { "answer_id": 7917798, "author": "Cesar Canassa", "author_id": 360829, "author_profile": "https://Stackoverflow.com/users/360829", "pm_score": 7, "selected": false, "text": "<p>I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:</p>\n\n<p>This replaces all underscores with hyphens in any non-hidden file in the current directory</p>\n\n<pre><code>import os\n[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]\n</code></pre>\n" }, { "answer_id": 10159893, "author": "harisibrahimkv", "author_id": 759163, "author_profile": "https://Stackoverflow.com/users/759163", "pm_score": 3, "selected": false, "text": "<p>I've written a python script on my own. It takes as arguments the path of the directory in which the files are present and the naming pattern that you want to use. However, it renames by attaching an incremental number (1, 2, 3 and so on) to the naming pattern you give.</p>\n\n<pre><code>import os\nimport sys\n\n# checking whether path and filename are given.\nif len(sys.argv) != 3:\n print \"Usage : python rename.py &lt;path&gt; &lt;new_name.extension&gt;\"\n sys.exit()\n\n# splitting name and extension.\nname = sys.argv[2].split('.')\nif len(name) &lt; 2:\n name.append('')\nelse:\n name[1] = \".%s\" %name[1]\n\n# to name starting from 1 to number_of_files.\ncount = 1\n\n# creating a new folder in which the renamed files will be stored.\ns = \"%s/pic_folder\" % sys.argv[1]\ntry:\n os.mkdir(s)\nexcept OSError:\n # if pic_folder is already present, use it.\n pass\n\ntry:\n for x in os.walk(sys.argv[1]):\n for y in x[2]:\n # creating the rename pattern.\n s = \"%spic_folder/%s%s%s\" %(x[0], name[0], count, name[1])\n # getting the original path of the file to be renamed.\n z = os.path.join(x[0],y)\n # renaming.\n os.rename(z, s)\n # incrementing the count.\n count = count + 1\nexcept OSError:\n pass\n</code></pre>\n\n<p>Hope this works for you.</p>\n" }, { "answer_id": 20371910, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 4, "selected": false, "text": "<p>I have this to simply rename all files in subfolders of folder</p>\n\n<pre><code>import os\n\ndef replace(fpath, old_str, new_str):\n for path, subdirs, files in os.walk(fpath):\n for name in files:\n if(old_str.lower() in name.lower()):\n os.rename(os.path.join(path,name), os.path.join(path,\n name.lower().replace(old_str,new_str)))\n</code></pre>\n\n<p>I am replacing all occurences of old_str with any case by new_str.</p>\n" }, { "answer_id": 43704504, "author": "frank__aguirre", "author_id": 5314707, "author_profile": "https://Stackoverflow.com/users/5314707", "pm_score": 2, "selected": false, "text": "<pre><code>directoryName = \"Photographs\"\nfilePath = os.path.abspath(directoryName)\nfilePathWithSlash = filePath + \"\\\\\"\n\nfor counter, filename in enumerate(os.listdir(directoryName)):\n\n filenameWithPath = os.path.join(filePathWithSlash, filename)\n\n os.rename(filenameWithPath, filenameWithPath.replace(filename,\"DSC_\" + \\\n str(counter).zfill(4) + \".jpg\" ))\n\n# e.g. filename = \"photo1.jpg\", directory = \"c:\\users\\Photographs\" \n# The string.replace call swaps in the new filename into \n# the current filename within the filenameWitPath string. Which \n# is then used by os.rename to rename the file in place, using the \n# current (unmodified) filenameWithPath.\n\n# os.listdir delivers the filename(s) from the directory\n# however in attempting to \"rename\" the file using os \n# a specific location of the file to be renamed is required.\n\n# this code is from Windows \n</code></pre>\n" }, { "answer_id": 45734556, "author": "Jayhello", "author_id": 6329006, "author_profile": "https://Stackoverflow.com/users/6329006", "pm_score": 1, "selected": false, "text": "<p>as to me in my directory I have multiple subdir, each subdir has lots of images I want to change all the subdir images to 1.jpg ~ n.jpg</p>\n\n<pre><code>def batch_rename():\n base_dir = 'F:/ad_samples/test_samples/'\n sub_dir_list = glob.glob(base_dir + '*')\n # print sub_dir_list # like that ['F:/dir1', 'F:/dir2']\n for dir_item in sub_dir_list:\n files = glob.glob(dir_item + '/*.jpg')\n i = 0\n for f in files:\n os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))\n i += 1\n</code></pre>\n\n<p>(mys own answer)<a href=\"https://stackoverflow.com/a/45734381/6329006\" title=\"mys own answer\">https://stackoverflow.com/a/45734381/6329006</a></p>\n" }, { "answer_id": 46819382, "author": "Amber Davis", "author_id": 8798132, "author_profile": "https://Stackoverflow.com/users/8798132", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem, but I wanted to append text to the beginning of the file name of all files in a directory and used a similar method. See example below:</p>\n\n<pre><code>folder = r\"R:\\mystuff\\GIS_Projects\\Website\\2017\\PDF\"\n\nimport os\n\n\nfor root, dirs, filenames in os.walk(folder):\n\n\nfor filename in filenames: \n fullpath = os.path.join(root, filename) \n filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])\n print fullpath\n print filename_split[0]\n print filename_split[1]\n os.rename(os.path.join(root, filename), os.path.join(root, \"NewText_2017_\" + filename_split[0] + filename_split[1]))\n</code></pre>\n" }, { "answer_id": 49614494, "author": "Dan", "author_id": 5627860, "author_profile": "https://Stackoverflow.com/users/5627860", "pm_score": 1, "selected": false, "text": "<pre><code># another regex version\n# usage example:\n# replacing an underscore in the filename with today's date\n# rename_files('..\\\\output', '(.*)(_)(.*\\.CSV)', '\\g&lt;1&gt;_20180402_\\g&lt;3&gt;')\ndef rename_files(path, pattern, replacement):\n for filename in os.listdir(path):\n if re.search(pattern, filename):\n new_filename = re.sub(pattern, replacement, filename)\n new_fullname = os.path.join(path, new_filename)\n old_fullname = os.path.join(path, filename)\n os.rename(old_fullname, new_fullname)\n print('Renamed: ' + old_fullname + ' to ' + new_fullname\n</code></pre>\n" }, { "answer_id": 52156458, "author": "Ajay Chandran", "author_id": 5117807, "author_profile": "https://Stackoverflow.com/users/5117807", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Be in the directory where you need to perform the renaming.</p>\n</blockquote>\n\n<pre><code>import os\n# get the file name list to nameList\nnameList = os.listdir() \n#loop through the name and rename\nfor fileName in nameList:\n rename=fileName[15:28]\n os.rename(fileName,rename)\n#example:\n#input fileName bulk like :20180707131932_IMG_4304.JPG\n#output renamed bulk like :IMG_4304.JPG\n</code></pre>\n" }, { "answer_id": 54103383, "author": "murthy annavajhula", "author_id": 9470985, "author_profile": "https://Stackoverflow.com/users/9470985", "pm_score": 0, "selected": false, "text": "<h1>This code will work</h1>\n\n<h1>The function exactly takes two arguments f_patth as your path to rename file and new_name as your new name to the file.</h1>\n\n<pre><code>import glob2\nimport os\n\n\ndef rename(f_path, new_name):\n filelist = glob2.glob(f_path + \"*.ma\")\n count = 0\n for file in filelist:\n print(\"File Count : \", count)\n filename = os.path.split(file)\n print(filename)\n new_filename = f_path + new_name + str(count + 1) + \".ma\"\n os.rename(f_path+filename[1], new_filename)\n print(new_filename)\n count = count + 1\n</code></pre>\n" }, { "answer_id": 57222273, "author": "Jim Shaddix", "author_id": 11842083, "author_profile": "https://Stackoverflow.com/users/11842083", "pm_score": 1, "selected": false, "text": "<p>If you would like to modify file names in an editor (such as vim), the <a href=\"https://click.palletsprojects.com/en/7.x/\" rel=\"nofollow noreferrer\">click</a> library comes with the command <code>click.edit()</code>, which can be used to receive user input from an editor. Here is an example of how it can be used to refactor files in a directory.</p>\n\n<pre><code>import click\nfrom pathlib import Path\n\n# current directory\ndirec_to_refactor = Path(\".\")\n\n# list of old file paths\nold_paths = list(direc_to_refactor.iterdir())\n\n# list of old file names\nold_names = [str(p.name) for p in old_paths]\n\n# modify old file names in an editor,\n# and store them in a list of new file names\nnew_names = click.edit(\"\\n\".join(old_names)).split(\"\\n\")\n\n# refactor the old file names\nfor i in range(len(old_paths)):\n old_paths[i].replace(direc_to_refactor / new_names[i])\n</code></pre>\n\n<p>I wrote a command line application that uses the same technique, but that reduces the volatility of this script, and comes with more options, such as recursive refactoring. Here is the link to the <a href=\"https://github.com/Jim-Shaddix/bulkrename\" rel=\"nofollow noreferrer\">github page</a>. This is useful if you like command line applications, and are interested in making some quick edits to file names. (My application is similar to the \"bulkrename\" command found in <a href=\"https://github.com/ranger/ranger\" rel=\"nofollow noreferrer\">ranger</a>).</p>\n" }, { "answer_id": 68989317, "author": "cappleby", "author_id": 16790441, "author_profile": "https://Stackoverflow.com/users/16790441", "pm_score": 0, "selected": false, "text": "<p>Building off of Cesar Canassa <a href=\"https://stackoverflow.com/a/7917798/16790441\">comment</a> above.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n[os.rename(f, f.replace(f[f.find('___'):], '')) for f in os.listdir('.') if not f.startswith('.')]\n</code></pre>\n<p>This will find three underscores (_) and replace them and everything after them with nothing ('').</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11760/" ]
Is there an easy way to rename a group of files already contained in a directory, using Python? **Example:** I have a directory full of \*.doc files and I want to rename them in a consistent way. > > X.doc -> "new(X).doc" > > > Y.doc -> "new(Y).doc" > > >
Such renaming is quite easy, for example with [os](http://docs.python.org/lib/module-os.html) and [glob](http://docs.python.org/lib/module-glob.html) modules: ``` import glob, os def rename(dir, pattern, titlePattern): for pathAndFilename in glob.iglob(os.path.join(dir, pattern)): title, ext = os.path.splitext(os.path.basename(pathAndFilename)) os.rename(pathAndFilename, os.path.join(dir, titlePattern % title + ext)) ``` You could then use it in your example like this: ``` rename(r'c:\temp\xx', r'*.doc', r'new(%s)') ``` The above example will convert all `*.doc` files in `c:\temp\xx` dir to `new(%s).doc`, where `%s` is the previous base name of the file (without extension).
225,741
<p>Is there a way to set the StartPosition of a Windows Forms form using code? It seems whatever I try results in the StartPostion being the default.</p> <p>Here is what I am doing in the form to display:</p> <pre><code> public DealsForm() { InitializeComponent(); this.StartPosition = FormStartPosition.CenterParent; } </code></pre> <p>Here is what I am doing to display the form:</p> <pre><code> private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { DealsForm frm = new DealsForm(); frm.DataSource = this.Deals; frm.Show(this); } </code></pre> <p>I have tried putting the following in each of the above methods, to no avail:</p> <pre><code>this.StartPosition = FormStartPosition.CenterParent; </code></pre> <p>If I set it via the Property Editor ... it works perfectly, but I would <strong>really</strong> like to do it via code.</p> <p>Should be a no-brainer ... but for the life of me I can't seem to figure it out ... maybe I need more caffeine.</p> <h3>Update:</h3> <p>If I do a <code>ShowDialog()</code> and pass the parent it works ... but I really don't want to show it as a Dialog.</p>
[ { "answer_id": 225767, "author": "Vordreller", "author_id": 11795, "author_profile": "https://Stackoverflow.com/users/11795", "pm_score": -1, "selected": false, "text": "<p>My first reaction is: experiment a bit with VS2008. It should be in the general properties screen.</p>\n\n<p>If you don't have Visual Studio, then it gets a little harder.</p>\n\n<p>A good site to check might be this one: <a href=\"http://en.csharp-online.net/CSharp_Certification%2C_Development%2C_and_Training\" rel=\"nofollow noreferrer\">csharp-online.net</a></p>\n\n<p>Sorry that I can't be more helpfull</p>\n" }, { "answer_id": 225768, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "<p>Did you try to set the property in the calling method?</p>\n\n<pre><code>private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n{\n DealsForm frm = new DealsForm();\n\n frm.DataSource = this.Deals;\n\n // Insert this\n frm.StartPosition = FormStartPosition.CenterParent;\n\n frm.Show(this);\n}\n</code></pre>\n" }, { "answer_id": 225779, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 1, "selected": false, "text": "<pre><code>public DealsForm()\n{\n InitializeComponent();\n this.StartPosition = FormStartPosition.CenterParent; \n}\n</code></pre>\n<p>Try to put it before InitializeComponent(). It might be already too late after InitializeComponent (the form might be already launch and the StatPosition is set too late).</p>\n<h1>Update</h1>\n<p>I just wrote :</p>\n<pre><code>public Form1()\n{\n InitializeComponent();\n this.StartPosition = FormStartPosition.CenterScreen;\n}\n</code></pre>\n<p>And:</p>\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n Form1 f = new Form1();\n f.Show();\n}\n</code></pre>\n<p>In a VS project (brand new) and when I click in my form2 a button it open the form in the middle of the screen. You can do the same with Parent...</p>\n" }, { "answer_id": 225795, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 0, "selected": false, "text": "<p>I'd suggest checking your DealsForm.Designer.cs and removing the line that sets the StartPosition in there, then doing it as you are.</p>\n\n<p>Alternatively, perhaps try setting it in the Load or Shown events of the form instead.</p>\n" }, { "answer_id": 225854, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 5, "selected": true, "text": "<blockquote>\n <p>If I do a ShowDialog() and pass the\n parent it works ... but I really don't\n want to show it as a Dialog.</p>\n</blockquote>\n\n<p>That is correct since ShowDialog would set frm.Parent == nvShowDeals.Parent\n<br>Since you are using .Show() then frm.Parent == null thus FormStartPosition.CenterParent is ignored.</p>\n\n<p>So to accomplish this function I would make the following changes:</p>\n\n<pre><code>public DealsForm()\n{\n InitializeComponent();\n //this.StartPosition = FormStartPosition.CenterParent;\n}\n\n//DealsForm_Load Event\nprivate void DealsForm_Load(object sender, EventArgs e)\n{\n this.Location = this.Owner.Location; //NEW CODE\n}\n</code></pre>\n\n<p>And Here I would make the following changes:</p>\n\n<pre><code>private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)\n{\n DealsForm frm = new DealsForm();\n\n frm.DataSource = this.Deals;\n frm.StartPosition = FormStartPosition.Manual; //NEW CODE\n frm.Show(this);\n}\n</code></pre>\n" }, { "answer_id": 225893, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": false, "text": "<p>Maybe you are not alone. Maybe you are not insane. Read this (Microsoft Connect Customer Feedback):</p>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=107589\" rel=\"noreferrer\">Windows Form StartPosition property only works for .ShowDialog method and not for .Show method</a></p>\n\n<p><em>Customer: \"Windows Form StartPosition only works for .ShowDialog method and not for .Show method. Note: I have also attached simple code and images of the results.\"</em></p>\n\n<p><em>MS: \"Unfortunately, we will not be able to fix this particular issue in a future release, as a fix here would be a breaking change to the behavior of WinForms 1, 1.1 and 2\"</em></p>\n" }, { "answer_id": 10726903, "author": "Justin Pihony", "author_id": 779513, "author_profile": "https://Stackoverflow.com/users/779513", "pm_score": 3, "selected": false, "text": "<p>To center on parent for the .Show call, this is what I had to do:</p>\n\n<pre><code>childForm.Location = new Point(\n (parentForm.Location.X + parentForm.Width / 2) - (childForm.Width / 2), \n (parentForm.Location.Y + parentForm.Height / 2) - (childForm.Height / 2));\nchildForm.StartPosition = FormStartPosition.Manual;\n</code></pre>\n" }, { "answer_id": 17860375, "author": "Si Fitz", "author_id": 2619061, "author_profile": "https://Stackoverflow.com/users/2619061", "pm_score": 3, "selected": false, "text": "<p>You can do this by calling this.CenterToParent() in the Form_Load event (when the parent is actually known). Don't call this in the Constructor because the parent it set when Show(form) is called.</p>\n\n<pre><code>private void myForm_Load(object sender, EventArgs e)\n{\n CenterToParent();\n}\n</code></pre>\n\n<p>I know this thread is old but it can be answered pretty easily so hopefully help others who come across it find the easy solution.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
Is there a way to set the StartPosition of a Windows Forms form using code? It seems whatever I try results in the StartPostion being the default. Here is what I am doing in the form to display: ``` public DealsForm() { InitializeComponent(); this.StartPosition = FormStartPosition.CenterParent; } ``` Here is what I am doing to display the form: ``` private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { DealsForm frm = new DealsForm(); frm.DataSource = this.Deals; frm.Show(this); } ``` I have tried putting the following in each of the above methods, to no avail: ``` this.StartPosition = FormStartPosition.CenterParent; ``` If I set it via the Property Editor ... it works perfectly, but I would **really** like to do it via code. Should be a no-brainer ... but for the life of me I can't seem to figure it out ... maybe I need more caffeine. ### Update: If I do a `ShowDialog()` and pass the parent it works ... but I really don't want to show it as a Dialog.
> > If I do a ShowDialog() and pass the > parent it works ... but I really don't > want to show it as a Dialog. > > > That is correct since ShowDialog would set frm.Parent == nvShowDeals.Parent Since you are using .Show() then frm.Parent == null thus FormStartPosition.CenterParent is ignored. So to accomplish this function I would make the following changes: ``` public DealsForm() { InitializeComponent(); //this.StartPosition = FormStartPosition.CenterParent; } //DealsForm_Load Event private void DealsForm_Load(object sender, EventArgs e) { this.Location = this.Owner.Location; //NEW CODE } ``` And Here I would make the following changes: ``` private void nvShowDeals_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { DealsForm frm = new DealsForm(); frm.DataSource = this.Deals; frm.StartPosition = FormStartPosition.Manual; //NEW CODE frm.Show(this); } ```
225,764
<p>I'm trying to safely update the home directory as specified in <code>/etc/passwd</code>, but the standard Linux utils - usermod and vipw - for doing so aren't provided by Cygwin.</p> <p>Could anyone tell me how they changed this in Cygwin?</p>
[ { "answer_id": 225821, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>I always set HOME as a user-specific environment variable in Computer Properties.</p>\n" }, { "answer_id": 226107, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": true, "text": "<p>I ended up exiting all my cygwin shells and editing it by hand in a text editor. So far, so good.</p>\n\n<p>Note: don't escape the spaces in the \"Documents and Settings\" directory. The entry will look like</p>\n\n<pre><code>user:...:/cygdrive/c/Documents and Settings/user:/bin/bash\n</code></pre>\n\n<p>The line is tokenized on the <code>:</code> character.</p>\n" }, { "answer_id": 327235, "author": "netjeff", "author_id": 41191, "author_profile": "https://Stackoverflow.com/users/41191", "pm_score": 7, "selected": false, "text": "<p><strong>EDIT:</strong> For recent versions of Cygwin (1.7.34 and beyond), see <a href=\"https://stackoverflow.com/q/1494658/1858225\">this newer question</a>.</p>\n\n<p>Like sblundy's answer, you can always edit by-hand.</p>\n\n<p>But if you want to do it the \"official\" way, use the cygwin-specific <a href=\"https://cygwin.com/cygwin-ug-net/mkpasswd.html\" rel=\"noreferrer\"><strong><code>mkpasswd</code></strong></a> command. Below is a snippet from the official docs on <a href=\"https://cygwin.com/cygwin-ug-net/mkpasswd.html\" rel=\"noreferrer\"><code>mkpasswd</code></a> :</p>\n\n<blockquote>\n <p>For example, this command:</p>\n \n <p><strong>Example 3.11. Using an alternate home root</strong></p>\n\n<pre><code>$ mkpasswd -l -p \"$(cygpath -H)\" &gt; /etc/passwd\n</code></pre>\n \n <p>would put local users' home directories in the Windows 'Profiles' directory. </p>\n</blockquote>\n\n<p>There's a bunch of other really useful commands described on the <a href=\"http://cygwin.com/cygwin-ug-net/using-utils.html\" rel=\"noreferrer\"><strong>Cygwin Utilities</strong></a> documentation page (which includes <code>mkpasswd</code>). The use of <code>cygpath</code> in the example above is another of these cygwin-specific tools.</p>\n\n<p>While you're at it, you probably also want to read the <a href=\"http://cygwin.com/cygwin-ug-net/using-effectively.html\" rel=\"noreferrer\">Using Cygwin Effectively with Windows</a> documentation. There's a bunch of really good advice.</p>\n" }, { "answer_id": 361940, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>To avoid problems caused by having spaces in the path to your home directory, use the short-form of the Windows 'Profiles' directory - i.e. <code>/cygdrive/c/DOCUME~1/user</code>. </p>\n\n<p>You can do this by typing the command:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>mkpasswd -l -p \"$(cygpath $(cygpath -dH))\" &gt; /etc/passwd\n</code></pre>\n" }, { "answer_id": 6326095, "author": "Myer", "author_id": 78202, "author_profile": "https://Stackoverflow.com/users/78202", "pm_score": 2, "selected": false, "text": "<p>I like to keep my cygwin installation sync'd to a pen drive and another computer, so I hate hard-coding the home directory. I use the following cygwin.bat:</p>\n\n<pre><code>echo off\nSETLOCAL\nset SHELL=\\\\bin\\\\bash\nset HOME=%~dp0..\\..\\doc\\unix\nbin\\bash --login -i\nENDLOCAL\n</code></pre>\n\n<p>SETLOCAL and ENDLOCAL make sure that SHELL and HOME don't clobber existing env variables for other programs. <code>HOME=%~dp0..\\..\\doc\\unix</code> sets HOME to be two directories up, in the doc/unix subdirectory. Then in ....\\doc\\unix.bashrc, I include <code>PATH=\"/bin:/usr/local/bin:/usr/X11R6/bin:/usr/bin\"</code>.\nI did not use <code>start /wait %CD%\\bin\\bash</code> to start bash, because I am using <a href=\"http://portableapps.com/apps/utilities/console_portable\" rel=\"nofollow\">Console2</a>, so I don't need an additional cmd window.</p>\n" }, { "answer_id": 10321615, "author": "M Smith", "author_id": 850252, "author_profile": "https://Stackoverflow.com/users/850252", "pm_score": 4, "selected": false, "text": "<p>The simplest answer I have found is to make /home to be a soft link to your Windows Home/UserProfile directory</p>\n\n<pre><code>cd /\nmv home oldhome\nln -s \"$(cygpath -H)\" home\n</code></pre>\n\n<p>I used cygpath as it will get the proper location for the HOME directory on the current version of Windows. On my box <code>cygpath -H</code> returns <code>/cygdrive/c/Users</code></p>\n" }, { "answer_id": 10818934, "author": "wyrdR", "author_id": 1426350, "author_profile": "https://Stackoverflow.com/users/1426350", "pm_score": 2, "selected": false, "text": "<h1>Using Windows Environment Variable: HOME</h1>\n\n<p>This works for me for a permanent, non-portable, non-network solution; i.e. setting the HOME Environment variable permanently in Windows.</p>\n\n<p><strong>Note</strong> that this doesn't affect <em>ssh</em> or <em>telnet</em> sessions which always refer to <em>/etc/passwd</em></p>\n\n<p><em><a href=\"http://cygwin.com/faq/faq.setup.html#faq.setup.home\" rel=\"nofollow\" title=\"My HOME environment variable is not what I want.\">ref: Setting up Cygwin- My HOME environment variable is not what I want.</a></em></p>\n\n<h2>CMD</h2>\n\n<p>For <em>current</em> user (needs to run once per user)::</p>\n\n<pre><code>reg add HKCU\\Environment /v HOME /t REG_EXPAND_SZ /d ^%USERPROFILE^%\n</code></pre>\n\n<p>For <em>new</em> Users:</p>\n\n<pre><code>reg add HKU\\.DEFAULT\\Environment /v HOME /t REG_EXPAND_SZ /d ^%USERPROFILE^%\n</code></pre>\n\n<p><strong>Note:</strong> Carets ^ <em>before</em> percent-signs %</p>\n\n<h2>IMPORT REG FILE</h2>\n\n<p>Import this reg file (<em>current</em> user):</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CURRENT_USER\\Environment]\n\"HOME\"=hex(2):25,00,55,00,53,00,45,00,52,00,50,00,52,00,4f,00,46,00,49,00,4c,\\\n 00,45,00,25,00,00,00\n</code></pre>\n\n<p>For <em>new</em> users:</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKU\\.DEFAULT\\Environment]\n\"HOME\"=hex(2):25,00,55,00,53,00,45,00,52,00,50,00,52,00,4f,00,46,00,49,00,4c,\\\n 00,45,00,25,00,00,00\n</code></pre>\n\n<h2>REGEDIT</h2>\n\n<p>In Regedit, under:</p>\n\n<p>For <em>current</em> user:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Environment\n</code></pre>\n\n<p>For <em>new</em> Users:</p>\n\n<pre><code>HKU\\.DEFAULT\\Environment\n</code></pre>\n\n<p>Create <strong>HOME</strong> as a new <em>Expandable String Value</em> (*REG_EXPAND_SZ*) and put in <strong>%USERPROFILE%</strong></p>\n" }, { "answer_id": 26371659, "author": "Pablo Halpern", "author_id": 1005445, "author_profile": "https://Stackoverflow.com/users/1005445", "pm_score": 0, "selected": false, "text": "<p>I edited my /etc/passwd file directly (making sure nothing else would be accessing it), and changed all references to /home to be /Users (on Windows 7). I found that, in order for everything to work correctly, I had to delete any directories in the /home directory (or move them to the appropriate other location). Otherwise, cygwin would develop a split personality where, for example, 'bash -l' would start in /home/Pablo but $HOME would be /Users/Pablo and emacs would appear to do the reverse. Once I deleted /home/Pablo, everything worked fine.</p>\n" }, { "answer_id": 29800987, "author": "Samuel", "author_id": 1045004, "author_profile": "https://Stackoverflow.com/users/1045004", "pm_score": 3, "selected": false, "text": "<p>For the current user the following worked for me:</p>\n\n<ol>\n<li>Close Cygwin.</li>\n<li>Set the HOME Windows user environment variable.</li>\n<li>Start Cygwin.</li>\n<li>run \"mkpasswd -c -p \"$(cygpath -H)\" > /etc/passwd\".</li>\n<li>Restart Cygwin.</li>\n</ol>\n\n<p>I confirmed it worked by running ssh-keygen without any arguments. After making this change the app now defaults to saving the key to /cygdrive/c/Users/user instead of /home/user. </p>\n\n<p>I don't know if setting HOME is required, but I did it anyway per instructions for setting up TortoiseGit with Cygwin using Tortoise's official documentation for unofficial Cygwin support <a href=\"https://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html#tgit-dug-settings-main\">here</a>. Setting HOME alone though was not enough for ssh-keygen to recognize the home directory change.</p>\n\n<p>Also, note that Cygwin's official documentation on this issue can be found <a href=\"http://cygwin.com/cygwin-ug-net/using-utils.html#utils-althome-ex\">here</a>.</p>\n\n<p>Confirmed in Windows 7 using 64-bit Cygwin v1.7.35.</p>\n" }, { "answer_id": 35451482, "author": "kitingChris", "author_id": 1260343, "author_profile": "https://Stackoverflow.com/users/1260343", "pm_score": 1, "selected": false, "text": "<pre><code>cd /home\nrm -rf chris\nln -s /cygdrive/z chris\n</code></pre>\n\n<p>I am not really sure if it is the safest solution but it is a possible solution that works for me ;) </p>\n" }, { "answer_id": 40756931, "author": "Christopher", "author_id": 193617, "author_profile": "https://Stackoverflow.com/users/193617", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Original <a href=\"https://stackoverflow.com/a/11182877/193617\">answer</a> by <a href=\"https://stackoverflow.com/users/193617/christopher\">Christopher</a> from <a href=\"https://stackoverflow.com/q/1494658/193617\">elsewhere</a></p>\n</blockquote>\n\n<h3>Cygwin 1.7.34+</h3>\n\n<p>For those using <strong>Cygwin 1.7.34</strong> or higher Cygwin supports configuring how to fetch home directory, login shell, and gecos information in <code>/etc/nsswitch.conf</code>. This is detailed in the Cygwin User Guide section:</p>\n\n<ul>\n<li><a href=\"https://www.cygwin.com/cygwin-ug-net/ntsec.html#ntsec-mapping-passwdinfo\" rel=\"nofollow noreferrer\">Cygwin user names, home dirs, login shells</a></li>\n</ul>\n\n<p>If you've previously created an <code>/etc/passwd</code> or <code>/etc/group</code> file you'll want to remove those and configure Cygwin using the new Windows Security model to POSIX mappings.</p>\n\n<pre><code>[[ -f /etc/passwd ]] &amp;&amp; mv /etc/passwd /etc/passwd.bak\n[[ -f /etc/group ]] &amp;&amp; mv /etc/group /etc/group.bak\n</code></pre>\n\n<p>The <code>/etc/nsswitch.conf</code> file's <code>db_home:</code> setting defines how Cygwin fetches the user's home directory. The default setting for <code>db_home:</code> is</p>\n\n<pre><code>db_home: /home/%U\n</code></pre>\n\n<p>So by default, Cygwin just sets the home dir to <code>/home/$USERNAME</code>. You can change that though to point at any other custom path you want. The supported wildcard characters are:</p>\n\n<ul>\n<li><code>%u</code> The Cygwin username (that's lowercase u).</li>\n<li><code>%U</code> The Windows username (that's uppercase U).</li>\n<li><code>%D</code> Windows domain in NetBIOS style.</li>\n<li><code>%H</code> Windows home directory in POSIX style. Note that, for the <code>db_home:</code> setting, this only makes sense right after the preceeding slash, as in <code>db_home: /%H/cygwin</code></li>\n<li><code>%_</code> Since space and TAB characters are used to separate the schemata, a space in the filename has to be given as <code>%_</code> (that's an underscore).</li>\n<li><code>%%</code> A per-cent character.</li>\n</ul>\n\n<p>In place of a path, you can specify one of four named path schemata that are predefined. </p>\n\n<ol>\n<li><p><code>windows</code> The user's home directory is set to the same directory which is used as Windows home directory, typically something along the lines of <code>%USERPROFILE%</code> or <code>C:\\Users\\$USERNAME</code>. Of course, the Windows directory is converted to POSIX-style by Cygwin.</p></li>\n<li><p><code>cygwin</code> AD only: The user's home directory is set to the POSIX path given in the cygwinHome attribute from the cygwinUser auxiliary class. See also <a href=\"https://www.cygwin.com/cygwin-ug-net/ntsec.html#ntsec-mapping-nsswitch-cygwin\" rel=\"nofollow noreferrer\">the section called “The cygwin schema”</a>.</p></li>\n<li><p><code>unix</code> AD only: The user's home directory is set to the POSIX path given in the unixHomeDirectory attribute from the posixAccount auxiliary class. See also <a href=\"https://www.cygwin.com/cygwin-ug-net/ntsec.html#ntsec-mapping-nsswitch-cygwin\" rel=\"nofollow noreferrer\">the section called “The unix schema”</a>.</p></li>\n<li><p><code>desc</code> The user's home directory is set to the POSIX path given in the home=\"...\" XML-alike setting in the user's description attribute in SAM or AD. See the section called “The desc schema” for a detailed description.</p></li>\n</ol>\n\n<p>The following will make the user's home directory in Cygwin the same as is used for the Windows home directory.</p>\n\n<pre><code>db_home: windows\n</code></pre>\n\n<h3>Cygwin 1.7.33 or earlier</h3>\n\n<p>For those using <strong>Cygwin 1.7.33</strong> or earlier, update to <a href=\"https://cygwin.org/install.html\" rel=\"nofollow noreferrer\">the latest version Cygwin</a> and remove previously used <code>/etc/passwd</code> and <code>/etc/group</code> files, then see the steps above.</p>\n\n<p>Else, follow these older steps below.</p>\n\n<p>Firstly, set a Windows environment variable for HOME that points to your user profile:</p>\n\n<ol>\n<li>Open <em>System</em> on the <em>Control Panel</em></li>\n<li>On the <em>Advanced</em> tab click <em>Environment Variables</em> (toward the bottom) </li>\n<li>In the User Variables area click \"New…\"</li>\n<li>For Variable name enter <code>HOME</code></li>\n<li>For Variable value enter <code>%USERPROFILE%</code></li>\n<li>Click OK in all the open dialog boxes to apply this new setting</li>\n</ol>\n\n<p>Now we are going to update the Cygwin <code>/etc/passwd</code> file with the Windows <code>%HOME%</code> variable we just created. Shell logins and remote logins via <code>ssh</code> will rely on <code>/etc/passwd</code> to tell them the location of the user's <code>$HOME</code> path.</p>\n\n<p>At the Cygwin bash command prompt type the following:</p>\n\n<pre><code>cp /etc/passwd /etc/passwd.bak\nmkpasswd -l -p $(cygpath -H) &gt; /etc/passwd \nmkpasswd -d -p $(cygpath -H) &gt;&gt; /etc/passwd \n</code></pre>\n\n<p>The <code>-d</code> switch tells mkpasswd to include DOMAIN users, while <code>-l</code> is to only output LOCAL machine users. This is important if you're using a PC at work where the user information is obtained from a Windows Domain Controller. </p>\n\n<p>Now, you can also do the same for groups, though this is not necessary unless you will be using a computer that is part of a Windows Domain. Cygwin reads group information from the Windows account databases, but you can add an <code>/etc/group</code> file if your machine is often disconnected from its Domain Controller. </p>\n\n<p>At the Cygwin bash prompt type the following:</p>\n\n<pre><code>cp /etc/group /etc/group.bak\nmkgroup -l &gt; /etc/group \nmkgroup -d &gt;&gt; /etc/group \n</code></pre>\n\n<p>Now, exit Cygwin and start it up again. You should find that your HOME path points to the same location as your Windows User Profile -- i.e. <code>/cygdrive/c/Users/username</code></p>\n" }, { "answer_id": 57097304, "author": "user123456789", "author_id": 5490686, "author_profile": "https://Stackoverflow.com/users/5490686", "pm_score": 0, "selected": false, "text": "<p>I only needed to be in <code>C:\\Users\\username</code> when I start cygwin. So, I just added to <code>.bashrc</code> and <code>.profile</code></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>cd ${HOMEPATH}\n</code></pre>\n\n<p>If you prefer to use <code>~/.</code> instead of <code>$HOMEPATH</code>, you can also add the following:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>export HOME=${HOMEPATH}\n</code></pre>\n\n<p>This way I don't disturb the cygwin installation.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4893/" ]
I'm trying to safely update the home directory as specified in `/etc/passwd`, but the standard Linux utils - usermod and vipw - for doing so aren't provided by Cygwin. Could anyone tell me how they changed this in Cygwin?
I ended up exiting all my cygwin shells and editing it by hand in a text editor. So far, so good. Note: don't escape the spaces in the "Documents and Settings" directory. The entry will look like ``` user:...:/cygdrive/c/Documents and Settings/user:/bin/bash ``` The line is tokenized on the `:` character.
225,772
<p>I'm currently developing an application using a MySQL database.</p> <p>The database-structure is still in flux and changes while development progresses (I change my local copy, leaving the one on the test-server alone).</p> <p>Is there a way to compare the two instances of the database to see if there were any changes?</p> <p>While currently simply discarding the previous test server database is fine, as testing starts entering test data it could get a bit tricky.<br> The same though more so will happen again later in production...</p> <p>Is there an easy way to incrementally make changes to the production database, preferably by automatically creating a script to modify it? </p> <hr> <p>Tools mentioned in the answers:</p> <ul> <li><a href="https://www.red-gate.com/products/mysql/mysql-compare/" rel="nofollow noreferrer">Red-Gate's MySQL Schema &amp; Data Compare</a> (Commercial)</li> <li><a href="https://launchpad.net/percona-toolkit" rel="nofollow noreferrer">Maatkit (now Percona)</a></li> <li><a href="http://www.liquibase.org" rel="nofollow noreferrer">liquibase</a></li> <li><a href="http://www.quest.com/toad-for-mysql/" rel="nofollow noreferrer">Toad</a></li> <li><a href="http://nobhillsoft.com/NHDBCompare.aspx" rel="nofollow noreferrer">Nob Hill Database Compare</a> (Commercial)</li> <li><a href="http://adamspiers.org/computing/mysqldiff/" rel="nofollow noreferrer">MySQL Diff</a></li> <li><a href="http://www.sqledt.com" rel="nofollow noreferrer">SQL EDT</a> (Commercial)</li> </ul>
[ { "answer_id": 225776, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>For the first part of the question, I just do a dump of both and diff them. Not sure about mysql, but postgres pg_dump has a command to just dump the schema without the table contents, so you can see if you've changed the schema any.</p>\n" }, { "answer_id": 225781, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 2, "selected": false, "text": "<p>There is a useful tool written using perl called <a href=\"http://code.google.com/p/maatkit/\" rel=\"nofollow noreferrer\">Maatkit</a>. It has several database comparison and syncing tools among other things.</p>\n" }, { "answer_id": 225787, "author": "anders.norgaard", "author_id": 8805, "author_profile": "https://Stackoverflow.com/users/8805", "pm_score": 3, "selected": false, "text": "<p>Have a look at <a href=\"http://www.liquibase.org/\" rel=\"noreferrer\">http://www.liquibase.org/</a></p>\n" }, { "answer_id": 225790, "author": "Anson Smith", "author_id": 28685, "author_profile": "https://Stackoverflow.com/users/28685", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://www.quest.com/toad-for-mysql/\" rel=\"noreferrer\">Toad for MySQL</a> has data and schema compare features, and I believe it will even create a synchronization script. Best of all, it's freeware.</p>\n" }, { "answer_id": 225799, "author": "andyhky", "author_id": 2764, "author_profile": "https://Stackoverflow.com/users/2764", "pm_score": 4, "selected": false, "text": "<p>From the feature comparison list... <a href=\"http://dev.mysql.com/workbench/?page_id=11\" rel=\"noreferrer\" title=\"MySQL Workbench\">MySQL Workbench</a> offers Schema Diff and Schema Synchronization in their community edition.</p>\n" }, { "answer_id": 225811, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 4, "selected": false, "text": "<p>I use a piece of software called <a href=\"http://www.navicat.com/\" rel=\"noreferrer\">Navicat</a> to : </p>\n\n<ul>\n<li>Sync Live databases to my test databases. </li>\n<li>Show differences between the two databases. </li>\n</ul>\n\n<p>It costs money, it's windows and mac only, and it's got a whacky UI, but I like it. </p>\n" }, { "answer_id": 225817, "author": "George", "author_id": 8803, "author_profile": "https://Stackoverflow.com/users/8803", "pm_score": 2, "selected": false, "text": "<p>SQL Compare by RedGate\n<a href=\"http://www.red-gate.com/products/SQL_Compare/index.htm\" rel=\"nofollow noreferrer\">http://www.red-gate.com/products/SQL_Compare/index.htm</a></p>\n\n<p>DBDeploy to help with database change management in an automated fashion\n<a href=\"http://dbdeploy.com/\" rel=\"nofollow noreferrer\">http://dbdeploy.com/</a></p>\n" }, { "answer_id": 225820, "author": "Craig Trader", "author_id": 12895, "author_profile": "https://Stackoverflow.com/users/12895", "pm_score": 2, "selected": false, "text": "<p>For myself, I'd start with dumping both databases and diffing the dumps, but if you want automatically generated merge scripts, you're going to want to get a real tool.</p>\n\n<p>A simple <a href=\"http://www.google.com/search?q=Mysql+schema+comparison\" rel=\"nofollow noreferrer\">Google search</a> turned up the following tools:</p>\n\n<ul>\n<li><a href=\"http://dev.mysql.com/workbench/\" rel=\"nofollow noreferrer\">MySQL Workbench</a>, available in Community (OSS) and Commercial variants.</li>\n<li><a href=\"http://nobhillsoft.com/NHDBCompare.aspx\" rel=\"nofollow noreferrer\">Nob Hill database compare</a>, available for free for MySQL.</li>\n<li><a href=\"http://mysql-schema-compare.qarchive.org/\" rel=\"nofollow noreferrer\">A listing</a> of other SQL comparison tools.</li>\n</ul>\n" }, { "answer_id": 225979, "author": "Zac", "author_id": 5630, "author_profile": "https://Stackoverflow.com/users/5630", "pm_score": 4, "selected": false, "text": "<p>If you only need to compare schemas (not data), and have access to Perl, mysqldiff might work. I've used it because it lets you compare local databases to remote databases (via SSH), so you don't need to bother dumping any data.</p>\n\n<p><a href=\"http://adamspiers.org/computing/mysqldiff/\" rel=\"nofollow noreferrer\">http://adamspiers.org/computing/mysqldiff/</a></p>\n\n<p>It will attempt to generate SQL queries to synchronize two databases, but I don't trust it (or any tool, actually). As far as I know, there's no 100% reliable way to reverse-engineer the changes needed to convert one database schema to another, especially when multiple changes have been made.</p>\n\n<p>For example, if you change only a column's type, an automated tool can easily guess how to recreate that. But if you also move the column, rename it, and add or remove other columns, the best any software package can do is guess at what probably happened. And you may end up losing data.</p>\n\n<p>I'd suggest keeping track of any schema changes you make to the development server, then running those statements by hand on the live server (or rolling them into an upgrade script or migration). It's more tedious, but it'll keep your data safe. And by the time you start allowing end users access to your site, are you really going to be making constant heavy database changes?</p>\n" }, { "answer_id": 470427, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm working with Nob Hill's Marketing team, I wanted to tell you I'll be happy to hear your questions, suggestion or anything else, please feel free to contact me.</p>\n\n<p>We originally decided to create our tool from scratch because while there are other such products on the market, none of them do the job right. It’s quite easy to show you the differences between databases. It’s quite another to actually make one database like the other. Smooth migration, both of schema and data, has always been a challenge. Well, we have achieved it here.<br>\n We are so confident that it could provide you a smooth migration, than if it doesn’t – if the migration scripts it generates are not readable enough or won’t work for you, and we can’t fix it in five business days – you will get your own free copy!</p>\n\n<p><a href=\"http://www.nobhillsoft.com/NHDBCompare.aspx\" rel=\"nofollow noreferrer\">http://www.nobhillsoft.com/NHDBCompare.aspx</a></p>\n" }, { "answer_id": 524618, "author": "stepancheg", "author_id": 15018, "author_profile": "https://Stackoverflow.com/users/15018", "pm_score": 2, "selected": false, "text": "<p>There is another open source command-line mysql-diff tool:</p>\n\n<p><a href=\"http://bitbucket.org/stepancheg/mysql-diff/\" rel=\"nofollow noreferrer\">http://bitbucket.org/stepancheg/mysql-diff/</a></p>\n" }, { "answer_id": 3786536, "author": "Devart", "author_id": 135566, "author_profile": "https://Stackoverflow.com/users/135566", "pm_score": 2, "selected": false, "text": "<p>Take a look at <a href=\"http://www.devart.com/dbforge/mysql/datacompare/\" rel=\"nofollow noreferrer\">dbForge Data Compare for MySQL</a>. It's a shareware with 30-days free trial period. It's a fast MySQL GUI tool for data comparison and synchronization, management of data differences, and customizable synchronization.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Hcrhx.gif\" alt=\"dbForge Data Compare for MySQL\"></p>\n" }, { "answer_id": 3859577, "author": "jmpeace", "author_id": 53415, "author_profile": "https://Stackoverflow.com/users/53415", "pm_score": 4, "selected": false, "text": "<p>dbSolo, it is paid but this feature might be the one you are looking for\n<a href=\"http://www.dbsolo.com/help/compare.html\" rel=\"noreferrer\">http://www.dbsolo.com/help/compare.html</a></p>\n\n<p>It works with Oracle, Microsoft SQL Server, Sybase, DB2, Solid, PostgreSQL, H2 and MySQL\n<img src=\"https://i.stack.imgur.com/Z1A1N.jpg\" alt=\"alt text\"></p>\n" }, { "answer_id": 4264978, "author": "Naim Zard", "author_id": 518506, "author_profile": "https://Stackoverflow.com/users/518506", "pm_score": 2, "selected": false, "text": "<p>The apache zeta components library is a general purpose library of loosly coupled components for development of applications based on PHP 5.<br/></p>\n\n<p><b>eZ Components - DatabaseSchema</b> allows you to:</p>\n\n<pre>\n .Create/Save a database schema definition;\n .Compare database schemas;\n .Generate synchronization queries;\n</pre>\n\n<p>You can check the tutorial here:\n<a href=\"http://incubator.apache.org/zetacomponents/documentation/trunk/DatabaseSchema/tutorial.html\" rel=\"nofollow\">http://incubator.apache.org/zetacomponents/documentation/trunk/DatabaseSchema/tutorial.html</a></p>\n" }, { "answer_id": 4791164, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think <a href=\"http://www.navicat.com/en/products/navicat_mysql/mysql_detail_win.html\" rel=\"nofollow noreferrer\">Navicat for MySQL</a> will be helpful for this case. It supports Data and Structure Synchronization for MySQL. <img src=\"https://i.stack.imgur.com/gyRNg.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 5516218, "author": "Yury Litvinov", "author_id": 95050, "author_profile": "https://Stackoverflow.com/users/95050", "pm_score": 4, "selected": false, "text": "<p>There is a Schema Synchronization Tool in <a href=\"http://www.webyog.com/\" rel=\"noreferrer\">SQLyog</a> (commercial) which generates SQL for synchronizing two databases.</p>\n\n<p><img src=\"https://i.stack.imgur.com/7xuOn.jpg\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 5639668, "author": "likeuclinux", "author_id": 704636, "author_profile": "https://Stackoverflow.com/users/704636", "pm_score": 3, "selected": false, "text": "<p>check: <a href=\"http://schemasync.org/\" rel=\"noreferrer\">http://schemasync.org/</a> \nthe schemasync tool works for me, it is a command line tool works easily in linux command line</p>\n" }, { "answer_id": 7082953, "author": "Nikolay Ivanov", "author_id": 613598, "author_profile": "https://Stackoverflow.com/users/613598", "pm_score": 2, "selected": false, "text": "<p>After hours searching on web for simple tool, i realized i didn't look in Ubuntu Software Center.\nHere is a free solution i found:\n<a href=\"http://torasql.com/\" rel=\"nofollow\">http://torasql.com/</a>\nThey claim to have a version for Windows also, but I'm only using it under Ubuntu.</p>\n\n<p>Edit: 2015-Feb-05\nIf you need Windows tool, TOAD is perfect and free:\n<a href=\"http://software.dell.com/products/toad-for-mysql/\" rel=\"nofollow\">http://software.dell.com/products/toad-for-mysql/</a></p>\n" }, { "answer_id": 8718572, "author": "Jared", "author_id": 14744, "author_profile": "https://Stackoverflow.com/users/14744", "pm_score": 9, "selected": true, "text": "<p>If you're working with small databases I've found running mysqldump on both databases with the <code>--skip-comments</code> and <code>--skip-extended-insert</code> options to generate SQL scripts, then running diff on the SQL scripts works pretty well.</p>\n\n<p>By skipping comments you avoid meaningless differences such as the time you ran the mysqldump command. By using the <code>--skip-extended-insert</code> command you ensure each row is inserted with its own insert statement. This eliminates the situation where a single new or modified record can cause a chain reaction in all future insert statements. Running with these options produces larger dumps with no comments so this is probably not something you want to do in production use but for development it should be fine. I've put examples of the commands I use below:</p>\n\n<pre><code>mysqldump --skip-comments --skip-extended-insert -u root -p dbName1&gt;file1.sql\nmysqldump --skip-comments --skip-extended-insert -u root -p dbName2&gt;file2.sql\ndiff file1.sql file2.sql\n</code></pre>\n" }, { "answer_id": 9618043, "author": "Artem Goutsoul", "author_id": 1110069, "author_profile": "https://Stackoverflow.com/users/1110069", "pm_score": 2, "selected": false, "text": "<p>Very easy to use comparison and sync tool:<br>\n Database Comparer\n <a href=\"http://www.clevercomponents.com/products/dbcomparer/index.asp\" rel=\"nofollow\">http://www.clevercomponents.com/products/dbcomparer/index.asp</a></p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>fast</li>\n<li>easy to use</li>\n<li>easy to select changes to apply</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>does not sync length to tiny ints</li>\n<li>does not sync index names properly</li>\n<li>does not sync comments</li>\n</ul>\n" }, { "answer_id": 10285788, "author": "develCuy", "author_id": 2108644, "author_profile": "https://Stackoverflow.com/users/2108644", "pm_score": 4, "selected": false, "text": "<p>There are many ways certainly, but in my case I prefer the dump and diff command. So here is an script based on Jared's comment:</p>\n\n<pre><code>#!/bin/sh\n\necho \"Usage: dbdiff [user1:pass1@dbname1] [user2:pass2@dbname2] [ignore_table1:ignore_table2...]\"\n\ndump () {\n up=${1%%@*}; user=${up%%:*}; pass=${up##*:}; dbname=${1##*@};\n mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname $table &gt; $2\n}\n\nrm -f /tmp/db.diff\n\n# Compare\nup=${1%%@*}; user=${up%%:*}; pass=${up##*:}; dbname=${1##*@};\nfor table in `mysql -u $user -p$pass $dbname -N -e \"show tables\" --batch`; do\n if [ \"`echo $3 | grep $table`\" = \"\" ]; then\n echo \"Comparing '$table'...\"\n dump $1 /tmp/file1.sql\n dump $2 /tmp/file2.sql\n diff -up /tmp/file1.sql /tmp/file2.sql &gt;&gt; /tmp/db.diff\n else\n echo \"Ignored '$table'...\"\n fi\ndone\nless /tmp/db.diff\nrm -f /tmp/file1.sql /tmp/file2.sql\n</code></pre>\n\n<p>Feedback is welcome :)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27439/" ]
I'm currently developing an application using a MySQL database. The database-structure is still in flux and changes while development progresses (I change my local copy, leaving the one on the test-server alone). Is there a way to compare the two instances of the database to see if there were any changes? While currently simply discarding the previous test server database is fine, as testing starts entering test data it could get a bit tricky. The same though more so will happen again later in production... Is there an easy way to incrementally make changes to the production database, preferably by automatically creating a script to modify it? --- Tools mentioned in the answers: * [Red-Gate's MySQL Schema & Data Compare](https://www.red-gate.com/products/mysql/mysql-compare/) (Commercial) * [Maatkit (now Percona)](https://launchpad.net/percona-toolkit) * [liquibase](http://www.liquibase.org) * [Toad](http://www.quest.com/toad-for-mysql/) * [Nob Hill Database Compare](http://nobhillsoft.com/NHDBCompare.aspx) (Commercial) * [MySQL Diff](http://adamspiers.org/computing/mysqldiff/) * [SQL EDT](http://www.sqledt.com) (Commercial)
If you're working with small databases I've found running mysqldump on both databases with the `--skip-comments` and `--skip-extended-insert` options to generate SQL scripts, then running diff on the SQL scripts works pretty well. By skipping comments you avoid meaningless differences such as the time you ran the mysqldump command. By using the `--skip-extended-insert` command you ensure each row is inserted with its own insert statement. This eliminates the situation where a single new or modified record can cause a chain reaction in all future insert statements. Running with these options produces larger dumps with no comments so this is probably not something you want to do in production use but for development it should be fine. I've put examples of the commands I use below: ``` mysqldump --skip-comments --skip-extended-insert -u root -p dbName1>file1.sql mysqldump --skip-comments --skip-extended-insert -u root -p dbName2>file2.sql diff file1.sql file2.sql ```
225,825
<p>I'm developing a piece in VB.NET. Inside my primary form, I'm creating a new form to use as a dialog. I was wondering if there was a way to, upon the close of the new dialog, save it's size settings for each user (probably in a file on their machine, through XML or something?)</p>
[ { "answer_id": 225853, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 2, "selected": false, "text": "<p>Although <a href=\"https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c\">this is for C#</a>, it will help with VB.Net as well.</p>\n" }, { "answer_id": 225900, "author": "Keithius", "author_id": 5956, "author_profile": "https://Stackoverflow.com/users/5956", "pm_score": 0, "selected": false, "text": "<p>You can also do this using the UI provided by the VB.NET IDE itself. In the properties pane for a form, look under the item called \"(Application Settings)\" and then under \"Property Binding.\" You can bind just about every property of the form (including size and location) to a settings value for that application. </p>\n" }, { "answer_id": 225925, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 4, "selected": true, "text": "<p>you can save it to the settings file, and update it on the 'onclosing' event.</p>\n\n<p>to make a setting goto Project Properties ->settings -> then make a setting like 'dialogsize' of type system.drawing.size.</p>\n\n<p>then do this in your dialog form:</p>\n\n<pre><code>Public Sub New()\n InitializeComponent()\nEnd Sub\n\nPublic Sub New(ByVal userSize As Size)\n InitializeComponent()\n Me.Size = userSize\nEnd Sub\n\nProtected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)\n MyBase.OnClosing(e)\n My.Settings.DialogSize = Me.Size\n My.Settings.Save()\nEnd Sub\n</code></pre>\n\n<p>do something like this to check and use the setting:</p>\n\n<pre><code> Dim dlg As MyDialogWindow\n If My.Settings.DialogSize.IsEmpty Then\n dlg = New MyDialogWindow()\n Else\n dlg = New MyDialogWindow(My.Settings.DialogSize)\n End If\n dlg.ShowDialog()\n</code></pre>\n" }, { "answer_id": 226950, "author": "Joe Morgan", "author_id": 13244, "author_profile": "https://Stackoverflow.com/users/13244", "pm_score": 0, "selected": false, "text": "<p>As it turns out, I found a way to do this using the <code>System.IO.IsolatedStorage</code></p>\n" }, { "answer_id": 12751376, "author": "Waleed El-Safty", "author_id": 1723762, "author_profile": "https://Stackoverflow.com/users/1723762", "pm_score": 2, "selected": false, "text": "<p>You can also add a new setting to your application (size) and set it to <code>system.drawing.size</code></p>\n\n<p>Then, you make sure you save the current size to settings on close.</p>\n\n<pre><code> Private Sub myForm_FormClosing(ByVal sender As System.Object,\n ByVal e As System.Windows.Forms.FormClosingEventArgs) _\n Handles MyBase.FormClosing\n\n My.Settings.size = Me.Size\n My.Settings.Save()\n\nEnd Sub\n</code></pre>\n\n<p>and on load you apply the size you have saved in settings</p>\n\n<pre><code> Private Sub myForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _\n Handles MyBase.Load\n ' if this is the first time to load the form \n ' dont set the size ( the form will load with the size in the designe)\n If Not My.Settings.size.IsEmpty Then\n Me.Size = My.Settings.size\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 60029846, "author": "Aaron", "author_id": 4451823, "author_profile": "https://Stackoverflow.com/users/4451823", "pm_score": 1, "selected": false, "text": "<p>Here's a solution that <a href=\"http://christ-offer.blogspot.com/2012/02/vbnet-remember-application-window-size.html\" rel=\"nofollow noreferrer\">I found online</a> that seems to work rather well for me. </p>\n\n<p>Some of the previously mentioned solutions weren't working for me as expected. Depending on where my form was positioned at the time of closing the form wouldn't get repositioned back to that exact location when I would load it again. </p>\n\n<p>This solution seems to do the trick by taking into account some other factors as well:</p>\n\n<p>You need to set up these two setting under Project Properties -> settings: WindowLocation and WindowSize like so:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rk34J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rk34J.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then create the following function:</p>\n\n<pre><code>Private Sub LoadWindowPosition()\n\n 'Get window location/position from settings\n Dim ptLocation As System.Drawing.Point = My.Settings.WindowLocation\n\n 'Exit if it has not been set (X = Y = -1)\n If (ptLocation.X = -1) And (ptLocation.Y = -1) Then\n Return\n End If\n\n 'Verify the window position is visible on at least one of our screens\n Dim bLocationVisible As Boolean = False\n\n For Each S As Screen In Screen.AllScreens\n If S.Bounds.Contains(ptLocation) Then\n bLocationVisible = True\n Exit For\n End If\n Next\n\n 'Exit if window location is not visible on any screen \n If Not bLocationVisible Then\n Return\n End If\n\n 'Set Window Size, Location\n Me.StartPosition = FormStartPosition.Manual\n Me.Location = ptLocation\n Me.Size = My.Settings.WindowSize\nEnd Sub\n</code></pre>\n\n<p>Next, you'll need to add code to your form's load and closing events like so:</p>\n\n<pre><code>Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n LoadWindowPosition()\nEnd Sub\n\nPrivate Sub frmMain_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing\n My.Settings.WindowLocation = Me.Location\n My.Settings.WindowSize = Me.Size\nEnd Sub\n</code></pre>\n\n<p>I hope that helps. </p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13244/" ]
I'm developing a piece in VB.NET. Inside my primary form, I'm creating a new form to use as a dialog. I was wondering if there was a way to, upon the close of the new dialog, save it's size settings for each user (probably in a file on their machine, through XML or something?)
you can save it to the settings file, and update it on the 'onclosing' event. to make a setting goto Project Properties ->settings -> then make a setting like 'dialogsize' of type system.drawing.size. then do this in your dialog form: ``` Public Sub New() InitializeComponent() End Sub Public Sub New(ByVal userSize As Size) InitializeComponent() Me.Size = userSize End Sub Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs) MyBase.OnClosing(e) My.Settings.DialogSize = Me.Size My.Settings.Save() End Sub ``` do something like this to check and use the setting: ``` Dim dlg As MyDialogWindow If My.Settings.DialogSize.IsEmpty Then dlg = New MyDialogWindow() Else dlg = New MyDialogWindow(My.Settings.DialogSize) End If dlg.ShowDialog() ```
225,832
<p>Here's the deal. I have an XML document with a lot of records. Something like this:</p> <pre><code>print("&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;Orders&gt; &lt;Order&gt; &lt;Phone&gt;1254&lt;/Phone&gt; &lt;City&gt;City1&lt;/City&gt; &lt;State&gt;State&lt;/State&gt; &lt;/Order&gt; &lt;Order&gt; &lt;Phone&gt;98764321&lt;/Phone&gt; &lt;City&gt;City2&lt;/City&gt; &lt;State&gt;State2&lt;/State&gt; &lt;/Order&gt; &lt;/Orders&gt;"); </code></pre> <p>There's also an XSD schema file. I would like to extract data from this file and insert these records into a database table. First of course I would like to validate each order record. For example if there are 5 orders in the file and 2 of them fail validation I would like to insert the 3 that passed validation into the db and left the other 2. There can be thousands of records in one xml file. What would be the best approach here. And how would the validation go for this since I need to discard the failed records and only use the ones that passed validation. At the moment I'm using <b>XmlReaderSettings</b> to validate the XML document records. Should I extract these records into another XML file or a Dataset or a custom object before I insert into a DB. I'm using .Net 3.5. Any code or link is welcome.</p>
[ { "answer_id": 225885, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>If the data maps fairly cleanly to an object model, you could try using xsd.exe to generate some classes from the .xsd, and process the classes into your DAL of choice. The problem is that if the volume is high (you mention thousands of records), you will most likely have a <em>lot</em> of round-trips.</p>\n\n<p>Another option might be to pass the data \"as is\" through to the database and use SQL/XML to process the data in TSQL - presumably as a stored procedure that accepts a parameter of type xml (SQL Server 2005 etc).</p>\n" }, { "answer_id": 226183, "author": "joshua.ewer", "author_id": 28664, "author_profile": "https://Stackoverflow.com/users/28664", "pm_score": 0, "selected": false, "text": "<p>A lot of that depends on what \"validation\" means in your scenario. I assume, since you're using an .xsd, you are already validating that the data is syntactically correct. \nSo, validation probably means you'll be calling other services or procedures to determine if an order is valid?</p>\n\n<p>You might want to look at Sql Server Integration Services. The XML Task in SSIS lets you do things like XPath queries, merging, likely anything and everything you'd need to do with that document. You could also use that do to all of your upfront validation with schema file too. </p>\n\n<p>Marc's option of passing that data to a stored procedure might work in this scenario too, but SSIS (or, even DTS but you're going to give up too much related to XML to make it as nice of an option) will let you visually orchestrate all of this work. Plus, it'll make it easier for these things to run out of process so you should end up with a much more scalable solution.</p>\n" }, { "answer_id": 226246, "author": "Neil Barnwell", "author_id": 26414, "author_profile": "https://Stackoverflow.com/users/26414", "pm_score": 1, "selected": true, "text": "<p>You have a couple of options:</p>\n\n<ol>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldatadocument(VS.80).aspx\" rel=\"nofollow noreferrer\">XmlDataDocument</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument(VS.80).aspx\" rel=\"nofollow noreferrer\">XmlDocument</a>. The downside to this approach is that the data will be cached in memory, which is bad if you have a lot of it. On the other hand, you get good in-memory querying facilities with DataSet. XmlDocument requires that you use XPath queries to work on the data, whereas XmlDataDocument gives you an experience more like the DataSet functionality.</p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/9d83k261(VS.80).aspx\" rel=\"nofollow noreferrer\">XmlReader</a>. This is a good, fast approach because the data isn't cached; you read it in a bit at a time as a stream. You move from one element to the next, and query information about that element in your application to decide what to do with it. This does mean that you maintain in your application's memory the tree level that you're at, but with a simple XML file structure like yours this should be very simple.</p></li>\n</ol>\n\n<p>I recommend option 2 in your case. It should scale well in terms of memory usage, and should provide the simplest implementation for processing a file.</p>\n" }, { "answer_id": 228826, "author": "Malik Daud Ahmad Khokhar", "author_id": 1688440, "author_profile": "https://Stackoverflow.com/users/1688440", "pm_score": 0, "selected": false, "text": "<p>By validation I mean validating each node. The nodes that have at least one error need to be inserted into a new xml document. Basically at the end I should have 2 xml documents. One containing the successful nodes and the other containing the failure nodes. Any way I can accomplish that? I'm using LINQ.</p>\n" }, { "answer_id": 899379, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 1, "selected": false, "text": "<p>I agree with idea that you should use an XmlReader, but I thought I'd try something a little different.</p>\n\n<p>Basically, I am first validating the whole XDocument, then if there are errors, I enumerate through the orders and bin them as needed. It's not pretty, but maybe it'll give you some ideas.</p>\n\n<pre><code> XDocument doc = XDocument.Load(\"sample.xml\");\n XmlSchemaSet schemas = new XmlSchemaSet();\n schemas.Add(\"\", \"sample.xsd\");\n\n bool errors = false;\n doc.Validate(schemas, (sender, e) =&gt;\n {\n errors = true;\n });\n\n List&lt;XElement&gt; good = new List&lt;XElement&gt;();\n List&lt;XElement&gt; bad = new List&lt;XElement&gt;();\n var orders = doc.Descendants(\"Order\");\n if (errors)\n {\n foreach (var order in orders)\n {\n errors = false;\n order.Validate(order.GetSchemaInfo().SchemaElement, schemas, (sender, e) =&gt;\n {\n errors = true;\n });\n\n if (errors)\n bad.Add(order);\n else\n good.Add(order);\n }\n }\n else\n {\n good = orders.ToList();\n }\n</code></pre>\n\n<p>Instead of the lambda expressions, you could use a common function, but I just threw this together. Also, you could build two XDocuments instead of shoving the order elements into a list. I'm sure there are a ton of other problems here too, but maybe this will spark something.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
Here's the deal. I have an XML document with a lot of records. Something like this: ``` print("<?xml version="1.0" encoding="utf-8" ?> <Orders> <Order> <Phone>1254</Phone> <City>City1</City> <State>State</State> </Order> <Order> <Phone>98764321</Phone> <City>City2</City> <State>State2</State> </Order> </Orders>"); ``` There's also an XSD schema file. I would like to extract data from this file and insert these records into a database table. First of course I would like to validate each order record. For example if there are 5 orders in the file and 2 of them fail validation I would like to insert the 3 that passed validation into the db and left the other 2. There can be thousands of records in one xml file. What would be the best approach here. And how would the validation go for this since I need to discard the failed records and only use the ones that passed validation. At the moment I'm using **XmlReaderSettings** to validate the XML document records. Should I extract these records into another XML file or a Dataset or a custom object before I insert into a DB. I'm using .Net 3.5. Any code or link is welcome.
You have a couple of options: 1. [XmlDataDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldatadocument(VS.80).aspx) or [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument(VS.80).aspx). The downside to this approach is that the data will be cached in memory, which is bad if you have a lot of it. On the other hand, you get good in-memory querying facilities with DataSet. XmlDocument requires that you use XPath queries to work on the data, whereas XmlDataDocument gives you an experience more like the DataSet functionality. 2. [XmlReader](http://msdn.microsoft.com/en-us/library/9d83k261(VS.80).aspx). This is a good, fast approach because the data isn't cached; you read it in a bit at a time as a stream. You move from one element to the next, and query information about that element in your application to decide what to do with it. This does mean that you maintain in your application's memory the tree level that you're at, but with a simple XML file structure like yours this should be very simple. I recommend option 2 in your case. It should scale well in terms of memory usage, and should provide the simplest implementation for processing a file.
225,833
<p>I have to add a coupon table to my db. There are 3 types of coupons : percentage, amount or 2 for 1.</p> <p>So far I've come up with a coupon table that contains these 3 fields. If there's a percentage value not set to null then it's this kind of coupon.</p> <p>I feel it's not the proper way to do it. Should I create a CouponType table and how would you see it? Where would you store these values?</p> <p>Any help or cue appreciated!</p> <p>Thanks,</p> <p>Teebot</p>
[ { "answer_id": 225862, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": true, "text": "<p>You're correct, I think a CouponType table would be fit for your problem.</p>\n\n<p>Two tables: Coupons and CouponTypes. Store the CouponTypeId inside the Coupons table.</p>\n\n<p>So for an example, you'll have a Coupon record called \"50% off\", if would reference the percent off CouponType record and from there you could determine the logic to take 50% off the cost of the item.</p>\n\n<p>So now you can create unlimited coupons, if it's a dollar amount coupon type it will take the \"amount\" column and treat it as a dollar amount. If it's a percent off it will treat it as a percentage and if it's an \"x for 1\" deal, it will treat the value as x.</p>\n\n<pre><code>- Table Coupons\n - ID\n - name\n - coupon_type_id # (or whatever fits your style guidelines)\n - amount # Example: 10.00 (treated as $10 off for amount type, treated as \n # 10% for percent type or 10 for 1 with the final type) \n - expiration_date\n\n- Table CouponTypes\n - ID\n - type # (amount, percent, &lt;whatever you decided to call the 2 for 1&gt; :))\n</code></pre>\n" }, { "answer_id": 225865, "author": "Chris Kloberdanz", "author_id": 28714, "author_profile": "https://Stackoverflow.com/users/28714", "pm_score": 1, "selected": false, "text": "<p>I would definitely create a CouponType lookup table. That way you avoid all the NULL's and allow for more coupon types in the future.</p>\n\n<p>Coupon\n coupon_id INT \n name VARCHAR\n coupon_type_id INT &lt;- Foreign Key</p>\n\n<p>CouponType\n coupon_type_id INT\n type_description VARCHAR\n ...</p>\n\n<p>Or I suppose you could have a coupon type column in your coupon table CHAR(1)</p>\n" }, { "answer_id": 225871, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 2, "selected": false, "text": "<p>In the future you might have much more different coupon types. You could also have different business logic associated with them - you never know. It's always useful to do the things right in this case, so yes, definitely, create a coupon type field and an associated dictionary table to go with it.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24291/" ]
I have to add a coupon table to my db. There are 3 types of coupons : percentage, amount or 2 for 1. So far I've come up with a coupon table that contains these 3 fields. If there's a percentage value not set to null then it's this kind of coupon. I feel it's not the proper way to do it. Should I create a CouponType table and how would you see it? Where would you store these values? Any help or cue appreciated! Thanks, Teebot
You're correct, I think a CouponType table would be fit for your problem. Two tables: Coupons and CouponTypes. Store the CouponTypeId inside the Coupons table. So for an example, you'll have a Coupon record called "50% off", if would reference the percent off CouponType record and from there you could determine the logic to take 50% off the cost of the item. So now you can create unlimited coupons, if it's a dollar amount coupon type it will take the "amount" column and treat it as a dollar amount. If it's a percent off it will treat it as a percentage and if it's an "x for 1" deal, it will treat the value as x. ``` - Table Coupons - ID - name - coupon_type_id # (or whatever fits your style guidelines) - amount # Example: 10.00 (treated as $10 off for amount type, treated as # 10% for percent type or 10 for 1 with the final type) - expiration_date - Table CouponTypes - ID - type # (amount, percent, <whatever you decided to call the 2 for 1> :)) ```
225,843
<p>I have a menu div that I want to slide down so it's always visible, but I want it to be positioned under my title div. I don't want it to move until the top of the menu hits the top of the screen and then stay in place. Basically I want a sliding menu with a maximum height it can slide to.</p>
[ { "answer_id": 225899, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "<p>Slashdot does this. Check it out at, for example, <a href=\"http://tech.slashdot.org/tech/08/10/22/1246200.shtml\" rel=\"nofollow noreferrer\">http://tech.slashdot.org/tech/08/10/22/1246200.shtml</a></p>\n\n<p>You may be able to lift the technique from their site.</p>\n" }, { "answer_id": 225935, "author": "jaacob", "author_id": 28109, "author_profile": "https://Stackoverflow.com/users/28109", "pm_score": 4, "selected": true, "text": "<p>I think I understand what you're talking about—we used a similar technique on <a href=\"http://www.kingtray.com\" rel=\"nofollow noreferrer\">The King</a> with jQuery. Here's how:</p>\n\n<pre><code>///// CONFIGURATION VARIABLES:\n\nvar name = \"#rightsidebar\";\nvar menu_top_limit = 241;\nvar menu_top_margin = 20;\nvar menu_shift_duration = 500;\nvar menuYloc = null;\n///////////////////////////////////\n\n$(window).scroll(function() \n{ \n // Calculate the top offset, adding a limit\n offset = menuYloc + $(document).scrollTop() + menu_top_margin;\n\n // Limit the offset to 241 pixels...\n // This keeps the menu out of our header area:\n if(offset &lt; menu_top_limit)\n offset = menu_top_limit;\n\n // Give it the PX for pixels:\n offset += \"px\";\n\n // Animate:\n $(name).animate({top:offset},{duration:menu_shift_duration,queue:false});\n});\n</code></pre>\n\n<p>(Hat tip to <a href=\"http://soyrex.com/\" rel=\"nofollow noreferrer\">@soyrex</a> who wrote this code.)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30377/" ]
I have a menu div that I want to slide down so it's always visible, but I want it to be positioned under my title div. I don't want it to move until the top of the menu hits the top of the screen and then stay in place. Basically I want a sliding menu with a maximum height it can slide to.
I think I understand what you're talking about—we used a similar technique on [The King](http://www.kingtray.com) with jQuery. Here's how: ``` ///// CONFIGURATION VARIABLES: var name = "#rightsidebar"; var menu_top_limit = 241; var menu_top_margin = 20; var menu_shift_duration = 500; var menuYloc = null; /////////////////////////////////// $(window).scroll(function() { // Calculate the top offset, adding a limit offset = menuYloc + $(document).scrollTop() + menu_top_margin; // Limit the offset to 241 pixels... // This keeps the menu out of our header area: if(offset < menu_top_limit) offset = menu_top_limit; // Give it the PX for pixels: offset += "px"; // Animate: $(name).animate({top:offset},{duration:menu_shift_duration,queue:false}); }); ``` (Hat tip to [@soyrex](http://soyrex.com/) who wrote this code.)
225,845
<p>I'm trying to get a kernel module to load at boot.</p> <p>If I run <code>insmod /path/to/module.ko</code>, it works fine. But this has to be repeated every time I reboot.</p> <p>If I run <code>modprobe /path/to/module.ko</code>, it can't find the module. I know modprobe uses a configuration file, but I can't get it to load the module even after adding /path/to/module.ko to /etc/modules.</p> <p>What is the proper configuration?</p>
[ { "answer_id": 225971, "author": "Jaime Soriano", "author_id": 28855, "author_profile": "https://Stackoverflow.com/users/28855", "pm_score": 7, "selected": true, "text": "<p>You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.</p>\n\n<pre><code>sudo ln -s /path/to/module.ko /lib/modules/`uname -r`\nsudo depmod -a\nsudo modprobe module\n</code></pre>\n\n<p>If you add the module name to /etc/modules it will be loaded any time you boot.</p>\n\n<p>Anyway I think that the proper configuration is to copy the module to the standard paths.</p>\n" }, { "answer_id": 226015, "author": "Ray Li", "author_id": 28952, "author_profile": "https://Stackoverflow.com/users/28952", "pm_score": 3, "selected": false, "text": "<p>I think the key is to copy the module to the standard paths.</p>\n\n<p>Once that is done, modprobe only accepts the module name, so leave off the path and \".ko\" extension.</p>\n" }, { "answer_id": 35968849, "author": "tusharrnimje", "author_id": 5164423, "author_profile": "https://Stackoverflow.com/users/5164423", "pm_score": 4, "selected": false, "text": "<p>Follow following steps:</p>\n\n<blockquote>\n <ol>\n <li>Copy hello.ko to /lib/modules/'uname-r'/misc/</li>\n <li>Add misc/hello.ko entry in /lib/modules/'uname-r'/modules.dep</li>\n <li>sudo depmod</li>\n <li>sudo modprobe hello</li>\n </ol>\n</blockquote>\n\n<p>modprobe will check modules.dep file for any dependency.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13652/" ]
I'm trying to get a kernel module to load at boot. If I run `insmod /path/to/module.ko`, it works fine. But this has to be repeated every time I reboot. If I run `modprobe /path/to/module.ko`, it can't find the module. I know modprobe uses a configuration file, but I can't get it to load the module even after adding /path/to/module.ko to /etc/modules. What is the proper configuration?
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module. ``` sudo ln -s /path/to/module.ko /lib/modules/`uname -r` sudo depmod -a sudo modprobe module ``` If you add the module name to /etc/modules it will be loaded any time you boot. Anyway I think that the proper configuration is to copy the module to the standard paths.
225,881
<p>Can anyone provide a clear explanation / example of what these functions do, and when it's appropriate to use them?</p>
[ { "answer_id": 225907, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 6, "selected": true, "text": "<p>Straight from <a href=\"http://www.postgresql.org/docs/8.3/static/ddl-constraints.html#DDL-CONSTRAINTS-FK\" rel=\"noreferrer\">the manual</a>...</p>\n\n<blockquote>\n <p>We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that as well. Intuitively, we have a few options:</p>\n \n <p>Disallow deleting a referenced product</p>\n \n <p>Delete the orders as well</p>\n \n <p>Something else?</p>\n</blockquote>\n\n<pre><code>CREATE TABLE order_items (\n product_no integer REFERENCES products ON DELETE RESTRICT,\n order_id integer REFERENCES orders ON DELETE CASCADE,\n quantity integer,\n PRIMARY KEY (product_no, order_id)\n);\n</code></pre>\n\n<blockquote>\n <p>Restricting and cascading deletes are the two most common options. RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be deferred until later in the transaction, whereas RESTRICT does not.) CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key, the operation will fail.</p>\n \n <p>Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same.</p>\n</blockquote>\n\n<p><strong>edit:</strong> You might want to take a look at this related question: <a href=\"https://stackoverflow.com/questions/59297/whenwhy-to-use-cascading-in-sql-server\">When/Why to use Cascading in SQL Server?</a>. The concepts behind the question/answers are the same.</p>\n" }, { "answer_id": 225918, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "<p>I have a PostGreSQL database and I use On Delete when I have a user that I delete from the database and I need to delete it's information from other table. This ways I need to do only 1 delete and FK that has ON delete will delete information from other table.</p>\n\n<p>You can do the same with ON Update. If you update the table and the field have a FK with On Update, if a change is made on the FK you will be noticed on the FK table.</p>\n" }, { "answer_id": 226070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What Daok says is true... it can be rather convenient. On the other hand, having things happen automagically in the database can be a real problem, especially when it comes to eliminating data. It's possible that in the future someone will count on the fact that FKs usually prevent deletion of parents when there are children and not realize that your use of On Delete Cascade not only doesn't prevent deletion, it makes huge amounts of data in dozens of other tables go away thanks to a waterfall of cascading deletes. </p>\n\n<p>@Arthur's comment.</p>\n\n<p>The more frequently \"hidden\" things happen in the database the less likely it becomes that anyone will ever have a good handle on what is going on. Triggers (and this is essentially a trigger) can cause my simple action of deleting a row, to have wide ranging consequences throughout my database. I issue a Delete statement and 17 tables are affected with cascades of triggers and constraints and none of this is immediately apparent to the issuer of the command. OTOH, If I place the deletion of the parent and all its children in a procedure then it is very easy and clear for anyone to see EXACTLY what is going to happen when I issue the command. </p>\n\n<p>It has absolutely nothing to do with how well I design a database. It has everything to do with the operational issues introduced by triggers. </p>\n" }, { "answer_id": 3202209, "author": "Jeff Edwards", "author_id": 386467, "author_profile": "https://Stackoverflow.com/users/386467", "pm_score": 0, "selected": false, "text": "<p>Instead of writing the method to do all the work, of the cascade delete or cascade update, you could simply write a warning message instead. A lot easier than reinventing the wheel, and it makes it clear to the client (and new developers picking up the code)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
Can anyone provide a clear explanation / example of what these functions do, and when it's appropriate to use them?
Straight from [the manual](http://www.postgresql.org/docs/8.3/static/ddl-constraints.html#DDL-CONSTRAINTS-FK)... > > We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that as well. Intuitively, we have a few options: > > > Disallow deleting a referenced product > > > Delete the orders as well > > > Something else? > > > ``` CREATE TABLE order_items ( product_no integer REFERENCES products ON DELETE RESTRICT, order_id integer REFERENCES orders ON DELETE CASCADE, quantity integer, PRIMARY KEY (product_no, order_id) ); ``` > > Restricting and cascading deletes are the two most common options. RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be deferred until later in the transaction, whereas RESTRICT does not.) CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key, the operation will fail. > > > Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same. > > > **edit:** You might want to take a look at this related question: [When/Why to use Cascading in SQL Server?](https://stackoverflow.com/questions/59297/whenwhy-to-use-cascading-in-sql-server). The concepts behind the question/answers are the same.
225,895
<p>I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty):</p> <pre><code>... if(Single.getInstance().firstTime()){ doPreperations(); } normalResponse(); ... </code></pre> <p>The singleton 'Single' looks like this:</p> <pre><code>private static Single theInstance = new Single(); private Single() { ...load properties... } public static Single getInstance() { return theInstance; } </code></pre> <p>With the way this is set to use a static initializer instead of checking for a null theInstance in the getInstance() method, could this get rebuilt over and over again?</p> <p>PS - We're running WebSphere 6 with the App on Java 1.4</p>
[ { "answer_id": 225909, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 4, "selected": false, "text": "<p>No it won't get built over and over again. It's static, so it'll only be constructed once, right when the class is touched for the first time by the Classloader.</p>\n\n<p>Only exception - if you happen to have multiple Classloaders.</p>\n\n<p>(from <a href=\"http://geekandpoke.typepad.com/.a/6a00d8341d3df553ef0147e0761e2f970b-800wi\" rel=\"nofollow noreferrer\">GeekAndPoke</a>):</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZHqCV.jpg\" alt=\"alt text\"></p>\n" }, { "answer_id": 225913, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 1, "selected": false, "text": "<p>No - the static initialization of the <code>instance</code> will only ever be done once. Two things to consider:</p>\n\n<ul>\n<li>This is not thread-safe (the instance is not \"published\" to main memory)</li>\n<li>Your <code>firstTime</code> method is probably called multiple times, unless properly synchronized</li>\n</ul>\n" }, { "answer_id": 225914, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "<p>I found this on Sun's site: </p>\n\n<blockquote>\n <h3>Multiple Singletons Simultaneously Loaded by Different Class Loaders</h3>\n \n <p>When two class loaders load a class,\n you actually have two copies of the\n class, and each one can have its own\n Singleton instance. That is\n particularly relevant in servlets\n running in certain servlet engines\n (iPlanet for example), where each\n servlet by default uses its own class\n loader. Two different servlets\n accessing a joint Singleton will, in\n fact, get two different objects.</p>\n \n <p>Multiple class loaders occur more\n commonly than you might think. When\n browsers load classes from the network\n for use by applets, they use a\n separate class loader for each server\n address. Similarly, Jini and RMI\n systems may use a separate class\n loader for the different code bases\n from which they download class files.\n If your own system uses custom class\n loaders, all the same issues may\n arise.</p>\n \n <p>If loaded by different class loaders,\n two classes with the same name, even\n the same package name, are treated as\n distinct -- even if, in fact, they are\n byte-for-byte the same class. The\n different class loaders represent\n different namespaces that distinguish\n classes (even though the classes'\n names are the same), so that the two\n <code>MySingleton</code> classes are in fact\n distinct. (See \"Class Loaders as a\n Namespace Mechanism\" in Resources.)\n Since two Singleton objects belong to\n two classes of the same name, it will\n appear at first glance that there are\n two Singleton objects of the same\n class.</p>\n</blockquote>\n\n<p><a href=\"http://www.oracle.com/technetwork/articles/java/singleton-1577166.html\" rel=\"nofollow noreferrer\">Citation</a>.</p>\n\n<p>In addition to the above issue, if <code>firstTime()</code> is not synchronized, you could have threading issues there as well.</p>\n" }, { "answer_id": 225920, "author": "Einar", "author_id": 2964, "author_profile": "https://Stackoverflow.com/users/2964", "pm_score": 1, "selected": false, "text": "<p>In theory it will be built only once. However, this pattern breaks in various application servers, where you can get multiple instances of 'singleton' classes (since they are not thread-safe).</p>\n\n<p>Also, the singleton pattern has been critized a lot. See for instance <a href=\"http://www.codingwithoutcomments.com/2008/10/08/singleton-i-love-you-but-youre-bringing-me-down/\" rel=\"nofollow noreferrer\">Singleton I love you, but you're bringing me down</a></p>\n" }, { "answer_id": 225927, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 2, "selected": false, "text": "<p>The only thing I would change about that Singleton implementation (other than not using a Singleton at all) is to make the instance field final. The static field will be initialised once, on class load. Since classes are loaded lazily, you effectively get lazy instantiation for free.</p>\n\n<p>Of course, if it's loaded from separate class loaders you get multiple \"singletons\", but that's a limitation of every singleton idiom in Java.</p>\n\n<p><strong>EDIT</strong>: The firstTime() and doPreparations() bits do look suspect though. Can't they be moved into the constructor of the singleton instance?</p>\n" }, { "answer_id": 225933, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<p>As others have mentioned, the static initializer will only be run once per classloader.</p>\n\n<p>One thing I would take a look at is the <code>firstTime()</code> method - why can't the work in <code>doPreparations()</code> be handled within the singleton itself?</p>\n\n<p>Sounds like a nasty set of dependencies.</p>\n" }, { "answer_id": 225998, "author": "nkr1pt", "author_id": 24046, "author_profile": "https://Stackoverflow.com/users/24046", "pm_score": 0, "selected": false, "text": "<p>This will get only loaded once when the class is loaded by the classloader.\nThis example provides a better Singleton implementation however, it's as lazy-loaded as possible and thread-safe.\nMoreover, it works in all known versions of Java. \nThis solution is the most portable across different Java compilers and virtual machines.</p>\n\n<pre><code>\npublic class Single {\n\nprivate static class SingleHolder {\n private static final Single INSTANCE = new Single();\n}\n\nprivate Single() {\n...load properties...\n}\n\npublic static Single getInstance() {\n return SingleHolder.INSTANCE;\n}\n\n}</code></pre>\n\n<p>The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized). </p>\n" }, { "answer_id": 226051, "author": "Jevgeni Kabanov", "author_id": 20022, "author_profile": "https://Stackoverflow.com/users/20022", "pm_score": 3, "selected": false, "text": "<p>There is absolutely no difference between using a static initializer and lazy initialization. In fact it's far easier to mess up the lazy initialization, which also enforces synchronization. The JVM guarantees that the static initializer is always run before the class is accessed and it will happen once and only once.</p>\n\n<p>That said JVM does not guarantee that your class will be loaded only once. However even if it is loaded more than once, your web application will still see only the relevant singleton, as it will be loaded either in the web application classloader or its parent. If you have several web application deployed, then firstTime() will be called once for each application. </p>\n\n<p>The most apparent things to check is that firstTime() needs to be synchronized and that the firstTime flag is set before exiting that method.</p>\n" }, { "answer_id": 227637, "author": "mjlee", "author_id": 2829, "author_profile": "https://Stackoverflow.com/users/2829", "pm_score": 3, "selected": false, "text": "<p>No, It won't create multiple copies of 'Single'. ( Classloader issue will be visited later )</p>\n\n<p>The implementation you outlined is described as 'Eager Initialization' by in Briant Goetz's book - '<a href=\"http://www.javaconcurrencyinpractice.com/\" rel=\"noreferrer\">Java Concurrency in Practice</a>'.</p>\n\n<pre><code>public class Single\n{\n private static Single theInstance = new Single();\n\n private Single() \n { \n // load properties\n }\n\n public static Single getInstance() \n {\n return theInstance;\n }\n}\n</code></pre>\n\n<p>However, the code is not you wanted. Your code is trying to perform lazy-initialization after the instance is created. This requires all the client library to perform 'firstTime()/doPreparation()' before using it. You are going to rely on the client to do right thing which make the code very fragile.</p>\n\n<p>You can modify the code as the following so there won't be any duplicate code.</p>\n\n<pre><code>public class Single\n{\n private static Single theInstance = new Single();\n\n private Single() \n { \n // load properties\n }\n\n public static Single getInstance() \n { \n // check for initialization of theInstance\n if ( theInstance.firstTime() )\n theInstance.doPreparation();\n\n return theInstance;\n }\n}\n</code></pre>\n\n<p>Unfortunately, this is a poor implementation of lazy initialization and this will not work in concurrent environment ( like J2EE container ). </p>\n\n<p>There are many articles written about Singleton initialization, specifically on memory model. <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html\" rel=\"noreferrer\">JSR 133</a> addressed many weakness in Java memory model in Java 1.5 and 1.6.</p>\n\n<p>With Java 1.5 &amp; 1.6, you have several choices and they are mentioned in the book '<a href=\"http://java.sun.com/docs/books/effective/\" rel=\"noreferrer\">Effective Java</a>' by Joshua Bloch.</p>\n\n<ol>\n<li>Eager Initialziation, like the above [EJ Item 3]</li>\n<li>Lazy Initalization Holder Class Idiom [EJ Item 71]</li>\n<li>Enum Type [EJ Item 3]</li>\n<li>Double Checked Locking with 'volatile' static field [EJ Item 71]</li>\n</ol>\n\n<p>Solution 3 and 4 will only work in Java 1.5 and above. So the best solution would be #2.</p>\n\n<p>Here is the psuedo-implementation.</p>\n\n<pre><code>public class Single\n{\n private static class SingleHolder\n {\n public static Single theInstance = new Single();\n }\n\n private Single() \n { \n // load properties\n doPreparation();\n }\n\n public static Single getInstance() \n {\n return SingleHolder.theInstance;\n }\n}\n</code></pre>\n\n<p>Notice that 'doPreparation()' is inside of the constructor so you are guarantee to get the properly initialized instance. Also, you are piggying back on JVM's lazy class loading and do not need any synchronization 'getInstance()'.</p>\n\n<p>One thing you noticed that static field theInstance is <strong>not 'final'.</strong> The example on Java Concurrency does not have 'final' but EJ does. Maybe James's can add more color to his answer on 'classloader' and requirement of 'final' to guarantee correctness,</p>\n\n<p>Having said that, there are a side-effect that with using 'static final'. Java compiler is very aggressive when it sees 'static final' and tries to inline it as much as possible. This is mentioned on <a href=\"http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html\" rel=\"noreferrer\">a blog posting by Jeremy Manson</a>.</p>\n\n<p>Here is a simple example.</p>\n\n<p>file: A.java</p>\n\n<pre><code>public class A\n{\n final static String word = \"Hello World\";\n}\n</code></pre>\n\n<p>file: B.java</p>\n\n<pre><code>public class B\n{\n public static void main(String[] args) {\n System.out.println(A.word);\n }\n}\n</code></pre>\n\n<p>After you compile both A.java and B.java, you change A.java to following.</p>\n\n<p>file: A.java</p>\n\n<pre><code>public class A\n{\n final static String word = \"Goodbye World\";\n}\n</code></pre>\n\n<p>You recompile 'A.java' and rerun B.class. The output you would get is</p>\n\n<pre><code>Hello World\n</code></pre>\n\n<p>As for the classloader issue, the answer is yes, you can have more than one instance of Singleton in multiple classloaders. You can find more information on <a href=\"http://en.wikipedia.org/wiki/Java_Classloader\" rel=\"noreferrer\">wikipedia</a>. There is also a specific article on <a href=\"http://www-128.ibm.com/developerworks/websphere/library/techarticles/0112_deboer/deboer.html\" rel=\"noreferrer\">Websphere</a>.</p>\n" }, { "answer_id": 990846, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's not mandatory for the single instance to be final (it's not a good idea at all indeed, because this will avoid you to switch it's behaviour using other patterns).</p>\n\n<h1>In the code below you can see how it gets instantiated only once (first time you call the constructor)</h1>\n\n<p>package date;</p>\n\n<p>import java.util.Date;</p>\n\n<p>public class USDateFactory implements DateFactory {\n private static USDateFactory usdatefactory = null;</p>\n\n<pre><code>private USDateFactory () { }\n\npublic static USDateFactory getUsdatefactory() {\n if(usdatefactory==null) {\n usdatefactory = new USDateFactory();\n }\n return usdatefactory;\n}\n\npublic String getTextDate (Date date) {\n return null;\n}\n\npublic NumericalDate getNumericalDate (Date date) {\n return null;\n}\n</code></pre>\n\n<p>}</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30381/" ]
I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty): ``` ... if(Single.getInstance().firstTime()){ doPreperations(); } normalResponse(); ... ``` The singleton 'Single' looks like this: ``` private static Single theInstance = new Single(); private Single() { ...load properties... } public static Single getInstance() { return theInstance; } ``` With the way this is set to use a static initializer instead of checking for a null theInstance in the getInstance() method, could this get rebuilt over and over again? PS - We're running WebSphere 6 with the App on Java 1.4
I found this on Sun's site: > > ### Multiple Singletons Simultaneously Loaded by Different Class Loaders > > > When two class loaders load a class, > you actually have two copies of the > class, and each one can have its own > Singleton instance. That is > particularly relevant in servlets > running in certain servlet engines > (iPlanet for example), where each > servlet by default uses its own class > loader. Two different servlets > accessing a joint Singleton will, in > fact, get two different objects. > > > Multiple class loaders occur more > commonly than you might think. When > browsers load classes from the network > for use by applets, they use a > separate class loader for each server > address. Similarly, Jini and RMI > systems may use a separate class > loader for the different code bases > from which they download class files. > If your own system uses custom class > loaders, all the same issues may > arise. > > > If loaded by different class loaders, > two classes with the same name, even > the same package name, are treated as > distinct -- even if, in fact, they are > byte-for-byte the same class. The > different class loaders represent > different namespaces that distinguish > classes (even though the classes' > names are the same), so that the two > `MySingleton` classes are in fact > distinct. (See "Class Loaders as a > Namespace Mechanism" in Resources.) > Since two Singleton objects belong to > two classes of the same name, it will > appear at first glance that there are > two Singleton objects of the same > class. > > > [Citation](http://www.oracle.com/technetwork/articles/java/singleton-1577166.html). In addition to the above issue, if `firstTime()` is not synchronized, you could have threading issues there as well.
225,915
<p>I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written...</p> <pre><code> for (var intElement = 0; intElement &lt; document.forms[0].elements.length; intElement = intElement + 1) { if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field { if (document.forms[0].elements[intElement].onblur()) { return false; break; } } } return true; </code></pre> <p>I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing.</p> <p>The onblur method that is getting called looks like this...</p> <pre><code>function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode) { var tagCreditOrDebit; var tagIsTotal; var tagPercentageOrDecimal; eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC"); eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal"); eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal"); if (tagPercentageOrDecimal.value == "P") { reaMax = Math.round((reaMax - 1) * 100); reaMin = Math.round((1 - reaMin) * 100); if (parseFloat(tagFactor.value) == 0) { alert("Please enter a value other than 0 or leave this field blank."); f_SetFocus(tagFactor); return false; } if (tagIsTotal.value == "True") { if (tagCreditOrDebit.checked) { if (parseFloat(tagFactor.value) &gt; reaMin) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } else { if (parseFloat(tagFactor.value) &gt; reaMax) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } } } return true; } </code></pre> <p><strong>EDIT:</strong> I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below...</p> <pre><code> if (!document.forms[0].elements[intElement].onblur()) </code></pre> <p>or</p> <pre><code> if (document.forms[0].elements[intElement].onblur()) </code></pre> <p>is not returning what the single onblur function (f_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function.</p>
[ { "answer_id": 225969, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": -1, "selected": false, "text": "<p>First, for the love of god and all that is holy, stop writing native javascript and help yourself to some of that <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> :)</p>\n\n<p>Second, start using a validation framework. For jQuery, <a href=\"http://docs.jquery.com/Plugins/Validation\" rel=\"nofollow noreferrer\">jQuery Validate</a> usually works really well. It supports things like dependencies between different fields, etc. And you can also quite easily add new rules, like valid ISBN numbers, etc.</p>\n\n<p><strong>Edit:</strong> As for your code, I'm not sure that you can use onunload for this, as at that point there's no way back, you can't abort at that point. You should put this code on the onsubmit event instead.</p>\n" }, { "answer_id": 226284, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p>This question is a bit too involved for me at this time of the night, but I will give you this bit of advice:</p>\n\n<pre><code>eval(\"tagCreditOrDebit = document.forms[0].\" + tagFactor.name.substr(0,3) + \"CreditOrDebitC\");\n</code></pre>\n\n<p>This can be written in a MUCH better way:</p>\n\n<pre><code>tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + \"CreditOrDebitC\"];\n</code></pre>\n\n<p>In javascript, anywhere where you can use dotted syntax, you can use square brackets.</p>\n\n<pre><code>document.body;\ndocument['body'];\nvar b = 'body';\ndocument[b];\n</code></pre>\n\n<p>Also, think about giving your forms some sort of identifier. I have no clue at all why <code>document.forms[0]</code> was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break!</p>\n\n<p>Other ways to do it include:</p>\n\n<pre><code>// HTML\n&lt;form name=\"myFormName\"&gt;\n\n// Javascript\nvar f = document.myFormName;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;form id=\"myFormId\"&gt;\n\nvar f = document.getElementById(\"myFormId\")\n</code></pre>\n" }, { "answer_id": 227100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I ended up solving this with a global variable. I originally set a value <code>g_bHardEditsPassed</code> to true assuming we will have no errors. Then in <code>f_VerifyRange</code>, everytime I return a value, I put a line before it to set the <code>g_bHardEditsPassed</code> variable to match. Then I modified the loop to look like this...</p>\n\n<pre><code> g_bHardEditsPassed = true;\n\n for (var intElement = 0; intElement &lt; document.forms[0].elements.length; intElement = intElement + 1)\n {\n if (document.forms[0].elements[intElement].name.substr(3) == \"FactorAmount\")\n {\n document.forms[0].elements[intElement].onblur()\n if (!g_bHardEditsPassed)\n {\n g_bHardEditsPassed = true;\n return false;\n }\n }\n }\n\n return true;\n</code></pre>\n\n<p>Thanks for everyone's suggestions. I'm sure that the jQuery thing especially will be worth looking into for the future.</p>\n" }, { "answer_id": 227893, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": 0, "selected": false, "text": "<p>You´re not getting any success with <code>if (!...onblur())</code> because the return of <code>onblur()</code> is always <code>undefined</code> when used directly. <code>OnBlur()</code> is a <a href=\"http://www.w3schools.com/jsref/jsref_events.asp\" rel=\"nofollow noreferrer\">Event Handler Function</a>. Like you descovered, you have to create a workaround.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written... ``` for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1) { if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field { if (document.forms[0].elements[intElement].onblur()) { return false; break; } } } return true; ``` I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing. The onblur method that is getting called looks like this... ``` function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode) { var tagCreditOrDebit; var tagIsTotal; var tagPercentageOrDecimal; eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC"); eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal"); eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal"); if (tagPercentageOrDecimal.value == "P") { reaMax = Math.round((reaMax - 1) * 100); reaMin = Math.round((1 - reaMin) * 100); if (parseFloat(tagFactor.value) == 0) { alert("Please enter a value other than 0 or leave this field blank."); f_SetFocus(tagFactor); return false; } if (tagIsTotal.value == "True") { if (tagCreditOrDebit.checked) { if (parseFloat(tagFactor.value) > reaMin) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } else { if (parseFloat(tagFactor.value) > reaMax) { alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit."); f_SetFocus(tagFactor); return false; } } } } return true; } ``` **EDIT:** I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below... ``` if (!document.forms[0].elements[intElement].onblur()) ``` or ``` if (document.forms[0].elements[intElement].onblur()) ``` is not returning what the single onblur function (f\_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f\_VerifyRange which is my onblur function.
This question is a bit too involved for me at this time of the night, but I will give you this bit of advice: ``` eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC"); ``` This can be written in a MUCH better way: ``` tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + "CreditOrDebitC"]; ``` In javascript, anywhere where you can use dotted syntax, you can use square brackets. ``` document.body; document['body']; var b = 'body'; document[b]; ``` Also, think about giving your forms some sort of identifier. I have no clue at all why `document.forms[0]` was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break! Other ways to do it include: ``` // HTML <form name="myFormName"> // Javascript var f = document.myFormName; ``` or ``` <form id="myFormId"> var f = document.getElementById("myFormId") ```
225,916
<p>Following on from this question <a href="https://stackoverflow.com/questions/150814/how-to-handle-an-activex-event-in-javascript">here</a></p> <p>I have a custom ActiveX control which raises an event "BeforePageValidated" which has a parameter "args" which is an object which contains a boolean. The purpose of this is to allow the client to override the validation and force it fail by setting the boolean value to true.</p> <p>I can catch the event in IE using the following</p> <pre><code>&lt;script for="objInterviewNOW" event="BeforePageValidated(args)"&gt; </code></pre> <p>However I can't access the property of the args object.</p> <p>How should I be doing this?</p>
[ { "answer_id": 225974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Worked it out for myself.</p>\n\n<p>The problem was that the event was being passed down from another dll used by the activeX control, and this is where the args class was declared.</p>\n\n<p>Fixed it by creating a copy of the args class in the activeX object and using this when raising the event.</p>\n\n<p>Unfortunately does mean the args class is duplicated, so maybe someone knows a better way?</p>\n" }, { "answer_id": 1291903, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><code>args</code> also needs to register as com object.</p>\n\n<pre><code>[ComVisible(true)]\n[GuidAttribute(\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\")]\npublic class args\n{\n\n}\n</code></pre>\n\n<p>Hope this will help.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Following on from this question [here](https://stackoverflow.com/questions/150814/how-to-handle-an-activex-event-in-javascript) I have a custom ActiveX control which raises an event "BeforePageValidated" which has a parameter "args" which is an object which contains a boolean. The purpose of this is to allow the client to override the validation and force it fail by setting the boolean value to true. I can catch the event in IE using the following ``` <script for="objInterviewNOW" event="BeforePageValidated(args)"> ``` However I can't access the property of the args object. How should I be doing this?
Worked it out for myself. The problem was that the event was being passed down from another dll used by the activeX control, and this is where the args class was declared. Fixed it by creating a copy of the args class in the activeX object and using this when raising the event. Unfortunately does mean the args class is duplicated, so maybe someone knows a better way?
225,929
<p>I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java. C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves. </p> <p>What’s the matter with multiple inheritance? Are there any concrete samples? </p>
[ { "answer_id": 225945, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 4, "selected": false, "text": "<p>let's say you have objects A and B which are both inherited by C. A and B both implement foo() and C does not. I call C.foo(). Which implementation gets chosen? There are other issues, but this type of thing is a big one.</p>\n" }, { "answer_id": 225973, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 3, "selected": false, "text": "<p>The main problem with multiple inheritance is nicely summed up with tloach's example. When inheriting from multiple base classes that implement the same function or field it's the compiler has to make a decision about what implementation to inherit.</p>\n\n<p>This get's worse when you inherit from multiple classes that inherit from the same base class. (diamond inheritance, if you draw the inheritance tree you get a diamond shape)</p>\n\n<p>These problems are not really problematic for a compiler to overcome. But the choice the compiler has to make here are rather arbitrary, this make code far less intuitive.</p>\n\n<p>I find that when doing good OO design I never need multiple inheritance. In cases I do need it I usually find I've been using inheritance to reuse functionality while inheritance is only appropriate for \"is-a\" relations.</p>\n\n<p>There are other techniques like mixins that solve the same problems and don't have the issues that multiple inheritance has.</p>\n" }, { "answer_id": 225991, "author": "J Francis", "author_id": 19169, "author_profile": "https://Stackoverflow.com/users/19169", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Diamond_problem\" rel=\"noreferrer\">The diamond problem</a>:</p>\n\n<blockquote>\n <p>an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have <a href=\"https://en.wikipedia.org/wiki/Method_overriding_(programming)\" rel=\"noreferrer\">overridden</a>, and D does not override it, then which version of the method does D inherit: that of B, or that of C?</p>\n \n <p>...It is called the \"diamond problem\" because of the shape of the class inheritance diagram in this situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape...</p>\n</blockquote>\n" }, { "answer_id": 225997, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 4, "selected": false, "text": "<p>Multiple inheritance is one of those things that is not used often, and can be misused, but is sometimes needed.</p>\n\n<p>I never understood not adding a feature, just because it might be misused, when there are no good alternatives. Interfaces are not an alternative to multiple inheritance. For one, they don't let you enforce preconditions or postconditions. Just like any other tool, you need to know when it is appropriate to use, and how to use it.</p>\n" }, { "answer_id": 226056, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 8, "selected": true, "text": "<p>The most obvious problem is with function overriding.</p>\n\n<p>Let's say have two classes <code>A</code> and <code>B</code>, both of which define a method <code>doSomething</code>. Now you define a third class <code>C</code>, which inherits from both <code>A</code> and <code>B</code>, but you don't override the <code>doSomething</code> method.</p>\n\n<p>When the compiler seed this code...</p>\n\n<pre><code>C c = new C();\nc.doSomething();\n</code></pre>\n\n<p>...which implementation of the method should it use? Without any further clarification, it's impossible for the compiler to resolve the ambiguity.</p>\n\n<p>Besides overriding, the other big problem with multiple inheritance is the layout of the physical objects in memory.</p>\n\n<p>Languages like C++ and Java and C# create a fixed address-based layout for each type of object. Something like this:</p>\n\n<pre><code>class A:\n at offset 0 ... \"abc\" ... 4 byte int field\n at offset 4 ... \"xyz\" ... 8 byte double field\n at offset 12 ... \"speak\" ... 4 byte function pointer\n\nclass B:\n at offset 0 ... \"foo\" ... 2 byte short field\n at offset 2 ... 2 bytes of alignment padding\n at offset 4 ... \"bar\" ... 4 byte array pointer\n at offset 8 ... \"baz\" ... 4 byte function pointer\n</code></pre>\n\n<p>When the compiler generates machine code (or bytecode), it uses those numeric offsets to access each method or field.</p>\n\n<p>Multiple inheritance makes it very tricky.</p>\n\n<p>If class <code>C</code> inherits from both <code>A</code> and <code>B</code>, the compiler has to decide whether to layout the data in <code>AB</code> order or in <code>BA</code> order.</p>\n\n<p>But now imagine that you're calling methods on a <code>B</code> object. Is it really just a <code>B</code>? Or is it actually a <code>C</code> object being called polymorphically, through its <code>B</code> interface? Depending on the actual identity of the object, the physical layout will be different, and its impossible to know the offset of the function to invoke at the call-site.</p>\n\n<p>The way to handle this kind of system is to ditch the fixed-layout approach, allowing each object to be queried for its layout <em>before</em> attempting to invoke the functions or access its fields.</p>\n\n<p>So...long story short...it's a pain in the neck for compiler authors to support multiple inheritance. So when someone like Guido van Rossum designs python, or when Anders Hejlsberg designs c#, they know that supporting multiple inheritance is going to make the compiler implementations significantly more complex, and presumably they don't think the benefit is worth the cost.</p>\n" }, { "answer_id": 291585, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>The problems you guys mention are not really that hard to solve. In fact e.g. Eiffel does that perfectly well! (and without introducing arbitrary choices or whatever)</p>\n\n<p>E.g. if you inherit from A and B, both having method foo(), then of course you don't want an arbitrary choice in your class C inheriting from both A and B.\nYou have to either redefine foo so it's clear what will be used if c.foo() is called or otherwise you have to rename one of the methods in C. (it could become bar())</p>\n\n<p>Also I think that multiple inheritance is often quite useful. If you look at libraries of Eiffel you'll see that it's used all over the place and personally I've missed the feature when I had to go back to programming in Java.</p>\n" }, { "answer_id": 1368211, "author": "Christian Lemer", "author_id": 167077, "author_profile": "https://Stackoverflow.com/users/167077", "pm_score": 2, "selected": false, "text": "<p>There is nothing wrong in multiple inheritance itself. The problem is to add multiple inheritance to a language that was not designed with multiple inheritance in mind from the start.</p>\n\n<p>The Eiffel language is supporting multiple inheritance without restrictions in a very efficient and productive way but the language was designed from that start to support it.</p>\n\n<p>This feature is complex to implement for compiler developers, but it seems that that drawback could be compensated by the fact that a good multiple inheritance support could avoid the support of other features (i.e. no need for Interface or Extension Method).</p>\n\n<p>I think that supporting multiple inheritance or not is more a matter of choice, a matter of priorities. A more complex feature takes more time to be correctly implemented and operational and may be more controversial. The C++ implementation may be the reason why multiple inheritance was not implemented in C# and Java... </p>\n" }, { "answer_id": 2521864, "author": "Frank Shearar", "author_id": 10259, "author_profile": "https://Stackoverflow.com/users/10259", "pm_score": 2, "selected": false, "text": "<p>The Common Lisp Object System (CLOS) is another example of something that supports MI while avoiding the C++-style problems: inheritance is given a <a href=\"http://www.gigamonkeys.com/book/object-reorientation-classes.html\" rel=\"nofollow noreferrer\">sensible default</a>, while still allowing you the freedom to explicitly decide how exactly to, say, call a super's behaviour.</p>\n" }, { "answer_id": 3184459, "author": "Turing Complete", "author_id": 372920, "author_profile": "https://Stackoverflow.com/users/372920", "pm_score": 3, "selected": false, "text": "<p>I don't think the diamond problem is a problem, I would consider that sophistry, nothing else.</p>\n\n<p>The worst problem, from my point of view, with multiple inheritance is RAD - victims and people who claim to be developers but in reality are stuck with half - knowledge (at best).</p>\n\n<p>Personally, I would be very happy if I could finally do something in Windows Forms like this (it's not correct code, but it should give you the idea):</p>\n\n<pre><code>public sealed class CustomerEditView : Form, MVCView&lt;Customer&gt;\n</code></pre>\n\n<p>This is the main issue I have with having no multiple inheritance. You CAN do something similar with interfaces, but there is what I call \"s*** code\", it's this painful repetitive c*** you have to write in each of your classes to get a data context, for example.</p>\n\n<p>In my opinion, there should be absolutely no need, not the slightest, for ANY repetition of code in a modern language.</p>\n" }, { "answer_id": 15883576, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "<p>One of the design goals of frameworks like Java and .NET is to make it possible for code which is compiled to work with one version of a pre-compiled library, to work equally well with subsequent versions of that library, even if those subsequent versions add new features. While the normal paradigm in languages like C or C++ is to distribute statically-linked executables that contain all of the libraries they need, the paradigm in .NET and Java is to distribute applications as collections of components that are \"linked\" at run-time.</p>\n\n<p>The COM model which preceded .NET attempted to use this general approach, but it didn't really have inheritance--instead, each class definition effectively defined both a class and an interface of the same name which contained all its public members. Instances were of the class type, while references were of the interface type. Declared a class as deriving from another was equivalent to declaring a class as implementing the other's interface, and required the new class to re-implement all public members of the classes from which one derived. If Y and Z derive from X, and then W derives from Y and Z, it won't matter if Y and Z implement X's members differently, because Z won't be able to use their implementations--it will have to define its own. W might encapsulate instances of Y and/or Z, and chain its implementations of X's methods through theirs, but there would be no ambiguity as to what X's methods should do--they'd do whatever Z's code explicitly directed them to do.</p>\n\n<p>The difficulty in Java and .NET is that code is allowed to inherit members and have accesses to them <em>implicitly</em> refer to the parent members. Suppose one had classes W-Z related as above:</p>\n\n<pre><code>class X { public virtual void Foo() { Console.WriteLine(\"XFoo\"); }\nclass Y : X {};\nclass Z : X {};\nclass W : Y, Z // Not actually permitted in C#\n{\n public static void Test()\n {\n var it = new W();\n it.Foo();\n }\n}\n</code></pre>\n\n<p>It would seem like <code>W.Test()</code> should creating an instance of W call the implementation of virtual method <code>Foo</code> defined in <code>X</code>. Suppose, however, that Y and Z were actually in a separately-compiled module, and although they were defined as above when X and W were compiled, they were later changed and recompiled:</p>\n\n<pre><code>class Y : X { public override void Foo() { Console.WriteLine(\"YFoo\"); }\nclass Z : X { public override void Foo() { Console.WriteLine(\"ZFoo\"); }\n</code></pre>\n\n<p>Now what should be the effect of calling <code>W.Test()</code>? If the program had to be statically linked before distribution, the static link stage might be able to discern that while the program had no ambiguity before Y and Z were changed, the changes to Y and Z have made things ambiguous and the linker could refuse to build the program unless or until such ambiguity is resolved. On the other hand, it's possible that the person who has both W and the new versions of Y and Z is someone who simply wants to run the program and has no source code for any of it. When <code>W.Test()</code> runs, it would no longer be clear what <code>W.Test()</code> should do, but until the user tried to run W with the new version of Y and Z there would be no way any part of the system could recognize there was a problem (unless W was considered illegitimate even before the changes to Y and Z).</p>\n" }, { "answer_id": 37380038, "author": "number Zero", "author_id": 6368531, "author_profile": "https://Stackoverflow.com/users/6368531", "pm_score": 2, "selected": false, "text": "<p>The diamond is not a problem, as long as you <strong>don’t</strong> use anything like C++ virtual inheritance: in normal inheritance each base class resembles a member field (actually they are laid out in RAM this way), giving you some syntactic sugar and an extra ability to override more virtual methods. That may impose some ambiguity at compile-time but that’s usually easy to solve.</p>\n\n<p>On the other hand, with the virtual inheritance it too easily goes out of control (and then becomes a mess). Consider as an example a “heart” diagram:</p>\n\n<pre><code> A A\n / \\ / \\\nB C D E\n \\ / \\ /\n F G\n \\ /\n H\n</code></pre>\n\n<p>In C++ it is entirely impossible: as soon as <code>F</code> and <code>G</code> are merged into a single class, their <code>A</code>s are merged too, period. That means you may never consider base classes opaque in C++ (in this example you have to construct <code>A</code> in <code>H</code> so you have to know that it present somewhere in the hierarchy). In other languages it may work, however; for example, <code>F</code> and <code>G</code> could explicitly declare A as “internal,” thus forbidding consequent merging and effectively making themselves solid.</p>\n\n<p>Another interesting example (<strong>not</strong> C++-specific):</p>\n\n<pre><code> A\n / \\\nB B\n| |\nC D\n \\ /\n E\n</code></pre>\n\n<p>Here, only <code>B</code> uses virtual inheritance. So <code>E</code> contains two <code>B</code>s that share the same <code>A</code>. This way, you can get an <code>A*</code> pointer that points to <code>E</code>, but you can’t cast it to a <code>B*</code> pointer although the object <strong>is</strong> actually <code>B</code> as such cast is ambiguous, and this ambiguity can’t be detected at compile time (unless the compiler sees the whole program). Here is the test code:</p>\n\n<pre><code>struct A { virtual ~A() {} /* so that the class is polymorphic */ };\nstruct B: virtual A {};\nstruct C: B {};\nstruct D: B {};\nstruct E: C, D {};\n\nint main() {\n E data;\n E *e = &amp;data;\n A *a = dynamic_cast&lt;A *&gt;(e); // works, A is unambiguous\n// B *b = dynamic_cast&lt;B *&gt;(e); // doesn't compile\n B *b = dynamic_cast&lt;B *&gt;(a); // NULL: B is ambiguous\n std::cout &lt;&lt; \"E: \" &lt;&lt; e &lt;&lt; std::endl;\n std::cout &lt;&lt; \"A: \" &lt;&lt; a &lt;&lt; std::endl;\n std::cout &lt;&lt; \"B: \" &lt;&lt; b &lt;&lt; std::endl;\n// the next casts work\n std::cout &lt;&lt; \"A::C::B: \" &lt;&lt; dynamic_cast&lt;B *&gt;(dynamic_cast&lt;C *&gt;(e)) &lt;&lt; std::endl;\n std::cout &lt;&lt; \"A::D::B: \" &lt;&lt; dynamic_cast&lt;B *&gt;(dynamic_cast&lt;D *&gt;(e)) &lt;&lt; std::endl;\n std::cout &lt;&lt; \"A=&gt;C=&gt;B: \" &lt;&lt; dynamic_cast&lt;B *&gt;(dynamic_cast&lt;C *&gt;(a)) &lt;&lt; std::endl;\n std::cout &lt;&lt; \"A=&gt;D=&gt;B: \" &lt;&lt; dynamic_cast&lt;B *&gt;(dynamic_cast&lt;D *&gt;(a)) &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n\n<p>Moreover, the implementation may be very complex (depends on language; see benjismith’s answer).</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22088/" ]
I can see people asking all the time whether multiple inheritance should be included into the next version of C# or Java. C++ folks, who are fortunate enough to have this ability, say that this is like giving someone a rope to eventually hang themselves. What’s the matter with multiple inheritance? Are there any concrete samples?
The most obvious problem is with function overriding. Let's say have two classes `A` and `B`, both of which define a method `doSomething`. Now you define a third class `C`, which inherits from both `A` and `B`, but you don't override the `doSomething` method. When the compiler seed this code... ``` C c = new C(); c.doSomething(); ``` ...which implementation of the method should it use? Without any further clarification, it's impossible for the compiler to resolve the ambiguity. Besides overriding, the other big problem with multiple inheritance is the layout of the physical objects in memory. Languages like C++ and Java and C# create a fixed address-based layout for each type of object. Something like this: ``` class A: at offset 0 ... "abc" ... 4 byte int field at offset 4 ... "xyz" ... 8 byte double field at offset 12 ... "speak" ... 4 byte function pointer class B: at offset 0 ... "foo" ... 2 byte short field at offset 2 ... 2 bytes of alignment padding at offset 4 ... "bar" ... 4 byte array pointer at offset 8 ... "baz" ... 4 byte function pointer ``` When the compiler generates machine code (or bytecode), it uses those numeric offsets to access each method or field. Multiple inheritance makes it very tricky. If class `C` inherits from both `A` and `B`, the compiler has to decide whether to layout the data in `AB` order or in `BA` order. But now imagine that you're calling methods on a `B` object. Is it really just a `B`? Or is it actually a `C` object being called polymorphically, through its `B` interface? Depending on the actual identity of the object, the physical layout will be different, and its impossible to know the offset of the function to invoke at the call-site. The way to handle this kind of system is to ditch the fixed-layout approach, allowing each object to be queried for its layout *before* attempting to invoke the functions or access its fields. So...long story short...it's a pain in the neck for compiler authors to support multiple inheritance. So when someone like Guido van Rossum designs python, or when Anders Hejlsberg designs c#, they know that supporting multiple inheritance is going to make the compiler implementations significantly more complex, and presumably they don't think the benefit is worth the cost.
225,937
<p>There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.</p> <p>First type:</p> <pre><code>List&lt;string&gt; someList = &lt;some way to init&gt; foreach(string s in someList) { &lt;process the string&gt; } </code></pre> <p>Other Way:</p> <pre><code>List&lt;string&gt; someList = &lt;some way to init&gt; someList.ForEach(delegate(string s) { &lt;process the string&gt; }); </code></pre> <p>I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...</p>
[ { "answer_id": 225952, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 4, "selected": false, "text": "<p>I guess the <code>someList.ForEach()</code> call could be easily parallelized whereas the normal <code>foreach</code> is not that easy to run parallel.\nYou could easily run several different delegates on different cores, which is not that easy to do with a normal <code>foreach</code>.<br/>\nJust my 2 cents</p>\n" }, { "answer_id": 225957, "author": "Craig.Nicol", "author_id": 1404, "author_profile": "https://Stackoverflow.com/users/1404", "pm_score": 3, "selected": false, "text": "<p>You could name the anonymous delegate :-)</p>\n\n<p>And you can write the second as:</p>\n\n<pre><code>someList.ForEach(s =&gt; s.ToUpper())\n</code></pre>\n\n<p>Which I prefer, and saves a lot of typing.</p>\n\n<p>As Joachim says, parallelism is easier to apply to the second form.</p>\n" }, { "answer_id": 225959, "author": "EFrank", "author_id": 28572, "author_profile": "https://Stackoverflow.com/users/28572", "pm_score": 1, "selected": false, "text": "<p>The second way you showed uses an extension method to execute the delegate method for each of the elements in the list.</p>\n\n<p>This way, you have another delegate (=method) call.</p>\n\n<p>Additionally, there is the possibility to iterate the list with a <em>for</em> loop.</p>\n" }, { "answer_id": 225966, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 2, "selected": false, "text": "<p>Behind the scenes, the anonymous delegate gets turned into an actual method so you could have some overhead with the second choice if the compiler didn't choose to inline the function. Additionally, any local variables referenced by the body of the anonymous delegate example would change in nature because of compiler tricks to hide the fact that it gets compiled to a new method. More info here on how C# does this magic:</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx</a></p>\n" }, { "answer_id": 226012, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 1, "selected": false, "text": "<p>One thing to be wary of is how to exit from the Generic .ForEach method - see <a href=\"http://silverlight.net/forums/t/32450.aspx\" rel=\"nofollow noreferrer\">this discussion</a>. Although the link seems to say that this way is the fastest. Not sure why - you'd think they would be equivalent once compiled...</p>\n" }, { "answer_id": 226040, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>List.ForEach() is considered to be more functional.</p>\n\n<p><code>List.ForEach()</code> says what you want done. <code>foreach(item in list)</code> also says exactly how you want it done. This leaves <code>List.ForEach</code> free to change the implementation of the <em>how</em> part in the future. For example, a hypothetical future version of .Net might always run <code>List.ForEach</code> in parallel, under the assumption that at this point everyone has a number of cpu cores that are generally sitting idle. </p>\n\n<p>On the other hand, <code>foreach (item in list)</code> gives you a little more control over the loop. For example, you know that the items will be iterated in some kind of sequential order, and you could easily break in the middle if an item meets some condition.</p>\n\n<hr>\n\n<p>Some more recent remarks on this issue are available here:</p>\n\n<blockquote>\n <p><a href=\"https://stackoverflow.com/a/529197/3043\">https://stackoverflow.com/a/529197/3043</a></p>\n</blockquote>\n" }, { "answer_id": 226082, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<p>There is one important, and useful, distinction between the two.</p>\n\n<p>Because .ForEach uses a <code>for</code> loop to iterate the collection, this is valid (edit: <strong>prior to .net 4.5</strong> - the implementation changed and they both throw):</p>\n\n<pre><code>someList.ForEach(x =&gt; { if(x.RemoveMe) someList.Remove(x); }); \n</code></pre>\n\n<p>whereas <code>foreach</code> uses an enumerator, so this is not valid:</p>\n\n<pre><code>foreach(var item in someList)\n if(item.RemoveMe) someList.Remove(item);\n</code></pre>\n\n<hr>\n\n<p><strong>tl;dr: Do NOT copypaste this code into your application!</strong> </p>\n\n<p>These examples aren't best practice, they are just to demonstrate the differences between <code>ForEach()</code> and <code>foreach</code>.</p>\n\n<p>Removing items from a list within a <code>for</code> loop can have side effects. The most common one is described in the comments to this question.</p>\n\n<p>Generally, if you are looking to remove multiple items from a list, you would want to separate the determination of which items to remove from the actual removal. It doesn't keep your code compact, but it guarantees that you do not miss any items.</p>\n" }, { "answer_id": 226094, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 4, "selected": false, "text": "<p>For fun, I popped List into reflector and this is the resulting C#:</p>\n\n<pre><code>public void ForEach(Action&lt;T&gt; action)\n{\n if (action == null)\n {\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);\n }\n for (int i = 0; i &lt; this._size; i++)\n {\n action(this._items[i]);\n }\n}\n</code></pre>\n\n<p>Similarly, the MoveNext in Enumerator which is what is used by foreach is this:</p>\n\n<pre><code>public bool MoveNext()\n{\n if (this.version != this.list._version)\n {\n ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);\n }\n if (this.index &lt; this.list._size)\n {\n this.current = this.list._items[this.index];\n this.index++;\n return true;\n }\n this.index = this.list._size + 1;\n this.current = default(T);\n return false;\n}\n</code></pre>\n\n<p>The List.ForEach is much more trimmed down than MoveNext - far less processing - will more likely JIT into something efficient..</p>\n\n<p>In addition, foreach() will allocate a new Enumerator no matter what. The GC is your friend, but if you're doing the same foreach repeatedly, this will make more throwaway objects, as opposed to reusing the same delegate - <strong>BUT</strong> - this is really a fringe case. In typical usage you will see little or no difference.</p>\n" }, { "answer_id": 226299, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 6, "selected": false, "text": "<p>We had some code here (in VS2005 and C#2.0) where the previous engineers went out of their way to use <code>list.ForEach( delegate(item) { foo;});</code> instead of <code>foreach(item in list) {foo; };</code> for all the code that they wrote. e.g. a block of code for reading rows from a dataReader.</p>\n\n<p>I still don't know exactly why they did this.</p>\n\n<p>The drawbacks of <code>list.ForEach()</code> are:</p>\n\n<ul>\n<li><p>It is more verbose in C# 2.0. However, in C# 3 onwards, you can use the \"<code>=&gt;</code>\" syntax to make some nicely terse expressions.</p></li>\n<li><p>It is less familiar. People who have to maintain this code will wonder why you did it that way. It took me awhile to decide that there wasn't any reason, except maybe to make the writer seem clever (the quality of the rest of the code undermined that). It was also less readable, with the \"<code>})</code>\" at the end of the delegate code block.</p></li>\n<li><p>See also Bill Wagner's book \"Effective C#: 50 Specific Ways to Improve Your C#\" where he talks about why foreach is preferred to other loops like for or while loops - the main point is that you are letting the compiler decide the best way to construct the loop. If a future version of the compiler manages to use a faster technique, then you will get this for free by using foreach and rebuilding, rather than changing your code.</p></li>\n<li><p>a <code>foreach(item in list)</code> construct allows you to use <code>break</code> or <code>continue</code> if you need to exit the iteration or the loop. But you cannot alter the list inside a foreach loop.</p></li>\n</ul>\n\n<p>I'm surprised to see that <code>list.ForEach</code> is slightly faster. But that's probably not a valid reason to use it throughout , that would be premature optimisation. If your application uses a database or web service that, not loop control, is almost always going to be be where the time goes. And have you benchmarked it against a <code>for</code> loop too? The <code>list.ForEach</code> could be faster due to using that internally and a <code>for</code> loop without the wrapper would be even faster. </p>\n\n<p>I disagree that the <code>list.ForEach(delegate)</code> version is \"more functional\" in any significant way. It does pass a function to a function, but there's no big difference in the outcome or program organisation. </p>\n\n<p>I don't think that <code>foreach(item in list)</code> \"says exactly how you want it done\" - a <code>for(int 1 = 0; i &lt; count; i++)</code> loop does that, a <code>foreach</code> loop leaves the choice of control up to the compiler.</p>\n\n<p>My feeling is, on a new project, to use <code>foreach(item in list)</code> for most loops in order to adhere to the common usage and for readability, and use <code>list.Foreach()</code> only for short blocks, when you can do something more elegantly or compactly with the C# 3 \"<code>=&gt;</code>\" operator. In cases like that, there may already be a LINQ extension method that is more specific than <code>ForEach()</code>. See if <code>Where()</code>, <code>Select()</code>, <code>Any()</code>, <code>All()</code>, <code>Max()</code> or one of the many other LINQ methods doesn't already do what you want from the loop. </p>\n" }, { "answer_id": 226359, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 4, "selected": false, "text": "<p>I know two obscure-ish things that make them different. Go me!</p>\n\n<p>Firstly, there's the classic bug of making a delegate for each item in the list. If you use the foreach keyword, all your delegates can end up referring to the last item of the list:</p>\n\n<pre><code> // A list of actions to execute later\n List&lt;Action&gt; actions = new List&lt;Action&gt;();\n\n // Numbers 0 to 9\n List&lt;int&gt; numbers = Enumerable.Range(0, 10).ToList();\n\n // Store an action that prints each number (WRONG!)\n foreach (int number in numbers)\n actions.Add(() =&gt; Console.WriteLine(number));\n\n // Run the actions, we actually print 10 copies of \"9\"\n foreach (Action action in actions)\n action();\n\n // So try again\n actions.Clear();\n\n // Store an action that prints each number (RIGHT!)\n numbers.ForEach(number =&gt;\n actions.Add(() =&gt; Console.WriteLine(number)));\n\n // Run the actions\n foreach (Action action in actions)\n action();\n</code></pre>\n\n<p>The List.ForEach method doesn't have this problem. The current item of the iteration is passed by value as an argument to the outer lambda, and then the inner lambda correctly captures that argument in its own closure. Problem solved.</p>\n\n<p>(Sadly I believe ForEach is a member of List, rather than an extension method, though it's easy to define it yourself so you have this facility on any enumerable type.)</p>\n\n<p>Secondly, the ForEach method approach has a limitation. If you are implementing IEnumerable by using yield return, you can't do a yield return inside the lambda. So looping through the items in a collection in order to yield return things is not possible by this method. You'll have to use the foreach keyword and work around the closure problem by manually making a copy of the current loop value inside the loop.</p>\n\n<p><a href=\"http://incrediblejourneysintotheknown.blogspot.com/2008/06/classic-delegateforeach-interaction-bug.html\" rel=\"noreferrer\">More here</a></p>\n" }, { "answer_id": 23290957, "author": "Pablo Caballero", "author_id": 1784916, "author_profile": "https://Stackoverflow.com/users/1784916", "pm_score": 2, "selected": false, "text": "<p>The ForEach function is member of the generic class List.</p>\n\n<p>I have created the following extension to reproduce the internal code:</p>\n\n<pre><code>public static class MyExtension&lt;T&gt;\n {\n public static void MyForEach(this IEnumerable&lt;T&gt; collection, Action&lt;T&gt; action)\n {\n foreach (T item in collection)\n action.Invoke(item);\n }\n }\n</code></pre>\n\n<p>So a the end we are using a normal foreach (or a loop for if you want).</p>\n\n<p>On the other hand, using a delegate function is just another way to define a function, this code:</p>\n\n<pre><code>delegate(string s) {\n &lt;process the string&gt;\n}\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>private static void myFunction(string s, &lt;other variables...&gt;)\n{\n &lt;process the string&gt;\n}\n</code></pre>\n\n<p>or using labda expressions:</p>\n\n<pre><code>(s) =&gt; &lt;process the string&gt;\n</code></pre>\n" }, { "answer_id": 36326089, "author": "Peter Shen", "author_id": 4719126, "author_profile": "https://Stackoverflow.com/users/4719126", "pm_score": 2, "selected": false, "text": "<p>The entire ForEach scope (delegate function) is treated as a single line of code (calling the function), and you cannot set breakpoints or step into the code. If an unhandled exception occurs the entire block is marked.</p>\n" }, { "answer_id": 59277515, "author": "Stacy Dudovitz", "author_id": 1552452, "author_profile": "https://Stackoverflow.com/users/1552452", "pm_score": 4, "selected": false, "text": "<p>As they say, the devil is in the details...</p>\n\n<p>The biggest difference between the two methods of collection enumeration is that <code>foreach</code> carries state, whereas <code>ForEach(x =&gt; { })</code> does not. </p>\n\n<p>But lets dig a little deeper, because there are some things you should be aware of that can influence your decision, and there are some caveats you should be aware of when coding for either case.</p>\n\n<p>Lets use <code>List&lt;T&gt;</code> in our little experiment to observe behavior. For this experiment, I am using .NET 4.7.2:</p>\n\n<pre><code>var names = new List&lt;string&gt;\n{\n \"Henry\",\n \"Shirley\",\n \"Ann\",\n \"Peter\",\n \"Nancy\"\n};\n</code></pre>\n\n<p>Lets iterate over this with <code>foreach</code> first:</p>\n\n<pre><code>foreach (var name in names)\n{\n Console.WriteLine(name);\n}\n</code></pre>\n\n<p>We could expand this into:</p>\n\n<pre><code>using (var enumerator = names.GetEnumerator())\n{\n\n}\n</code></pre>\n\n<p>With the enumerator in hand, looking under the covers we get:</p>\n\n<pre><code>public List&lt;T&gt;.Enumerator GetEnumerator()\n{\n return new List&lt;T&gt;.Enumerator(this);\n}\n internal Enumerator(List&lt;T&gt; list)\n{\n this.list = list;\n this.index = 0;\n this.version = list._version;\n this.current = default (T);\n}\n\npublic bool MoveNext()\n{\n List&lt;T&gt; list = this.list;\n if (this.version != list._version || (uint) this.index &gt;= (uint) list._size)\n return this.MoveNextRare();\n this.current = list._items[this.index];\n ++this.index;\n return true;\n}\n\nobject IEnumerator.Current\n{\n {\n if (this.index == 0 || this.index == this.list._size + 1)\n ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);\n return (object) this.Current;\n }\n}\n</code></pre>\n\n<p>Two things become immediate evident:</p>\n\n<ol>\n<li>We are returned a stateful object with intimate knowledge of the underlying collection.</li>\n<li>The copy of the collection is a shallow copy.</li>\n</ol>\n\n<p>This is of course in no way thread safe. As was pointed out above, changing the collection while iterating is just bad mojo.</p>\n\n<p>But what about the problem of the collection becoming invalid during iteration by means outside of us mucking with the collection during iteration? Best practices suggests versioning the collection during operations and iteration, and checking versions to detect when the underlying collection changes.</p>\n\n<p>Here's where things get really murky. According to the Microsoft documentation:</p>\n\n<blockquote>\n <p>If changes are made to the collection, such as adding, modifying, or\n deleting elements, the behavior of the enumerator is undefined.</p>\n</blockquote>\n\n<p>Well, what does that mean? By way of example, just because <code>List&lt;T&gt;</code> implements exception handling does not mean that all collections that implement <code>IList&lt;T&gt;</code> will do the same. That seems to be a clear violation of the Liskov Substitution Principle:</p>\n\n<blockquote>\n <p>Objects of a superclass shall be replaceable with objects of its\n subclasses without breaking the application.</p>\n</blockquote>\n\n<p>Another problem is that the enumerator must implement <code>IDisposable</code> -- that means another source of potential memory leaks, not only if the caller gets it wrong, but if the author does not implement the <code>Dispose</code> pattern correctly.</p>\n\n<p>Lastly, we have a lifetime issue... what happens if the iterator is valid, but the underlying collection is gone? We now a snapshot of <em>what was</em>... when you separate the lifetime of a collection and its iterators, you are asking for trouble.</p>\n\n<p>Lets now examine <code>ForEach(x =&gt; { })</code>:</p>\n\n<pre><code>names.ForEach(name =&gt;\n{\n\n});\n</code></pre>\n\n<p>This expands to:</p>\n\n<pre><code>public void ForEach(Action&lt;T&gt; action)\n{\n if (action == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);\n int version = this._version;\n for (int index = 0; index &lt; this._size &amp;&amp; (version == this._version || !BinaryCompatibility.TargetsAtLeast_Desktop_V4_5); ++index)\n action(this._items[index]);\n if (version == this._version || !BinaryCompatibility.TargetsAtLeast_Desktop_V4_5)\n return;\n ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);\n}\n</code></pre>\n\n<p>Of important note is the following:</p>\n\n<p><code>for (int index = 0; index &lt; this._size &amp;&amp; ... ; ++index)\n action(this._items[index]);</code></p>\n\n<p>This code does not allocate any enumerators (nothing to <code>Dispose</code>), and does not <em>pause</em> while iterating.</p>\n\n<p>Note that this also performs a shallow copy of the underlying collection, but the collection is now a snapshot in time. If the author does not correctly implement a check for the collection changing or going 'stale', the snapshot is still valid.</p>\n\n<p>This doesn't in any way protect you from the problem of the lifetime issues... if the underlying collection disappears, you now have a shallow copy that points to what was... but at least you don't have a <code>Dispose</code> problem to deal with on orphaned iterators...</p>\n\n<p>Yes, I said iterators... sometimes its advantageous to have state. Suppose you want to maintain something akin to a database cursor... maybe multiple <code>foreach</code> style <code>Iterator&lt;T&gt;</code>'s is the way to go. I personally dislike this style of design as there are too many lifetime issues, and you rely on the good graces of the authors of the collections you are relying on (unless you literally write everything yourself from scratch).</p>\n\n<p>There is always a third option...</p>\n\n<pre><code>for (var i = 0; i &lt; names.Count; i++)\n{\n Console.WriteLine(names[i]);\n}\n</code></pre>\n\n<p>It ain't sexy, but its got teeth (apologies to <strong>Tom Cruise</strong> and the movie <strong>The Firm</strong>)</p>\n\n<p>Its your choice, but now you know and it can be an informed one.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450139/" ]
There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other. First type: ``` List<string> someList = <some way to init> foreach(string s in someList) { <process the string> } ``` Other Way: ``` List<string> someList = <some way to init> someList.ForEach(delegate(string s) { <process the string> }); ``` I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...
There is one important, and useful, distinction between the two. Because .ForEach uses a `for` loop to iterate the collection, this is valid (edit: **prior to .net 4.5** - the implementation changed and they both throw): ``` someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); }); ``` whereas `foreach` uses an enumerator, so this is not valid: ``` foreach(var item in someList) if(item.RemoveMe) someList.Remove(item); ``` --- **tl;dr: Do NOT copypaste this code into your application!** These examples aren't best practice, they are just to demonstrate the differences between `ForEach()` and `foreach`. Removing items from a list within a `for` loop can have side effects. The most common one is described in the comments to this question. Generally, if you are looking to remove multiple items from a list, you would want to separate the determination of which items to remove from the actual removal. It doesn't keep your code compact, but it guarantees that you do not miss any items.
225,953
<p>Where can I find a list of all the C# Color constants and the associated R,G,B (Red, Green, Blue) values?</p> <p>e.g.</p> <p>Color.White == (255,255,255)</p> <p>Color.Black == (0,0,0)</p> <p>etc...</p>
[ { "answer_id": 225962, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 3, "selected": false, "text": "<p>It looks like this <a href=\"http://www.flounder.com/csharp_color_table.htm\" rel=\"noreferrer\">page</a> has all of them. </p>\n" }, { "answer_id": 225967, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>Run this program:</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Reflection;\n\npublic class Test\n{\n static void Main()\n {\n var props = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static);\n foreach (PropertyInfo prop in props)\n {\n Color color = (Color) prop.GetValue(null, null);\n Console.WriteLine(\"Color.{0} = ({1}, {2}, {3})\", prop.Name,\n color.R, color.G, color.B);\n }\n }\n}\n</code></pre>\n\n<p>Or alternatively:</p>\n\n<pre><code>using System;\nusing System.Drawing;\n\npublic class Test\n{\n static void Main()\n {\n foreach (KnownColor known in Enum.GetValues(typeof(KnownColor)))\n {\n Color color = Color.FromKnownColor(known);\n Console.WriteLine(\"Color.{0} = ({1}, {2}, {3})\", known,\n color.R, color.G, color.B);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 227104, "author": "Bryan", "author_id": 5423, "author_profile": "https://Stackoverflow.com/users/5423", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx\" rel=\"noreferrer\">MSDN link</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa358802.aspx\" rel=\"noreferrer\">Colors by name/hex via MSDN</a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
Where can I find a list of all the C# Color constants and the associated R,G,B (Red, Green, Blue) values? e.g. Color.White == (255,255,255) Color.Black == (0,0,0) etc...
Run this program: ``` using System; using System.Drawing; using System.Reflection; public class Test { static void Main() { var props = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static); foreach (PropertyInfo prop in props) { Color color = (Color) prop.GetValue(null, null); Console.WriteLine("Color.{0} = ({1}, {2}, {3})", prop.Name, color.R, color.G, color.B); } } } ``` Or alternatively: ``` using System; using System.Drawing; public class Test { static void Main() { foreach (KnownColor known in Enum.GetValues(typeof(KnownColor))) { Color color = Color.FromKnownColor(known); Console.WriteLine("Color.{0} = ({1}, {2}, {3})", known, color.R, color.G, color.B); } } } ```
225,984
<p>I have a partial that renders a select box using the following method:</p> <pre><code>&lt;%= collection_select 'type', 'id', @types, "id", "name", {:prompt =&gt; true}, {:onchange =&gt; remote_function( :loading =&gt; "Form.Element.disable('go_button')", :url =&gt; '/sfc/criteria/services', :with =&gt; "'type_id=' + encodeURIComponent(value) + '&amp;use_wizard=#{use_wizard}'"), :class =&gt; "hosp_select_buttons" } %&gt; </code></pre> <p>This partial gets used 2 times on every page, but at one point I need to get the value of the first select box. Using:</p> <pre><code>$('type_id') </code></pre> <p>returns the second select box. Is there a way to find the first one easily? Should I fix this using javascript or by redoing my partial?</p> <p>Note: the dropdowns do get rendered in separate forms.</p>
[ { "answer_id": 486646, "author": "Shalom Craimer", "author_id": 54491, "author_profile": "https://Stackoverflow.com/users/54491", "pm_score": 2, "selected": false, "text": "<p>As per your \"UPDATE\", creating a custom <code>DataGridViewCell</code> is the way this is done. I've done it, and it doesn't require that much modification from the example code available from the MSDN. In my case, I needed a bunch of custom editing controls, so I ended up inheriting from <code>DataGridViewTextBoxCell</code> and <code>DataGridViewColumn</code>. I inserted into my class (the one inherited from <code>DataGridViewTextBoxCell</code>) a new custom control which implemented <code>IDataGridViewEditingControl</code>, and it all just worked.</p>\n\n<p>I suppose that in your case, you could write a <code>PanelDataGridViewCell</code> which would contain a control <code>MyPanelControl</code> which would inherit from Panel and implement <code>IDataGridViewEditingControl</code>.</p>\n" }, { "answer_id": 881292, "author": "Billy Coover", "author_id": 59017, "author_profile": "https://Stackoverflow.com/users/59017", "pm_score": 2, "selected": false, "text": "<p>Rather than use a datagridview, how about using a TableLayoutPanel instead. Create your control that has a label and a button and events and fill your layout panel with them. Your control becomes the cell so to speak. It doesn't take much to make the table layout panel to look like a datagridview, if that is the layout style you want.</p>\n" }, { "answer_id": 15181258, "author": "Jeremy Thompson", "author_id": 495455, "author_profile": "https://Stackoverflow.com/users/495455", "pm_score": 2, "selected": false, "text": "<p>There are two ways to do this:</p>\n\n<p>1). Cast a DataGridViewCell to a certain cell type that exists. For example, convert a DataGridViewTextBoxCell to DataGridViewComboBoxCell type. </p>\n\n<p>2). Create a control and add it into the controls collection of DataGridView, set its location and size to fit the cell that to be host.</p>\n\n<p>See Zhi-Xin Ye's sample code below which illustrates the tricks:</p>\n\n<pre><code>private void Form_Load(object sender, EventArgs e)\n{\n DataTable dt = new DataTable();\n dt.Columns.Add(\"name\");\n for (int j = 0; j &lt; 10; j++)\n {\n dt.Rows.Add(\"\");\n }\n this.dataGridView1.DataSource = dt;\n this.dataGridView1.Columns[0].Width = 200;\n\n /*\n * First method : Convert to an existed cell type such ComboBox cell,etc\n */\n\n DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();\n ComboBoxCell.Items.AddRange(new string[] { \"aaa\",\"bbb\",\"ccc\" });\n this.dataGridView1[0, 0] = ComboBoxCell;\n this.dataGridView1[0, 0].Value = \"bbb\";\n\n DataGridViewTextBoxCell TextBoxCell = new DataGridViewTextBoxCell();\n this.dataGridView1[0, 1] = TextBoxCell;\n this.dataGridView1[0, 1].Value = \"some text\";\n\n DataGridViewCheckBoxCell CheckBoxCell = new DataGridViewCheckBoxCell();\n CheckBoxCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;\n this.dataGridView1[0, 2] = CheckBoxCell;\n this.dataGridView1[0, 2].Value = true;\n\n /*\n * Second method : Add control to the host in the cell\n */\n DateTimePicker dtp = new DateTimePicker();\n dtp.Value = DateTime.Now.AddDays(-10);\n //add DateTimePicker into the control collection of the DataGridView\n this.dataGridView1.Controls.Add(dtp);\n //set its location and size to fit the cell\n dtp.Location = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Location;\n dtp.Size = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Size;\n}\n</code></pre>\n\n<p><a href=\"http://social.msdn.microsoft.com/forums/en-US/winformsdesigner/thread/63ddb457-f769-44db-87cc-9e88e74929e8/\" rel=\"nofollow noreferrer\">MSDN Reference : how to host different controls in the same column in DataGridView control</a></p>\n\n<p>Using the 1st method looks like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/x9Eco.png\" alt=\"Different Controls in DataGridView Column\"></p>\n\n<p>Using the 2nd method looks like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/DxuoK.png\" alt=\"enter image description here\"></p>\n\n<p>Additional info: <a href=\"https://stackoverflow.com/questions/15238322/controls-in-the-same-datagridview-column-dont-render-while-initializing-grid\">Controls in the same DataGridView column dont render while initializing grid</a></p>\n" }, { "answer_id": 72250348, "author": "Patch", "author_id": 4879042, "author_profile": "https://Stackoverflow.com/users/4879042", "pm_score": 1, "selected": false, "text": "<p>Usually you should host controls in winfors forms datagridview cells as shown <a href=\"https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells?view=netframeworkdesktop-4.8&amp;redirectedfrom=MSDN\" rel=\"nofollow noreferrer\">here</a></p>\n<p>But if you need your control to be always visible, what you can do is make a custom column inheriting from DataGridViewImageColumn. Add the control to the datagridview. Set the DefaultCellStyle.Nullvalue of the control to a bitmap of the control you want always shown on the data gridview. Then using the cellMouseEnter event you can display and reposition the control to display over the image cell. This gives the appearance that your custom control is always visible without using as much resources as creating a new instance of your control for every row added to the datagridview. This will help performance quite a bit.</p>\n<p>Here is what I did with my custom “AddRemove” usercontrol.</p>\n<pre><code>public class AddRemoveColumn : DataGridViewImageColumn\n{\n private AddRemove SelectionControl = null;\n private Bitmap SelectionControlImage = null;\n\n public AddRemoveColumn()\n {\n SelectionControl = new AddRemove();\n }\n\n #region Set Up Column\n protected override void OnDataGridViewChanged()\n {\n base.OnDataGridViewChanged();\n if (DataGridView != null)\n {\n Activate();\n }\n }\n\n private void Activate()\n {\n SelectionControl.LostFocus += SelectionControl_LostFocus;\n this.DataGridView.CellMouseEnter += DataGridView_CellMouseEnter;\n this.DataGridView.BackgroundColorChanged += DataGridView_BackgroundColorChanged;\n\n this.DataGridView.RowHeightChanged += DataGridView_RowHeightChanged;\n SelectionControl.OnAddClicked += AddClicked;\n SelectionControl.OnRemoveClicked += RemoveClicked;\n\n\n this.DataGridView.Controls.Add(SelectionControl);\n SelectionControl.Visible = false;\n\n this.Width = SelectionControl.Width;\n SelectionControl.BackColor = this.DataGridView.BackgroundColor;\n \n this.DataGridView.RowTemplate.Height = SelectionControl.Height +1;\n\n foreach (DataGridViewRow row in DataGridView.Rows)\n {\n row.Height = SelectionControl.Height+1;\n }\n\n SetNullImage();\n }\n #endregion\n\n private void AddClicked(int RowIndex)\n {\n MessageBox.Show(&quot;Add clicked on index=&quot; + RowIndex.ToString());\n }\n\n private void RemoveClicked(int RowIndex)\n {\n MessageBox.Show(&quot;Removed clicked on index=&quot; + RowIndex.ToString());\n }\n\n private void SetNullImage()\n {\n if (SelectionControlImage != null)\n {\n\n SelectionControlImage.Dispose();\n }\n \n SelectionControlImage = new Bitmap(SelectionControl.Width, SelectionControl.Height);\n\n SelectionControl.DrawToBitmap(SelectionControlImage, new Rectangle(0, 0, SelectionControlImage.Width, SelectionControlImage.Height));\n\n this.DefaultCellStyle.NullValue = SelectionControlImage;\n }\n\n private void DataGridView_RowHeightChanged(object sender, DataGridViewRowEventArgs e)\n {\n if (e.Row.Height &lt;= 40)\n {\n e.Row.Height = 40;\n }\n\n SelectionControl.Visible = false;\n SetPosition(Index, e.Row.Index);\n }\n\n private void DataGridView_BackgroundColorChanged(object sender, EventArgs e)\n {\n SelectionControl.BackColor = this.DataGridView.BackgroundColor;\n\n\n SetNullImage();\n\n }\n\n private void SelectionControl_LostFocus(object sender, EventArgs e)\n {\n SelectionControl.Visible = false;\n }\n\n private void SetPosition(int ColumnIndex, int RowIndex)\n {\n Rectangle celrec = this.DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);//.Rows[e.RowIndex].Cells[e.ColumnIndex].GetContentBounds();\n\n int x_Offet = (celrec.Width - SelectionControl.Width)/ 2;\n int y_Offet = (celrec.Height - SelectionControl.Height)/2;\n\n SelectionControl.Location = new Point(celrec.X + x_Offet, celrec.Y + y_Offet);\n SelectionControl.Visible = true;\n SelectionControl.RowIndex = RowIndex;\n }\n\n private void DataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)\n {\n if (e.ColumnIndex == this.Index)\n {\n SetPosition(e.ColumnIndex, e.RowIndex);\n }\n }\n}\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/sGSk1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sGSk1.png\" alt=\"What this looks like\" /></a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/225984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
I have a partial that renders a select box using the following method: ``` <%= collection_select 'type', 'id', @types, "id", "name", {:prompt => true}, {:onchange => remote_function( :loading => "Form.Element.disable('go_button')", :url => '/sfc/criteria/services', :with => "'type_id=' + encodeURIComponent(value) + '&use_wizard=#{use_wizard}'"), :class => "hosp_select_buttons" } %> ``` This partial gets used 2 times on every page, but at one point I need to get the value of the first select box. Using: ``` $('type_id') ``` returns the second select box. Is there a way to find the first one easily? Should I fix this using javascript or by redoing my partial? Note: the dropdowns do get rendered in separate forms.
As per your "UPDATE", creating a custom `DataGridViewCell` is the way this is done. I've done it, and it doesn't require that much modification from the example code available from the MSDN. In my case, I needed a bunch of custom editing controls, so I ended up inheriting from `DataGridViewTextBoxCell` and `DataGridViewColumn`. I inserted into my class (the one inherited from `DataGridViewTextBoxCell`) a new custom control which implemented `IDataGridViewEditingControl`, and it all just worked. I suppose that in your case, you could write a `PanelDataGridViewCell` which would contain a control `MyPanelControl` which would inherit from Panel and implement `IDataGridViewEditingControl`.
226,002
<p>Have you ever tried this before?</p> <pre><code>static void Main(string[] args) { int x = 10; x = x++; Console.WriteLine(x); } </code></pre> <p>Output: 10.</p> <p>but for </p> <pre><code>static void Main(string[] args) { int x = 10; x++; Console.WriteLine(x); } </code></pre> <p>Output: 11.</p> <p>Could anyone explain why this?</p>
[ { "answer_id": 226008, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<p>X++ will increment the value, but then return its old value. </p>\n\n<p>So in this case:</p>\n\n<pre><code>static void Main(string[] args)\n{\n int x = 10;\n x = x++;\n Console.WriteLine(x);\n}\n</code></pre>\n\n<p>You have X at 11 just for a moment, then it gets back to 10 because 10 is the return value of (x++). </p>\n\n<p>You could instead do this for the same result:</p>\n\n<pre><code>static int plusplus(ref int x)\n{\n int xOld = x;\n x++;\n return xOld;\n}\n\nstatic void Main(string[] args)\n{\n int x = 10;\n x = plusplus(x);\n Console.WriteLine(x);\n}\n</code></pre>\n\n<p>It is also worth mentioning that you would have your expected result of 11 if you would have done:</p>\n\n<pre><code>static void Main(string[] args)\n{\n int x = 10;\n x = ++x;\n Console.WriteLine(x);\n}\n</code></pre>\n" }, { "answer_id": 226019, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "<p>In the assignment <code>x = x++</code> you <em>first</em> extract the old value of <code>x</code> to use in evaluating the right-hand side expression, in this case 'x'; then, you increment <code>x</code> by 1. Last, you assign the results of the expression evaluation (10) to <code>x</code> via the assignment statement.</p>\n\n<p>Perhaps an equivalent code would make the predicament clear:</p>\n\n<pre><code>var tmp = x;\nx++;\nx = tmp;\n</code></pre>\n\n<p>This is the equivalent of your <code>x = x++</code> code in C#.</p>\n" }, { "answer_id": 226021, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 4, "selected": false, "text": "<p>The behaviour of x++ is to increment x but return the value <strong>before</strong> the increment. Its called a post increment for this reason.</p>\n\n<p>So x = x++; simply put will </p>\n\n<p><strong>1. return the value</strong>, then </p>\n\n<p><strong>2. increment x</strong>, then </p>\n\n<p><strong>3. assign the original value(returned in step 1) of x to x</strong>.</p>\n" }, { "answer_id": 226024, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 4, "selected": false, "text": "<pre><code>x = 10\nx = ++x \n</code></pre>\n\n<p><code>x</code> would end up equalling 11.</p>\n" }, { "answer_id": 226033, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "<pre><code>x++;\n</code></pre>\n\n<p>does the following:</p>\n\n<pre><code>int returnValue = x;\nx = x+1;\nreturn returnValue;\n</code></pre>\n\n<p>As you can see, the original value is saved, x is incremented, and then the original value is returned.</p>\n\n<p>What this ends up doing is saving the value 10 somewhere, setting x equal to 11, and then returning 10, which causes x to be set back to 10. Note that x does actually become 11 for a few cycles (assuming no compiler optimization).</p>\n" }, { "answer_id": 226036, "author": "Sundar R", "author_id": 8127, "author_profile": "https://Stackoverflow.com/users/8127", "pm_score": -1, "selected": false, "text": "<p>The result of the assignment</p>\n\n<pre><code>x = x++;\n</code></pre>\n\n<p>is undefined in C and C++<s>, and I would guess the same with C# too. </p>\n\n<p>So, the actual sequence of operations that occurs depends on how the compiler decides to implements it, there's no guarantee whether the assignment or the increment will occur first. \n</s> (this is well defined in C#, as Jon Skeet has pointed out in the comments. Though I now feel this answer is of much less value now, I'm keeping this post undeleted for the OP's question and its answer in the comments.)</p>\n\n<p>However, in this case, it appears the sequence of operations that happens is:</p>\n\n<ol>\n<li>the old value (10) of x is saved</li>\n<li>x is incremented for the ++ part</li>\n<li>the old value is now assigned to x for the assignment </li>\n</ol>\n\n<p>In this way, though the increment occurs, it is overtaken by the assignment with old value, thus keeping x at 10. </p>\n\n<p>HTH</p>\n" }, { "answer_id": 226301, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 2, "selected": false, "text": "<p>You can think of it like this:</p>\n\n<pre><code>int x = 10;\n</code></pre>\n\n<p>X is a container, and contains a value, 10.</p>\n\n<pre><code>x = x++;\n</code></pre>\n\n<p>This can be broken down to:</p>\n\n<pre><code>1) increment the value contained in x \n now x contains 11\n\n2) return the value that was contained in x before it was incremented\n that is 10\n\n3) assign that value to x\n now, x contains 10\n</code></pre>\n\n<p>Now, print the value contained in x</p>\n\n<pre><code>Console.WriteLine(x);\n</code></pre>\n\n<p>And, unsurprisingly, it prints out 10.</p>\n" }, { "answer_id": 227181, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Putting the increment operator after the variable means that the increment and assignment happens <em>after</em> the expression is evaluated... so\nThe original statement \nx = x++;\ntranslates to\n1. Evaluate x and store value in tyransient memory\n ... Now execute code called for by ++ operator .... (steps 2 &amp; 3)\n2. Increment value of x (in transient memory)\n3. Assign Incremented value to x's storage location \n ... Now, continue with rest of the line's execution, to the left, there's an = sign...\n5. So assign value stored in Step 1 (unincremented value) to expression on left of = sign... which is x</p>\n" }, { "answer_id": 4896976, "author": "Max ", "author_id": 602981, "author_profile": "https://Stackoverflow.com/users/602981", "pm_score": 1, "selected": false, "text": "<p>The first thing you do is called \"post-increment\" meaning that</p>\n\n<pre><code> int x = 10;\n x++; //x still is 10\n Console.WriteLine(x); //x is now 11(post increment)\n</code></pre>\n\n<p>so the moment you assign x = x++; x still is 10 what you could do, if you need x to be 11 at this line write ++x (think its called pre increment correct me if im wrong) ... alternatively right x++; and than x = x++;</p>\n\n<p>question, is it dependend on the line or on statement meaning that it will increment after the ; ?</p>\n" }, { "answer_id": 39062137, "author": "vitaliy4us", "author_id": 5740380, "author_profile": "https://Stackoverflow.com/users/5740380", "pm_score": 0, "selected": false, "text": "<p>Maybe I am not right, but it's easier for me to understand the result on a similar example:</p>\n\n<pre><code>public static void main(String[] args) {\n int x = 10;\n int y = 0;\n y = x + x++; //1, 2, 3, 4\n x += x; //5\n System.out.println(\"x = \" + x + \"; y = \" + y); //6\n}\n</code></pre>\n\n<p>Let's take a look at operation y = x + x++ step by step:</p>\n\n<ol>\n<li>A computer takes the value of x and add it to value of x (10 + 10 = 20)</li>\n<li>The computer PUTS THE RESULT TO A TEMPORARY VARIABLE (temp = 20)</li>\n<li>The coputer increments x (10 + 1 = 11)</li>\n<li>The computer ASSIGNS THE RUSULT OF THE RIGHT SIDE OPERATION STORED IN temp to variable y (20)</li>\n<li>A computer takes the value of x and add it to value of x (11 + 11 = 22)</li>\n<li>The final result is: x = 22; y = 20</li>\n</ol>\n\n<p>And now let's return to the our example and make the same steps:</p>\n\n<pre><code>public static void main(String[] args) {\n int x = 10;\n x = x++; //1, 2, 3, 4\n System.out.println(x); //5\n}\n</code></pre>\n\n<ol>\n<li>A computer takes the value of x (10)</li>\n<li>The computer PUTS THE RESULT TO A TEMPORARY VARIABLE (temp = 10)</li>\n<li>The coputer increments x (10 + 1 = 11)</li>\n<li>The computer ASSIGNS THE RUSULT OF THE RIGHT SIDE OPERATION STORED IN temp to variable x (10)</li>\n<li>The final result is: x = 10</li>\n</ol>\n" }, { "answer_id": 47232964, "author": "galois", "author_id": 2005732, "author_profile": "https://Stackoverflow.com/users/2005732", "pm_score": 1, "selected": false, "text": "<p>I know there are a lot of answers, and an accepted one, but I'll still put in my two cents for yet another point of view.</p>\n\n<p>I know this question was C#, but I assume that for something like a postfix operator it doesn't have different behavior than C:</p>\n\n<pre><code>int main(){\n int x = 0;\n while (x&lt;1)\n x = x++;\n}\n</code></pre>\n\n<p>The assembly (yes, I edited it to make it more readable) generated by the compiler shows </p>\n\n<pre><code>...\n mov -8(rbp), 0 ; x = 0\nL1:\n cmp -8(rbp), 1 ; if x &gt;= 1,\n jge L2 ; leave the loop\n mov eax, -8(rbp) ; t1 = x\n mov ecx, eax ; t2 = t1\n add ecx, 1 ; t2 = t2 + 1\n mov -8(rbp), ecx ; x = t2 (so x = x + 1 !)\n mov -8(rbp), eax ; x = t1 (kidding, it's the original value again)\n jmp L1\nL2:\n...\n</code></pre>\n\n<p>Equivalently, the loop is doing something like:</p>\n\n<pre><code>t = x\nx = x + 1\nx = t\n</code></pre>\n\n<p>Side note: turning on any optimizations gives you some assembly result like this:</p>\n\n<pre><code>...\nL1:\n jmp L1\n...\n</code></pre>\n\n<p>it doesn't even bother to store the value you told it to give x!</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14118/" ]
Have you ever tried this before? ``` static void Main(string[] args) { int x = 10; x = x++; Console.WriteLine(x); } ``` Output: 10. but for ``` static void Main(string[] args) { int x = 10; x++; Console.WriteLine(x); } ``` Output: 11. Could anyone explain why this?
X++ will increment the value, but then return its old value. So in this case: ``` static void Main(string[] args) { int x = 10; x = x++; Console.WriteLine(x); } ``` You have X at 11 just for a moment, then it gets back to 10 because 10 is the return value of (x++). You could instead do this for the same result: ``` static int plusplus(ref int x) { int xOld = x; x++; return xOld; } static void Main(string[] args) { int x = 10; x = plusplus(x); Console.WriteLine(x); } ``` It is also worth mentioning that you would have your expected result of 11 if you would have done: ``` static void Main(string[] args) { int x = 10; x = ++x; Console.WriteLine(x); } ```
226,042
<p>As part of our build process we run a database update script as we deploy code to 4 different environments. Further, since the same query will get added to until we drop a release into production it <em>has</em> to be able to run multiple times on a given database. Like this:</p> <pre><code>IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[Table]')) BEGIN CREATE TABLE [Table] (...) END </code></pre> <p>Currently I have a create schema statement in the deployment/build script. Where do I query for the existence of a schema?</p>
[ { "answer_id": 226054, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 9, "selected": true, "text": "<p>Are you looking for <a href=\"http://msdn.microsoft.com/en-us/library/ms176011.aspx\" rel=\"noreferrer\">sys.schemas</a>?</p>\n\n<pre><code>IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'jim')\nBEGIN\nEXEC('CREATE SCHEMA jim')\nEND\n</code></pre>\n\n<p>Note that the <code>CREATE SCHEMA</code> must be run in its own batch (per <a href=\"https://stackoverflow.com/a/521271/2688\">the answer below</a>)</p>\n" }, { "answer_id": 521271, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 7, "selected": false, "text": "<p>@bdukes is right on the money for determining if the schema exists, but the statement above won't work in SQL Server 2005. <code>CREATE SCHEMA &lt;name&gt;</code> needs to run in its own batch. A work around is to execute the <code>CREATE SCHEMA</code> statement in an exec. </p>\n\n<p>Here is what I used in my build scripts:</p>\n\n<pre><code>IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = '&lt;name&gt;')\nBEGIN\n -- The schema must be run in its own batch!\n EXEC( 'CREATE SCHEMA &lt;name&gt;' );\nEND\n</code></pre>\n" }, { "answer_id": 44707980, "author": "Tom", "author_id": 401246, "author_profile": "https://Stackoverflow.com/users/401246", "pm_score": 1, "selected": false, "text": "<p>Just to be <em>extra</em> \"defensive\", the following version generates a Type conversion error to account for the possibility (however unlikely) of > 1 matching <code>Schema</code>'s similar to how validation code often intentionally Throw Exception's because I believe it's good to and I believe it's \"'best practice'\" to account for all possible return results however unlikely and even if it's just to generate a fatal exception because the known effects of stopping processing is usually better than unknown cascading effects of un-trapped errors. Because it's highly unlikely, I didn't think it's worth the trouble of a separate <code>Count</code> check + <code>Throw</code> or <code>Try</code>-<code>Catch</code>-<code>Throw</code> to generate a more user-friendly fatal error but still fatal error nonetheless.</p>\n\n<p>SS 2005-: </p>\n\n<pre><code>declare @HasSchemaX bit\nset @HasSchemaX = case (select count(1) from sys.schemas where lower(name) = lower('SchemaX')) when 1 then 1 when 0 then 0 else 'ERROR' end\n</code></pre>\n\n<p>SS 2008+: </p>\n\n<pre><code>declare @HasSchemaX bit = case (select count(1) from sys.schemas where lower(name) = lower('SchemaX')) when 1 then 1 when 0 then 0 else 'ERROR' end\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>if @HasSchemaX = 1\nbegin\n ...\nend -- if @HasSchemaX = 1\n</code></pre>\n" }, { "answer_id": 55190129, "author": "Mark Schultheiss", "author_id": 125981, "author_profile": "https://Stackoverflow.com/users/125981", "pm_score": 3, "selected": false, "text": "<p>This is old so I feel compelled to add: For SQL SERVER 2008+ These all work (for the select part), then use <code>EXECUTE('CREATE SCHEMA &lt;name&gt;')</code> to actually create it on negative results.</p>\n\n<pre><code>DECLARE @schemaName sysname = 'myfunschema';\n-- shortest\nIf EXISTS (SELECT 1 WHERE SCHEMA_ID(@schemaName) IS NOT NULL)\nPRINT 'YEA'\nELSE\nPRINT 'NOPE'\n\nSELECT DB_NAME() AS dbname WHERE SCHEMA_ID(@schemaName) IS NOT NULL -- nothing returned if not there\n\nIF NOT EXISTS ( SELECT top 1 *\n FROM sys.schemas\n WHERE name = @schemaName )\nPRINT 'WOOPS MISSING'\nELSE\nPRINT 'Has Schema'\n\nSELECT SCHEMA_NAME(SCHEMA_ID(@schemaName)) AS SchemaName1 -- null if not there otherwise schema name returned\n\nSELECT SCHEMA_ID(@schemaName) AS SchemaID1-- null if not there otherwise schema id returned\n\n\nIF EXISTS (\n SELECT sd.SchemaExists \n FROM (\n SELECT \n CASE \n WHEN SCHEMA_ID(@schemaName) IS NULL THEN 0\n WHEN SCHEMA_ID(@schemaName) IS NOT NULL THEN 1\n ELSE 0 \n END AS SchemaExists\n ) AS sd\n WHERE sd.SchemaExists = 1\n)\nBEGIN\n SELECT 'Got it';\nEND\nELSE\nBEGIN\n SELECT 'Schema Missing';\nEND\n</code></pre>\n" }, { "answer_id": 59671784, "author": "benik9", "author_id": 5919321, "author_profile": "https://Stackoverflow.com/users/5919321", "pm_score": 2, "selected": false, "text": "<p>If the layout of components allows it, this works too. </p>\n\n<pre>\nIF EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'myschema') SET NOEXEC ON \ngo\nCREATE SCHEMA myschema\nGO \nSET NOEXEC OFF -- if any further processing is needed.\nGO\n</pre>\n" }, { "answer_id": 72300881, "author": "Mohammad Sadeq Sirjani", "author_id": 11507996, "author_profile": "https://Stackoverflow.com/users/11507996", "pm_score": 0, "selected": false, "text": "<pre><code>IF NOT EXISTS (SELECT TOP (1) 1 FROM [sys].[schemas] WHERE [name] = 'Person')\nBEGIN\n EXEC ('CREATE SCHEMA [Person]')\nEND\n\nIF NOT EXISTS (SELECT TOP (1) 1 FROM [sys].[tables] AS T\n INNER JOIN [sys].[schemas] AS S ON S.schema_id = T.schema_id\n WHERE T.[name] = 'Guests' AND S.[name] = 'Person')\nBEGIN\n EXEC ('CREATE TABLE [Person].[Guests]\n (\n [GuestId] INT IDENTITY(1, 1) NOT NULL,\n [Forename] NVARCHAR(100) NOT NULL,\n [Surname] NVARCHAR(100) NOT NULL,\n [Email] VARCHAR(255) NOT NULL,\n [BirthDate] DATETIME2 NULL,\n CONSTRAINT [PK_Guests_GuestId] PRIMARY KEY CLUSTERED ([GuestId]),\n CONSTRAINT [UX_Guests_Email] UNIQUE([Email])\n )')\nEND\n</code></pre>\n<p>NOTICE: <code>CREATE SCHEMA</code> AND <code>CREATE TABLE</code> NEED COMPLETLY SEPARATED BATCH TO EXECUTE</p>\n<p>TO MORE DESCRIPTION VISIT MICROSOFT DOCS WEBSITE :)</p>\n" }, { "answer_id": 72974092, "author": "David Sopko", "author_id": 1197553, "author_profile": "https://Stackoverflow.com/users/1197553", "pm_score": 0, "selected": false, "text": "<p>As of SQL Server 2005 version 9.0 you can use the INFORMATION_SCHEMA.SCHEMATA view to check if the schema exists:</p>\n<pre><code>IF NOT EXISTS (\nSELECT SCHEMA_NAME\nFROM INFORMATION_SCHEMA.SCHEMATA\nWHERE SCHEMA_NAME = '&lt;schema name&gt;' )\n \nBEGIN\n EXEC sp_executesql N'CREATE SCHEMA &lt;schema name&gt;' \nEND\nGO\n</code></pre>\n<p>INFORMATION_SCHEMA views are the ISO standard and are generally preferable; these were adopted to make the syntax more consistent across different SQL database platforms.</p>\n<p>Note that the CREATE SCHEMA must be run in its own batch</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156/" ]
As part of our build process we run a database update script as we deploy code to 4 different environments. Further, since the same query will get added to until we drop a release into production it *has* to be able to run multiple times on a given database. Like this: ``` IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[Table]')) BEGIN CREATE TABLE [Table] (...) END ``` Currently I have a create schema statement in the deployment/build script. Where do I query for the existence of a schema?
Are you looking for [sys.schemas](http://msdn.microsoft.com/en-us/library/ms176011.aspx)? ``` IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'jim') BEGIN EXEC('CREATE SCHEMA jim') END ``` Note that the `CREATE SCHEMA` must be run in its own batch (per [the answer below](https://stackoverflow.com/a/521271/2688))
226,050
<p>I am trying to use <code>ResourceBundle#getStringArray</code> to retrieve a <code>String[]</code> from a properties file. The description of this method in the documentation reads:</p> <blockquote> <p>Gets a string array for the given key from this resource bundle or one of its parents.</p> </blockquote> <p>However, I have attempted to store the values in the properties file as multiple individual key/value pairs:</p> <pre><code>key=value1 key=value2 key=value3 </code></pre> <p>and as a comma-delimited list:</p> <pre><code>key=value1,value2,value3 </code></pre> <p>but neither of these is retrievable using <code>ResourceBundle#getStringArray</code>.</p> <p>How do you represent a set of key/value pairs in a properties file such that they can be retrieved using <code>ResourceBundle#getStringArray</code>?</p>
[ { "answer_id": 226142, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 3, "selected": false, "text": "<p>Umm, looks like this is a common problem, from threads <a href=\"http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&amp;f=33&amp;t=014772\" rel=\"noreferrer\">here</a> and <a href=\"http://www.theserverside.com/discussions/thread.tss?thread_id=15426\" rel=\"noreferrer\">here</a>.</p>\n\n<p>It seems either you don't use the method and parse the value for an array yourself or you write your own ResourceBundle implementation and do it yourself :(. Maybe there is an apache commons project for this... </p>\n\n<p>From the JDK source code, it seems the PropertyResourceBundle does not support it.</p>\n" }, { "answer_id": 226160, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 6, "selected": true, "text": "<p>A <code>Properties</code> object can hold <strong><code>Object</code>s</strong>, not just <code>String</code>s. That tends to be forgotten because they're overwhelmingly used to load .properties files, and so often will only contain <code>String</code>s. <a href=\"https://web.archive.org/web/20081217073139/http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html#getStringArray(java.lang.String)\" rel=\"nofollow noreferrer\">The documentation</a> indicates that calling <code>bundle.getStringArray(key)</code> is equivalent to calling <code>(String[]) bundle.getObject(key)</code>. That's the problem: the value isn't a <code>String[]</code>, it's a <code>String</code>.</p>\n\n<p>I'd suggest storing it in comma-delimited format and calling <code>split()</code> on the value.</p>\n" }, { "answer_id": 226177, "author": "Alan Krueger", "author_id": 7708, "author_profile": "https://Stackoverflow.com/users/7708", "pm_score": 2, "selected": false, "text": "<p>I don't believe this is possible with ResourceBundles loaded from a properties file. The PropertyResourceBundle leverages the Properties class to load the properties file. The Properties class loads a properties file as a set of String->String map entries and doesn't support pulling out String[] values.</p>\n\n<p>Calling ResourceBundle.getStringArray just calls ResourceBundle.getObject, casting the result to a String[]. Since the PropertyResourceBundle just hands this off to the Properties instance it loaded from the file, you'll never be able to get this to work with the current, stock PropertyResourceBundle.</p>\n" }, { "answer_id": 229338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>public String[] getPropertyStringArray(PropertyResourceBundle bundle, String keyPrefix) {\n String[] result;\n Enumeration&lt;String&gt; keys = bundle.getKeys();\n ArrayList&lt;String&gt; temp = new ArrayList&lt;String&gt;();\n\n for (Enumeration&lt;String&gt; e = keys; keys.hasMoreElements();) {\n String key = e.nextElement();\n if (key.startsWith(keyPrefix)) {\n temp.add(key);\n }\n }\n result = new String[temp.size()];\n\n for (int i = 0; i &lt; temp.size(); i++) {\n result[i] = bundle.getString(temp.get(i));\n }\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 1291284, "author": "João Silva", "author_id": 140816, "author_profile": "https://Stackoverflow.com/users/140816", "pm_score": 3, "selected": false, "text": "<p>You can use <a href=\"http://commons.apache.org/proper/commons-configuration/userguide/howto_properties.html\" rel=\"nofollow noreferrer\">Commons Configuration</a>, which has methods <code>getList</code> and <code>getStringArray</code> that allow you to retrieve a list of comma separated strings.</p>\n" }, { "answer_id": 14691389, "author": "Murlo", "author_id": 2040338, "author_profile": "https://Stackoverflow.com/users/2040338", "pm_score": 1, "selected": false, "text": "<p>example:</p>\n\n<pre><code>[email protected], [email protected]\n</code></pre>\n\n<p>..</p>\n\n<pre><code>myBundle=PropertyResourceBundle.getBundle(\"mailTemplates/bundle-name\", _locale);\n</code></pre>\n\n<p>..</p>\n\n<pre><code>public List&lt;String&gt; getCcEmailAddresses() \n{\n List&lt;String&gt; ccEmailAddresses=new ArrayList&lt;String&gt;();\n if(this.myBundle.containsKey(\"mail.ccEmailAddresses\"))\n {\n ccEmailAddresses.addAll(Arrays.asList(this.template.getString(\"mail.ccEmailAddresses\").split(\"\\\\s*(,|\\\\s)\\\\s*\")));// 1)Zero or more whitespaces (\\\\s*) 2) comma, or whitespace (,|\\\\s) 3) Zero or more whitespaces (\\\\s*)\n } \n return ccEmailAddresses;\n}\n</code></pre>\n" }, { "answer_id": 27667910, "author": "Lokesh Garg", "author_id": 3991465, "author_profile": "https://Stackoverflow.com/users/3991465", "pm_score": 1, "selected": false, "text": "<p>I have tried this and could find a way.\nOne way is to define a subclass of ListresourceBundle, then define instance variable of type String[]\nand assign the value to the key.. here is the code</p>\n\n<pre><code>@Override\nprotected Object[][] getContents() {\n // TODO Auto-generated method stub\n\n String[] str1 = {\"L1\",\"L2\"};\n\n return new Object[][]{\n\n {\"name\",str1},\n {\"country\",\"UK\"} \n };\n}\n</code></pre>\n" }, { "answer_id": 29901682, "author": "chrismarx", "author_id": 228369, "author_profile": "https://Stackoverflow.com/users/228369", "pm_score": 1, "selected": false, "text": "<p>just use spring - <a href=\"https://stackoverflow.com/questions/6212898/spring-properties-file-get-element-as-an-array\">Spring .properties file: get element as an Array</a></p>\n\n<p>relevant code:</p>\n\n<pre><code>base.module.elementToSearch=1,2,3,4,5,6\n\n@Value(\"${base.module.elementToSearch}\")\n private String[] elementToSearch;\n</code></pre>\n" }, { "answer_id": 30181278, "author": "Sujith", "author_id": 2327123, "author_profile": "https://Stackoverflow.com/users/2327123", "pm_score": -1, "selected": false, "text": "<pre><code>key=value1;value2;value3\n\nString[] toArray = rs.getString(\"key\").split(\";\");\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9254/" ]
I am trying to use `ResourceBundle#getStringArray` to retrieve a `String[]` from a properties file. The description of this method in the documentation reads: > > Gets a string array for the given key from this resource bundle or one of its parents. > > > However, I have attempted to store the values in the properties file as multiple individual key/value pairs: ``` key=value1 key=value2 key=value3 ``` and as a comma-delimited list: ``` key=value1,value2,value3 ``` but neither of these is retrievable using `ResourceBundle#getStringArray`. How do you represent a set of key/value pairs in a properties file such that they can be retrieved using `ResourceBundle#getStringArray`?
A `Properties` object can hold **`Object`s**, not just `String`s. That tends to be forgotten because they're overwhelmingly used to load .properties files, and so often will only contain `String`s. [The documentation](https://web.archive.org/web/20081217073139/http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html#getStringArray(java.lang.String)) indicates that calling `bundle.getStringArray(key)` is equivalent to calling `(String[]) bundle.getObject(key)`. That's the problem: the value isn't a `String[]`, it's a `String`. I'd suggest storing it in comma-delimited format and calling `split()` on the value.
226,064
<p>How do I load a true color image into a CImageList?</p> <p>Right now I have</p> <pre><code>mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255)); </code></pre> <p>Where <code>IDB_IMGLIST_BGTASK</code> is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the resource to load from.</p>
[ { "answer_id": 226104, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 4, "selected": true, "text": "<p>Needs 4 lines of code, but this works:</p>\n\n<pre><code>CBitmap bm;\nbm.LoadBitmap(IDB_IMGLIST_BGTASK);\nmImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4);\nmImageList.Add(&amp;bm, RGB(255,0,255));\n</code></pre>\n" }, { "answer_id": 226114, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 1, "selected": false, "text": "<pre><code>CImageList::Create(int cx, int cy, UINT nFlags, int nInitial, int nGrow)\n</code></pre>\n\n<p>allows to specify different flags with the <code>nFlags</code> parameter. You can try to use something like <code>ILC_COLOR32 | ILC_MASK</code>.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
How do I load a true color image into a CImageList? Right now I have ``` mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255)); ``` Where `IDB_IMGLIST_BGTASK` is a 64x16 True color image. The ClistCtrl I am using it in shows 16 bpp color. I don't see a Create overload that allows me to specify both the bpp and the resource to load from.
Needs 4 lines of code, but this works: ``` CBitmap bm; bm.LoadBitmap(IDB_IMGLIST_BGTASK); mImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4); mImageList.Add(&bm, RGB(255,0,255)); ```
226,071
<p>I have the HTML given below:</p> <pre><code>&lt;ul id="thumbsPhotos"&gt; &lt;li src="/images/1alvaston-hall-relaxing-lg.jpg" onclick="updatePhoto (this.title)"&gt;&lt;img src="/images/1alvaston-hall-relaxing-sl.jpg" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" src=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" src=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now, I want to replace all the <code>src</code> in <code>&lt;li&gt;</code> tags not in <code>&lt;img&gt;</code> tags using <code>InnerHTML</code>. With this, my output will be:</p> <pre><code>&lt;ul id="thumbsPhotos"&gt; &lt;li title="/images/1alvaston-hall-relaxing-lg.jpg" onclick="updatePhoto(this.title)"&gt;&lt;img src="/images/1alvaston-hall-relaxing-sl.jpg" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" title=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;li onclick="updatePhoto(this.title)" title=""&gt;&lt;img src="" width="56" height="56"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
[ { "answer_id": 226098, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>You could most likely use a RegEx replace that matches on the src attribute and do the conversion. I see that you want to also add the title attribute even if there is no match, that should be possible as well.</p>\n\n<p>I'll try to dig up some RegEx examples for this.</p>\n" }, { "answer_id": 226099, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>Not an answer, but that is not a very semantic way to do things. Where is this coming from? Why is there ever a src on the li element?</p>\n\n<p>Assuming you want a javascript option, you could use something like jquery to do:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"li[src], li[src='']\").each(function() {\n var li = $(this);\n li.attr(\"title\", li.attr(\"src\"));\n li.removeAttr(\"src\");\n });\n});\n</code></pre>\n" }, { "answer_id": 226100, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 3, "selected": true, "text": "<p>Not tested, but here's a regex which might do it for you...</p>\n\n<pre><code>// find:\n&lt;li ([^&gt;]*)src=\"(.*?)\"(.*?)&gt;\n\n// replace:\n&lt;li $1title=\"$2\"$3&gt;\n</code></pre>\n\n<p><strong>Update</strong>: tested and it works on your example.</p>\n\n<p>If you wanted to run this on the client side using Javascript (for whatever whacky reason), you could do this:</p>\n\n<pre><code>var ul = document.getElementById(\"thumbsPhotos\");\nul.innerHTML = ul.innerHTML.replace(\n /&lt;li ([^&gt;]*)src=\"(.*?)\"(.*?)&gt;/g,\n '&lt;li $1title=\"$2\"$3&gt;'\n);\n</code></pre>\n" }, { "answer_id": 226146, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 0, "selected": false, "text": "<p>If you need to do this once wouldn't just find and replace work?</p>\n\n<p>Otherwise I agree that a regex is the best option.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30394/" ]
I have the HTML given below: ``` <ul id="thumbsPhotos"> <li src="/images/1alvaston-hall-relaxing-lg.jpg" onclick="updatePhoto (this.title)"><img src="/images/1alvaston-hall-relaxing-sl.jpg" width="56" height="56"></li> <li onclick="updatePhoto(this.title)" src=""><img src="" width="56" height="56"></li> <li onclick="updatePhoto(this.title)" src=""><img src="" width="56" height="56"></li> </ul> ``` Now, I want to replace all the `src` in `<li>` tags not in `<img>` tags using `InnerHTML`. With this, my output will be: ``` <ul id="thumbsPhotos"> <li title="/images/1alvaston-hall-relaxing-lg.jpg" onclick="updatePhoto(this.title)"><img src="/images/1alvaston-hall-relaxing-sl.jpg" width="56" height="56"></li> <li onclick="updatePhoto(this.title)" title=""><img src="" width="56" height="56"></li> <li onclick="updatePhoto(this.title)" title=""><img src="" width="56" height="56"></li> </ul> ```
Not tested, but here's a regex which might do it for you... ``` // find: <li ([^>]*)src="(.*?)"(.*?)> // replace: <li $1title="$2"$3> ``` **Update**: tested and it works on your example. If you wanted to run this on the client side using Javascript (for whatever whacky reason), you could do this: ``` var ul = document.getElementById("thumbsPhotos"); ul.innerHTML = ul.innerHTML.replace( /<li ([^>]*)src="(.*?)"(.*?)>/g, '<li $1title="$2"$3>' ); ```
226,088
<p>My predicament is fairly simple: This function gets the <code>id</code> of 'this' <code>&lt;li&gt;</code> element based on parent <code>id</code> of <code>&lt;ul&gt;</code>. It used to work fine but not any more, I will either need to have <code>&lt;ul&gt;</code> use <code>class</code>es instead of <code>id</code> while still being able to assign <code>id</code> of 'current' to the current element, or change my css.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction(element) { liArray = document.getElementById("leftlist").childNodes; i = 0; while (liArray[i]) { liArray[i].id = ""; i++; } element.id = "current"; // or element.className ? }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul#leftlist { background-color: rgb(205, 205, 205); } ul#leftlist li#current a { color: rgb(96, 176, 255); background-color: 218, 218, 218); } ul#leftlist li a { color: rgb(86, 86, 86); } #leftlist a:link { color: rgb(86, 86, 86); background-color: #ddd; } #leftlist a:active { color: rgb(96, 176, 255); background-color: rgb(218, 218, 218); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul id="leftlist"&gt; &lt;li onClick='myFunction(this);'&gt; &lt;a href="123" bla bla &lt;/a&gt;&lt;/li&gt; &lt;li onClick='myFunction(this);'&gt; .... etc.&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>Perhaps I need to change my css. This worked before but now the current <code>id</code> is not being effective as <code>ul#leftlist li a</code> takes priority even when i assign <code>id="current"</code> via JavaScript.</p>
[ { "answer_id": 226181, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 1, "selected": false, "text": "<p>I'd suggest you using the jQuery framework. It will provide a nice abstraction over your DOM and make it way easier for you to find objects in your DOM and assign events to those objects.</p>\n\n<p>Try reading <a href=\"http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery\" rel=\"nofollow noreferrer\">this tutorial</a> over at <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">jQuery.com</a>. I am sure it will amaze you :)</p>\n" }, { "answer_id": 226186, "author": "Erlend Halvorsen", "author_id": 1920, "author_profile": "https://Stackoverflow.com/users/1920", "pm_score": 2, "selected": false, "text": "<p>You should use classes for things like \"current\", not the id. The id normally shouldn't change, and \"current\" isn't a very good id, as you could have a bunch of things on a page that is \"current\" in some way. If you need some css style to override another, you can force it with !important:</p>\n\n<pre><code>ul#leftlist li.current a {\n color: rgb(96,176,255) !important;\n background-color:218,218,218) !important;\n}\n</code></pre>\n" }, { "answer_id": 226202, "author": "Matt", "author_id": 29228, "author_profile": "https://Stackoverflow.com/users/29228", "pm_score": 0, "selected": false, "text": "<p>It looks like you do need to change one line in your css:</p>\n\n<pre><code>ul#leftlist li#current a{color: rgb(96,176,255); background-color:218,218,218);}\n</code></pre>\n\n<p>It's missing the <code>rgb(</code> after <code>background-color</code> and should look like:</p>\n\n<pre><code>ul#leftlist li#current a{color: rgb(96,176,255); background-color: rgb(218,218,218);}\n</code></pre>\n\n<p>I'd also agree with Erlend, <code>current</code> would be better suited to a class.</p>\n" }, { "answer_id": 226207, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 0, "selected": false, "text": "<p>The function changes to:</p>\n\n<pre><code>function myFunction(element){\n var liArray = document.getElementById(\"leftlist\").childNodes;\n var i=0, item;\n while (item = liArray[i++]) {\n if (item.nodeType === 1) {\n item.className = item.className.replace(/(^| )current( |$)/g, '');\n }\n }\n element.className += \" current\";\n}\n</code></pre>\n\n<p>The CSS needs a change to class as well:</p>\n\n<pre><code>ul#leftlist li.current a { ... }\n</code></pre>\n" }, { "answer_id": 226217, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p>Do you do your change in a way, so that you end up with more than one element having the same id ?-)</p>\n\n<p>That is clearly against the whole idea, using id's they have to be totally unique within the context of the html-document ...</p>\n\n<p>-- the first thing, you ought to do is to be sure you only address your li-elements:</p>\n\n<pre><code>liArray=element.parentNode.getElementsByTagName(\"li\");\n</code></pre>\n\n<p>Secondly it could be an idea, to ensure higher priority for one of your selectors by setting something more in the selector:</p>\n\n<p>Highest priority is gained, if you use an inline style-attribute on the tag, but this doesn't seem to be of any use here.</p>\n\n<p>IDs give a high priority, class give a fair priority and element- and pseudo-selectors give a low priority ...</p>\n\n<p>However each type of priority is accumulated and in that way you can give one selector very high priority by preceding it with another of same priority-type:</p>\n\n<p><code>ul#leftlist</code> gives 1 point in high priority and 1 point in low priority</p>\n\n<p><code>#myParent ul#leftlist</code> gives 2 points in high priority and 1 in low</p>\n\n<p><code>.myParent ul#leftlist</code> gives 1 points in high priority, 1 point in fair priority and 1 point in low priority </p>\n\n<p>Thus you can differentiate the priority for your selectors in the stylesheet !-)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419730/" ]
My predicament is fairly simple: This function gets the `id` of 'this' `<li>` element based on parent `id` of `<ul>`. It used to work fine but not any more, I will either need to have `<ul>` use `class`es instead of `id` while still being able to assign `id` of 'current' to the current element, or change my css. ```js function myFunction(element) { liArray = document.getElementById("leftlist").childNodes; i = 0; while (liArray[i]) { liArray[i].id = ""; i++; } element.id = "current"; // or element.className ? } ``` ```css ul#leftlist { background-color: rgb(205, 205, 205); } ul#leftlist li#current a { color: rgb(96, 176, 255); background-color: 218, 218, 218); } ul#leftlist li a { color: rgb(86, 86, 86); } #leftlist a:link { color: rgb(86, 86, 86); background-color: #ddd; } #leftlist a:active { color: rgb(96, 176, 255); background-color: rgb(218, 218, 218); } ``` ```html <ul id="leftlist"> <li onClick='myFunction(this);'> <a href="123" bla bla </a></li> <li onClick='myFunction(this);'> .... etc.</li> </ul> ``` Perhaps I need to change my css. This worked before but now the current `id` is not being effective as `ul#leftlist li a` takes priority even when i assign `id="current"` via JavaScript.
You should use classes for things like "current", not the id. The id normally shouldn't change, and "current" isn't a very good id, as you could have a bunch of things on a page that is "current" in some way. If you need some css style to override another, you can force it with !important: ``` ul#leftlist li.current a { color: rgb(96,176,255) !important; background-color:218,218,218) !important; } ```
226,131
<p>Safari on iPhone automatically creates links for strings of digits that appear to the telephone numbers. I am writing a web page containing an IP address, and Safari is turning that into a phone number link. Is it possible to disable this behavior for a whole page or an element on a page?</p>
[ { "answer_id": 226229, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "<p>You could try encoding them as HTML entities:</p>\n\n<pre><code>&amp;#48; = 0\n&amp;#57; = 9\n</code></pre>\n" }, { "answer_id": 226247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Add this, I think it is what you're looking for:</p>\n\n<pre><code>&lt;meta name = \"format-detection\" content = \"telephone=no\"&gt;\n</code></pre>\n" }, { "answer_id": 227238, "author": "lewinski", "author_id": 30491, "author_profile": "https://Stackoverflow.com/users/30491", "pm_score": 11, "selected": true, "text": "<p>This seems to be the right thing to do, according to the <a href=\"https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Introduction.html\" rel=\"noreferrer\">Safari HTML Reference</a>:</p>\n\n<pre><code>&lt;meta name=\"format-detection\" content=\"telephone=no\"&gt;\n</code></pre>\n\n<p>If you disable this but still want telephone links, you can still use the \"tel\" URI scheme.</p>\n\n<p>Here is the <a href=\"https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html#//apple_ref/doc/uid/TP40008193-SW1\" rel=\"noreferrer\">relevant page</a> at Apple's Developer Library.</p>\n" }, { "answer_id": 3437864, "author": "BobFromBris", "author_id": 381975, "author_profile": "https://Stackoverflow.com/users/381975", "pm_score": 3, "selected": false, "text": "<p>Think I've found a solution: put the number inside a <code>&lt;label&gt;</code> element. Haven't tried any other tags, but <code>&lt;div&gt;</code> left it active on the home screen, even with the <code>telephone=no</code> attribute.</p>\n\n<p>It seems obvious from earlier comments that the meta tag did work, but for some reason has broken under the later versions of iOS, at least under some conditions. I am running 4.0.1.</p>\n" }, { "answer_id": 5557962, "author": "catshow", "author_id": 693700, "author_profile": "https://Stackoverflow.com/users/693700", "pm_score": 5, "selected": false, "text": "<p>I was having the same problem. I found a property on the UIWebView that allows you to turn off the data detectors.</p>\n\n<pre><code>self.webView.dataDetectorTypes = UIDataDetectorTypeNone;\n</code></pre>\n" }, { "answer_id": 5797082, "author": "mattstuehler", "author_id": 49383, "author_profile": "https://Stackoverflow.com/users/49383", "pm_score": 2, "selected": false, "text": "<p>I had the same problem, but on an iPad web app.</p>\n\n<p>Unfortunately, neither...</p>\n\n<pre><code> &lt;meta name = \"format-detection\" content = \"telephone=no\"&gt;\n</code></pre>\n\n<p>nor ...</p>\n\n<pre><code>&amp;#48; = 0\n&amp;#57; = 9\n</code></pre>\n\n<p>... worked.</p>\n\n<p>But, here's three ugly hacks:</p>\n\n<ul>\n<li>replacing the number \"0\" with the letter \"O\"</li>\n<li>replacing the number \"1\" with the letter \"l\"</li>\n<li>insert a meaningless span: e.g., <code>555.5&lt;span&gt;5&lt;/span&gt;5.5555</code></li>\n</ul>\n\n<p>Depending on the font you use, the first two are barely noticeable. The latter obviously involves superfluous code, but is invisible to the user.</p>\n\n<p>Kludgy hacks for sure, and probably not viable if you're generating your code dynamically from data, or if you can't pollute your data this way.</p>\n\n<p>But, sufficient in a pinch.</p>\n" }, { "answer_id": 6047555, "author": "mhenry1384", "author_id": 24267, "author_profile": "https://Stackoverflow.com/users/24267", "pm_score": 2, "selected": false, "text": "<p>I had an ABN (Australian Business Number) that iPad Safari insisted on turning into a phone number link. None of the suggestions helped. My solution was to put img tags between the numbers.</p>\n\n<pre><code>ABN 98&lt;img class=\"PreventSafariFromTurningIntoLink\" /&gt; 009&lt;img /&gt; 675&lt;img /&gt; 709\n</code></pre>\n\n<p>The class exists only to document what the img tags are for.</p>\n\n<p>Works on iPad 1 (4.3.1) and iPad 2 (4.3.3).</p>\n" }, { "answer_id": 6349251, "author": "yodaisgreen", "author_id": 246034, "author_profile": "https://Stackoverflow.com/users/246034", "pm_score": 3, "selected": false, "text": "<p>To disable phone number detection on part of a page, wrap the affected text in an anchor tag with href=\"#\". If you do this, mobile Safari and UIWebView should leave it alone. </p>\n\n<pre><code>&lt;a href=\"#\"&gt; 1234567 &lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 7305442, "author": "Alan M.", "author_id": 199374, "author_profile": "https://Stackoverflow.com/users/199374", "pm_score": 3, "selected": false, "text": "<p>My experience is the same as some others mentioned. The meta tag...</p>\n\n<pre><code>&lt;meta name = \"format-detection\" content = \"telephone=no\"&gt;\n</code></pre>\n\n<p>...works when the website is running in Mobile Safari (i.e., with chrome) but stops working when run as a webapp (i.e., is saved to home screen and runs without chrome).</p>\n\n<p>My less-than-ideal solution is to insert the values into input fields...</p>\n\n<pre><code>&lt;input type=\"text\" readonly=\"readonly\" style=\"border:none;\" value=\"3105551212\"&gt;\n</code></pre>\n\n<p>It's less than ideal because, despite the border being set to none, iOS renders a multi-pixel gray bar above the field. But, it's better than seeing the number as a link.</p>\n" }, { "answer_id": 7778171, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<h3>Solution for Webview!</h3>\n\n<p>For PhoneGap-iPhone / PhoneGap-iOS applications, you can disable telephone number detection by adding the following to your project’s application delegate:</p>\n\n<pre><code>// ...\n\n- (void)webViewDidStartLoad:(UIWebView *)theWebView \n{\n // disable telephone detection, basically &lt;meta name=\"format-detection\" content=\"telephone=no\" /&gt;\n theWebView.dataDetectorTypes = UIDataDetectorTypeAll ^ UIDataDetectorTypePhoneNumber;\n\n return [ super webViewDidStartLoad:theWebView ];\n}\n\n// ...\n</code></pre>\n\n<p>source: <a href=\"http://solutions.michaelbrooks.ca/2011/02/09/disable-telephone-detection-in-phonegap-ios/\" rel=\"nofollow\">Disable Telephone Detection in PhoneGap-iOS</a>.</p>\n" }, { "answer_id": 9008797, "author": "someone else", "author_id": 1169920, "author_profile": "https://Stackoverflow.com/users/1169920", "pm_score": 1, "selected": false, "text": "<p>Same problem in Sencha Touch app solved with meta tag (<code>&lt;meta name=\"format-detection\" content=\"telephone=no\"&gt;</code>) in index.html of app.</p>\n" }, { "answer_id": 10401451, "author": "cabrera", "author_id": 935846, "author_profile": "https://Stackoverflow.com/users/935846", "pm_score": 2, "selected": false, "text": "<p><code>&lt;meta name = \"format-detection\" content = \"telephone=no\"&gt;</code> does not work for emails: if the HTML you are preparing is for an email, the metatag will be ignored.</p>\n\n<p>If what you are targeting are emails, here's yet another ugly-but-works solution for ya'll:</p>\n\n<p>Example of some HTML you want to avoid being linked or auto formatted:</p>\n\n<pre><code>will cease operations &lt;span class='ios-avoid-format'&gt;on June 1,\n2012&lt;/span&gt;&lt;span&gt;&lt;/span&gt;.\n</code></pre>\n\n<p>And the CSS that will make the magic happen:</p>\n\n<pre><code>@media only screen and (device-width: 768px) and (orientation:portrait){\nspan.ios-date{display:none;}\nspan.ios-date + span:after{content:\"on June 1, 2012\";}\n}\n</code></pre>\n\n<p>The drawback: you may need a media query for each of the ipad/iphone portrait/landscape combos</p>\n" }, { "answer_id": 11021252, "author": "Vincent Tobiaz", "author_id": 1454437, "author_profile": "https://Stackoverflow.com/users/1454437", "pm_score": 1, "selected": false, "text": "<p>This answer trumps everything as of 6-13-2012:</p>\n\n<pre><code>&lt;a href=\"#\" style=\"color: #666666; \n text-decoration: none;\n pointer-events: none;\"&gt;\n Boca Raton, FL 33487\n&lt;/a&gt;\n</code></pre>\n\n<p>Change the color to whatever matches your text, text decoration removes the underline, pointer events stops it from being viewed like a link in a browser (pointer doesn't change to a hand)</p>\n\n<p>This is perfect for HTML emails on ios and browser. </p>\n" }, { "answer_id": 14870203, "author": "Jay", "author_id": 751570, "author_profile": "https://Stackoverflow.com/users/751570", "pm_score": 2, "selected": false, "text": "<p>I have tested this myself and found that it works although it is certainly not an elegant solution. Inserting an empty span in the phone number will prevent the data detectors from turning it into a link.</p>\n\n<pre><code>(604) 555&lt;span&gt;&lt;/span&gt; -4321\n</code></pre>\n" }, { "answer_id": 15358743, "author": "Florian Grell", "author_id": 353907, "author_profile": "https://Stackoverflow.com/users/353907", "pm_score": 6, "selected": false, "text": "<p>To disable the phone parsing appearance for specific elements, this CSS seems to do the trick:</p>\n\n<pre><code>.element { pointer-events: none; }\n.element &gt; a { text-decoration:none; color:inherit; }\n</code></pre>\n\n<p>The first rule disables the click, the second takes care of the styling.</p>\n" }, { "answer_id": 17928016, "author": "Phil LaNasa", "author_id": 2374900, "author_profile": "https://Stackoverflow.com/users/2374900", "pm_score": 1, "selected": false, "text": "<p>A trick I use that works on more than just Mobile Safari is to use HTML escape codes and a little mark-up in the phone number. This makes it more difficult for the browser to \"identify\" a phone number, i.e.</p>\n\n<pre><code>Phone: 1-8&amp;#48;&amp;#48;&lt;span&gt;-&lt;/span&gt;62&amp;#48;&lt;span&gt;-&lt;/span&gt;38&amp;#48;3\n</code></pre>\n" }, { "answer_id": 22605764, "author": "Marc", "author_id": 3454790, "author_profile": "https://Stackoverflow.com/users/3454790", "pm_score": 2, "selected": false, "text": "<p>Why would you want to remove the linking, it makes it very user friendly to have th eoption.</p>\n\n<p>If you simply want to remove the auto editing, but keep the link working just add this into your CSS...</p>\n\n<pre><code>a[href^=tel] {\n color: inherit;\n text-decoration:inherit;\n}\n</code></pre>\n" }, { "answer_id": 30804432, "author": "kaosmos", "author_id": 2477547, "author_profile": "https://Stackoverflow.com/users/2477547", "pm_score": 1, "selected": false, "text": "<p>I too have this problem: Safari and other mobile browsers transform the VAT IDs into phone numbers. So I want a clean method to avoid it on a single element, not the whole page (or site).<br>\nI'm sharing a possible solution I found, it is suboptimal but still it is pretty viable: I put, inside the number I don't want to become a <code>tel:</code> link, the <code>&amp;#8288;</code> HTML entity which is the <a href=\"https://stackoverflow.com/a/28405917/2477547\">Word-Joiner invisible character</a>. I tried to stay more semantic (well, at least a sort of) by putting this char in some meaning spot, e.g. for the VAT ID I chose to put it between the different groups of digit according to <a href=\"https://en.wikipedia.org/wiki/VAT_identification_number\" rel=\"nofollow noreferrer\">its format</a> so for an Italian VAT I wrote: <code>0613605&amp;#8288;048&amp;#8288;8</code> which renders in 0613605&#8288;048&#8288;8 and it is not transformed in a telephone number.</p>\n" }, { "answer_id": 31054065, "author": "diazwatson", "author_id": 2285763, "author_profile": "https://Stackoverflow.com/users/2285763", "pm_score": 3, "selected": false, "text": "<p>You can also use the <code>&lt;a&gt;</code> label with <code>javascript: void(0)</code> as <code>href</code> value. <br/><br/>Example as follow:<br/><code>&lt;a href=\"javascript: void(0)\"&gt;+44 456 77 89 87&lt;/a&gt;</code></p>\n" }, { "answer_id": 36733173, "author": "stickyuser", "author_id": 2717951, "author_profile": "https://Stackoverflow.com/users/2717951", "pm_score": 6, "selected": false, "text": "<p>I use a zero-width joiner <code>&amp;zwj;</code></p>\n\n<p>Just put that somewhere in the phone number and it works for me. Tested in BrowserStack (and Litmus for emails).</p>\n" }, { "answer_id": 36927988, "author": "Daniel", "author_id": 2995613, "author_profile": "https://Stackoverflow.com/users/2995613", "pm_score": 1, "selected": false, "text": "<p>Another option is to replace the hyphens in your phone number by the character <code>‑</code> (U+2011 'Unicode Non-Breaking Hyphen')</p>\n" }, { "answer_id": 37722325, "author": "Oliver P", "author_id": 1616477, "author_profile": "https://Stackoverflow.com/users/1616477", "pm_score": 1, "selected": false, "text": "<p>I was really confused by this for a while but finally figured it out. We made updates to our site and had some numbers converting to a link and some weren't. Turns out that numbers won't be converted to a link if they're in a &lt;fieldset&gt;. Obviously not the right solution for most circumstances, but in some it will be the right one.</p>\n" }, { "answer_id": 38213781, "author": "Kareem", "author_id": 2151420, "author_profile": "https://Stackoverflow.com/users/2151420", "pm_score": 0, "selected": false, "text": "<p>Break the number down into separate blocks of text</p>\n\n<pre><code>301 &lt;div style=\"display:inline-block\"&gt;441&lt;/div&gt; 3909\n</code></pre>\n" }, { "answer_id": 73746889, "author": "dev_willis", "author_id": 1437705, "author_profile": "https://Stackoverflow.com/users/1437705", "pm_score": 0, "selected": false, "text": "<p>Adding the meta tag to turn off format detection did not work for me. I was trying to display a zoom meeting ID in a <code>&lt;p&gt;</code> tag along with other text and iOS was turning that ID into a tel link. Additionally, I was targeting tel links via <code>a[href^=&quot;tel:&quot;]</code> in order to give them custom styling so disabling the styles on tel links was not an option.</p>\n<p>The solution I found was to wrap the ID number in a <code>&lt;code&gt;</code> tag. This seems to prevent iOS from messing with it.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10947/" ]
Safari on iPhone automatically creates links for strings of digits that appear to the telephone numbers. I am writing a web page containing an IP address, and Safari is turning that into a phone number link. Is it possible to disable this behavior for a whole page or an element on a page?
This seems to be the right thing to do, according to the [Safari HTML Reference](https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Introduction.html): ``` <meta name="format-detection" content="telephone=no"> ``` If you disable this but still want telephone links, you can still use the "tel" URI scheme. Here is the [relevant page](https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html#//apple_ref/doc/uid/TP40008193-SW1) at Apple's Developer Library.
226,144
<p>We all know that you can overload a function according to the parameters:</p> <pre><code>int mul(int i, int j) { return i*j; } std::string mul(char c, int n) { return std::string(n, c); } </code></pre> <p>Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:</p> <pre><code>int n = mul(6, 3); // n = 18 std::string s = mul(6, 3); // s = "666" // Note that both invocations take the exact same parameters (same types) </code></pre> <p>You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.</p>
[ { "answer_id": 226165, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "<p>As far as I know, you can't (big pity, though...). As a workaround, you can define an 'out' parameter instead, and overload that one.</p>\n" }, { "answer_id": 226173, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 4, "selected": false, "text": "<p>No.</p>\n\n<p>You can't overload by return value because the caller can do anything (or nothing) with it. Consider:</p>\n\n<p><code>mul(1, 2);</code></p>\n\n<p>The return value is just thrown away, so there's no way it could choose an overload based on return value alone.</p>\n" }, { "answer_id": 226176, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>You could use a template, but then you'd have to specify the template parameter when you make the call.</p>\n" }, { "answer_id": 226178, "author": "AshtonKJ", "author_id": 24793, "author_profile": "https://Stackoverflow.com/users/24793", "pm_score": -1, "selected": false, "text": "<p>Put it in a different namespace? That would be how I would do it. Not strictly an overload, rather a just having two methods with the same name, but a different scope (hence the :: scope resolution operator).</p>\n\n<p>So stringnamespace::mul and intnamespace::mul. Maybe its not really what you are asking, but it seems like the only way to do it.</p>\n" }, { "answer_id": 226180, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 2, "selected": false, "text": "<p>You cannot overload a function based on the return value only.</p>\n\n<p>However, while strictly speaking this is not an overloaded function, you could return from your function as a result an instance of a class that overloads the conversion operators.</p>\n" }, { "answer_id": 226192, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Not in C++. What you'd get in the above example would be the returned value which is an int cast into something <code>string</code> can understand, most likely a <code>char</code>. Which would be ASCII 18 or \"device control 2\".</p>\n" }, { "answer_id": 226208, "author": "Paolo Tedesco", "author_id": 15622, "author_profile": "https://Stackoverflow.com/users/15622", "pm_score": -1, "selected": false, "text": "<p>You could do something like </p>\n\n<pre><code>template&lt;typename T&gt;\nT mul(int i,int j){\n return i * j;\n}\n\ntemplate&lt;&gt;\nstd::string mul(int i,int j){\n return std::string(j,i);\n}\n</code></pre>\n\n<p>And then call it like this:</p>\n\n<pre><code>int x = mul&lt;int&gt;(2,3);\nstd::string s = mul&lt;std::string&gt;(2,3);\n</code></pre>\n\n<p>There is no way of overloading on the return value.</p>\n" }, { "answer_id": 226220, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 3, "selected": false, "text": "<p>Use implicit conversion in an in between class.</p>\n\n<pre><code>class BadIdea\n{\n public:\n operator string() { return \"silly\"; }\n operator int() { return 15; }\n};\n\nBadIdea mul(int, int)\n</code></pre>\n\n<p>You get the idea, terrible idea though.</p>\n" }, { "answer_id": 226231, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "<p>I presume you could have it return some weird type Foo that just captures the parameters and then Foo has an implicit operator int and operator string, and it would \"work\", though it wouldn't really be overloading, rather an implicit conversion trick.</p>\n" }, { "answer_id": 226251, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 7, "selected": true, "text": "<pre><code>class mul\n{\npublic:\n mul(int p1, int p2)\n {\n param1 = p1;\n param2 = p2;\n }\n operator int ()\n {\n return param1 * param2;\n }\n\n operator std::string ()\n {\n return std::string(param2, param1 + '0');\n }\n\nprivate:\n int param1;\n int param2;\n};\n</code></pre>\n\n<p>Not that I would use that.</p>\n" }, { "answer_id": 226257, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>Let mul be a class, mul(x, y) its constructor, and overload some casting operators.</p>\n" }, { "answer_id": 226390, "author": "mempko", "author_id": 8863, "author_profile": "https://Stackoverflow.com/users/8863", "pm_score": 0, "selected": false, "text": "<p>You can use the functor solution above. C++ does not support this for functions except for const. You can overload based on const. </p>\n" }, { "answer_id": 228923, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": false, "text": "<p>You have to tell the compiler which version to use. In C++, you can do it three ways.</p>\n\n<h2>Explicitly differentiate the calls by typing</h2>\n\n<p>You somewhat cheated because you sent an integer to a function waiting for a char, and wrongly sent the number six when the char value of '6' is not 6 but 54 (in ASCII):</p>\n\n<pre><code>std::string mul(char c, int n) { return std::string(n, c); }\n\nstd::string s = mul(6, 3); // s = \"666\"\n</code></pre>\n\n<p>The right solution would be, of course, </p>\n\n<pre><code>std::string s = mul(static_cast&lt;char&gt;(54), 3); // s = \"666\"\n</code></pre>\n\n<p>This was worth mentioning, I guess, even if you did not want the solution.</p>\n\n<h2>Explicitly differentiate the calls by dummy pointer</h2>\n\n<p>You can add a dummy parameter to each functions, thus forcing the compiler to choose the right functions. The easiest way is to send a NULL dummy pointer of the type desired for the return:</p>\n\n<pre><code>int mul(int *, int i, int j) { return i*j; }\nstd::string mul(std::string *, char c, int n) { return std::string(n, c); }\n</code></pre>\n\n<p>Which can be used with the code:</p>\n\n<pre><code>int n = mul((int *) NULL, 6, 3); // n = 18\nstd::string s = mul((std::string *) NULL, 54, 3); // s = \"666\"\n</code></pre>\n\n<h2>Explicitly differentiate the calls by templating the return value</h2>\n\n<p>With this solution, we create a \"dummy\" function with code that won't compile if instantiated:</p>\n\n<pre><code>template&lt;typename T&gt;\nT mul(int i, int j)\n{\n // If you get a compile error, it's because you did not use\n // one of the authorized template specializations\n const int k = 25 ; k = 36 ;\n}\n</code></pre>\n\n<p>You'll note this function won't compile, which is a good thing because we want only to use some limited functions through template specialization:</p>\n\n<pre><code>template&lt;&gt;\nint mul&lt;int&gt;(int i, int j)\n{\n return i * j ;\n}\n\ntemplate&lt;&gt;\nstd::string mul&lt;std::string&gt;(int i, int j)\n{\n return std::string(j, static_cast&lt;char&gt;(i)) ;\n}\n</code></pre>\n\n<p>Thus, the following code will compile:</p>\n\n<pre><code>int n = mul&lt;int&gt;(6, 3); // n = 18\nstd::string s = mul&lt;std::string&gt;(54, 3); // s = \"666\"\n</code></pre>\n\n<p>But this one won't:</p>\n\n<pre><code>short n2 = mul&lt;short&gt;(6, 3); // error: assignment of read-only variable ‘k’\n</code></pre>\n\n<h2>Explicitly differentiate the calls by templating the return value, 2</h2>\n\n<blockquote>\n <blockquote>\n <p>Hey, you cheated, too!</p>\n </blockquote>\n</blockquote>\n\n<p>Right, I did use the same parameters for the two \"overloaded\" functions. But you did start the cheating (see above)...</p>\n\n<p>^_^</p>\n\n<p>More seriously, if you need to have different parameters, then you will to write more code, and then have to explicitly use the right types when calling the functions to avoid ambiguities:</p>\n\n<pre><code>// For \"int, int\" calls\ntemplate&lt;typename T&gt;\nT mul(int i, int j)\n{\n // If you get a compile error, it's because you did not use\n // one of the authorized template specializations\n const int k = 25 ; k = 36 ;\n}\n\ntemplate&lt;&gt;\nint mul&lt;int&gt;(int i, int j)\n{\n return i * j ;\n}\n\n// For \"char, int\" calls\ntemplate&lt;typename T&gt;\nT mul(char i, int j)\n{\n // If you get a compile error, it's because you did not use\n // one of the authorized template specializations\n const int k = 25 ; k = 36 ;\n}\n\ntemplate&lt;&gt;\nstd::string mul&lt;std::string&gt;(char i, int j)\n{\n return std::string(j, (char) i) ;\n}\n</code></pre>\n\n<p>And this code would be used as such:</p>\n\n<pre><code>int n = mul&lt;int&gt;(6, 3); // n = 18\nstd::string s = mul&lt;std::string&gt;('6', 3); // s = \"666\"\n</code></pre>\n\n<p>And the following line:</p>\n\n<pre><code>short n2 = mul&lt;short&gt;(6, 3); // n = 18\n</code></pre>\n\n<p>Would still not compile.</p>\n\n<h2>Conclusion</h2>\n\n<p>I love C++...</p>\n\n<p>:-p</p>\n" }, { "answer_id": 429724, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 5, "selected": false, "text": "<p>If you wanted to make <code>mul</code> be a real function instead of a class, you could just use an intermediate class:</p>\n\n<pre><code>class StringOrInt\n{\npublic:\n StringOrInt(int p1, int p2)\n {\n param1 = p1;\n param2 = p2;\n }\n operator int ()\n {\n return param1 * param2;\n }\n\n operator std::string ()\n {\n return std::string(param2, param1 + '0');\n }\n\nprivate:\n int param1;\n int param2;\n};\n\nStringOrInt mul(int p1, int p2)\n{\n return StringOrInt(p1, p2);\n}\n</code></pre>\n\n<p>This lets you do things like passing <code>mul</code> as a function into std algorithms:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n vector&lt;int&gt; x;\n x.push_back(3);\n x.push_back(4);\n x.push_back(5);\n x.push_back(6);\n\n vector&lt;int&gt; intDest(x.size());\n transform(x.begin(), x.end(), intDest.begin(), bind1st(ptr_fun(&amp;mul), 5));\n // print 15 20 25 30\n for (vector&lt;int&gt;::const_iterator i = intDest.begin(); i != intDest.end(); ++i)\n cout &lt;&lt; *i &lt;&lt; \" \";\n cout &lt;&lt; endl;\n\n vector&lt;string&gt; stringDest(x.size());\n transform(x.begin(), x.end(), stringDest.begin(), bind1st(ptr_fun(&amp;mul), 5));\n // print 555 5555 55555 555555\n for (vector&lt;string&gt;::const_iterator i = stringDest.begin(); i != stringDest.end(); ++i)\n cout &lt;&lt; *i &lt;&lt; \" \";\n cout &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 2831943, "author": "justin romaine", "author_id": 340936, "author_profile": "https://Stackoverflow.com/users/340936", "pm_score": -1, "selected": false, "text": "<p>OK you geniuses ;) this is how you do it like a pro.</p>\n\n<pre><code>\nclass mul\n{\n int m_i,m_j;\npublic:\n mull(int i,int j):m_i(i),m_j(j){}\n template\n operator R() \n {\n return (R)m_i * m_j;\n }\n};\n</code>\n</pre>\n\n<p>use like</p>\n\n<pre><code>\ndouble d = mul(1,2);\nlong l = mul(1,2);\n</code></pre>\n\n<p>no stupid &lt;></p>\n" }, { "answer_id": 6754713, "author": "John Littleberry Sr", "author_id": 852895, "author_profile": "https://Stackoverflow.com/users/852895", "pm_score": 2, "selected": false, "text": "<p>Short and simple, the answer is NO. In C++ the requirements are:</p>\n\n<p>1: name of functions MUST be the same<br>\n2: set of arguments MUST differ<br>\n*The return type can be the same or different </p>\n\n<pre><code>//This is not valid\n int foo();\n float foo();\n\n typedef int Int;\n\n int foo(int j);\n int foo(Int j);\n\n//Valid:\n int foo(int j);\n char* foo(char * s);\n int foo(int j, int k);\n float foo(int j, float k);\n float foo(float j, float k);\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
We all know that you can overload a function according to the parameters: ``` int mul(int i, int j) { return i*j; } std::string mul(char c, int n) { return std::string(n, c); } ``` Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used: ``` int n = mul(6, 3); // n = 18 std::string s = mul(6, 3); // s = "666" // Note that both invocations take the exact same parameters (same types) ``` You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.
``` class mul { public: mul(int p1, int p2) { param1 = p1; param2 = p2; } operator int () { return param1 * param2; } operator std::string () { return std::string(param2, param1 + '0'); } private: int param1; int param2; }; ``` Not that I would use that.
226,157
<p>I have a web service that has 8 web methods. These methods are called synchronously, the first call authenticates the user, and the rest of the methods perform a unit of work, these methods are called upon until the work is done.</p> <p>I need to store the state of the work (e.g. what actions to perform next, and what work has been done and is currently being performed.) I currently have a state object that contains this information.</p> <p>My question is what is the best way to persist this object between each web service call? Note that there may be multiple users calling this web service, each with it's own unique state. </p> <p>Here are some scenarios that I am thinking:</p> <p><strong>Idea #1</strong></p> <p>Store the object in a session.</p> <p><strong>Idea #2</strong> Create an instance variable that is a HashMap of a userId and their respective data. something like:</p> <pre> <code> [WebService(Namespace = "http://developer.intuit.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class QBWCService : QBWebConnectorSvc { // instance variable to hold current session data... private Dictionary&lt;Guid,Session&gt Sessions; public QBWCService () { Sessions = new Dictionary&lt;Guid,Session&gt(); } [WebMethod] public override string[] authenticate(string strUserName, string strPassword) { ... Sessions.Add(UserId, new SessoionObject()); } [WebMethod] public override string[] authenticate(Guid UserId) { SessionObject o = Sessions[UserId]; } } </code> </pre> <p>I am thinking that Idea 2 is going to be the cleanest "natural way", however I do not know any of the implication of implementing this sort of scheme...which way or what else would you recommend?</p>
[ { "answer_id": 226185, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "<p>Idea 2 is mimicking Session state management. I don't see an intrinsic benefit from performing your own session statement management.</p>\n" }, { "answer_id": 226193, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Idea one has the benefit of ASP.NET managing the sessions for you. I could see the second option becoming problematic if you have users that don't complete the full lifecycle as then you have entries in the hash table that reference old sessions. At minimum if going with #2 I would be building in a cleaning process to ensure that old sessions are expiring.</p>\n\n<p>If you just need to hold current step information, I'd almost vote for session as there is no point trying to re-invent it.</p>\n" }, { "answer_id": 226212, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 1, "selected": false, "text": "<p>You should take a look at <a href=\"http://msdn.microsoft.com/en-us/netframework/aa663328.aspx\" rel=\"nofollow noreferrer\">Windows Workflow Foundation (WF)</a>. You can design your workflow, then plug in persistence models and such.</p>\n\n<p>That being said - you can't use the session! it won't scale once you create multiple web farms/servers. Surely the QBW developer API needs to scale and be fault tolerant!</p>\n\n<p>Some more info about using this with ASP.NET is <a href=\"http://www.devx.com/dotnet/Article/29992/1954\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 226213, "author": "joshua.ewer", "author_id": 28664, "author_profile": "https://Stackoverflow.com/users/28664", "pm_score": 1, "selected": false, "text": "<p>This might be one of those situations where you are already too far to do a large refactor, but ... </p>\n\n<p>Sounds identical to a state workflow in Windows Workflow. If your plan is eventually expose each of those methods as their own encapsulated services, it would give you all that state management for free, plus you get the added benefit of being able to visually define the workflow between these service calls.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163538.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163538.aspx</a></p>\n\n<p>[EDIT]: Shoot, Jedi beat me to it. What he said.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have a web service that has 8 web methods. These methods are called synchronously, the first call authenticates the user, and the rest of the methods perform a unit of work, these methods are called upon until the work is done. I need to store the state of the work (e.g. what actions to perform next, and what work has been done and is currently being performed.) I currently have a state object that contains this information. My question is what is the best way to persist this object between each web service call? Note that there may be multiple users calling this web service, each with it's own unique state. Here are some scenarios that I am thinking: **Idea #1** Store the object in a session. **Idea #2** Create an instance variable that is a HashMap of a userId and their respective data. something like: ``` [WebService(Namespace = "http://developer.intuit.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class QBWCService : QBWebConnectorSvc { // instance variable to hold current session data... private Dictionary<Guid,Session> Sessions; public QBWCService () { Sessions = new Dictionary<Guid,Session>(); } [WebMethod] public override string[] authenticate(string strUserName, string strPassword) { ... Sessions.Add(UserId, new SessoionObject()); } [WebMethod] public override string[] authenticate(Guid UserId) { SessionObject o = Sessions[UserId]; } } ``` I am thinking that Idea 2 is going to be the cleanest "natural way", however I do not know any of the implication of implementing this sort of scheme...which way or what else would you recommend?
You should take a look at [Windows Workflow Foundation (WF)](http://msdn.microsoft.com/en-us/netframework/aa663328.aspx). You can design your workflow, then plug in persistence models and such. That being said - you can't use the session! it won't scale once you create multiple web farms/servers. Surely the QBW developer API needs to scale and be fault tolerant! Some more info about using this with ASP.NET is [here](http://www.devx.com/dotnet/Article/29992/1954).
226,206
<p>I would actually love to have an AlternatingItemTemplate on a GridView, but all it offers is an AlternatingItemStyle. In my grid, each two column row (in a table layout), has an image in the first column, and a description in the second column. I would like to have the positioning of the image and description alternate on alternate rows. </p> <p>How can I do this?</p>
[ { "answer_id": 226230, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>You will need to either handle the data binding event to try and determine if it is an item or alternating item, or switch to using a control that supports Item and AlternatingItem templates.</p>\n" }, { "answer_id": 226358, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<p>Here's one way:</p>\n\n<p>ASP.NET:</p>\n\n<pre><code>&lt;asp:Repeater runat=\"server\" ID=\"Repeater1\" OnItemDataBound=\"Repeater1_ItemDataBound\" /&gt;\n</code></pre>\n\n<p>ItemDataBound event:</p>\n\n<pre><code>public void Repeater1_ItemDataBound(Object sender, RepeaterItemEventArgs e)\n{\n if (e.Item.ItemType == ListItemType.AlternatingItem)\n {\n // e.Item is an alternating item\n }\n else\n {\n }\n}\n</code></pre>\n" }, { "answer_id": 226960, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 3, "selected": true, "text": "<p>You might consider managing this with AlternatingItemStyle for fun.</p>\n\n<p>Use 1 column or a repeater:</p>\n\n<p>Item Template:</p>\n\n<pre><code>&lt;div class=\"MyImage\"&gt;&lt;img src=\"\" /&gt;&lt;/div&gt;\n&lt;div class=\"MyDescription\"&gt;Blah...Blah...&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.MyItemStyle .MyImage {width:49%; float:left;}\n.MyItemStyle .MyDescription {width:49%; float:right;}\n\n.MyAltItemStyle .MyImage {width:49%; float:right;}\n.MyAltItemStyle .MyDescription {width:49%; float:left;}\n</code></pre>\n\n<p>Apply to Gridview/Repeater:</p>\n\n<pre><code>ItemStyle = \"MyItemStyle\"\nAlternatingItemStyle = \"MyAltItemStyle\"\n</code></pre>\n\n<p>This would let you change your mind without having to recode event handlers etc.</p>\n" }, { "answer_id": 227088, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>I'd think this would work:</p>\n\n<pre><code> &lt;asp:GridView&gt;\n &lt;Columns&gt;\n &lt;asp:TemplateColumn&gt;\n &lt;%# Container.DataItemIndex % 2 == 0 ? Eval(\"Image\") : Eval(\"Desc\") %&gt;\n &lt;/asp:TemplateColumn&gt;\n &lt;asp:TemplateColumn&gt;\n &lt;%# Container.DataItemIndex % 2 == 0 ? Eval(\"Desc\") : Eval(\"Image\") %&gt;\n &lt;/asp:TemplateColumn&gt;\n &lt;/Columns&gt;\n &lt;/asp:GridView&gt;\n</code></pre>\n\n<p>Obviously, the Eval image would really need to be an img tag, or you could substitute some usercontrols, etc. The important bit is the Container.DataItemIndex % 2. You could even use that as a databind on visible.</p>\n\n<pre><code> &lt;asp:GridView&gt;\n &lt;Columns&gt;\n &lt;asp:TemplateColumn&gt;\n &lt;uc:Image Data='&lt;%# Eval(\"Image\") %&gt;' \n Visible='&lt;%# Container.DataItemIndex % 2 == 0 %&gt;' /&gt;\n &lt;uc:Description Data='&lt;%# Eval(\"Description\") %&gt;' \n Visible='&lt;%# Container.DataItemIndex % 2 != 0 %&gt;' /&gt;\n &lt;/asp:TemplateColumn&gt;\n &lt;asp:TemplateColumn&gt;\n &lt;uc:Image Data='&lt;%# Eval(\"Image\") %&gt;' \n Visible='&lt;%# Container.DataItemIndex % 2 != 0 %&gt;' /&gt;\n &lt;uc:Description Data='&lt;%# Eval(\"Description\") %&gt;' \n Visible='&lt;%# Container.DataItemIndex % 2 == 0 %&gt;' /&gt;\n &lt;/asp:TemplateColumn&gt;\n &lt;/Columns&gt;\n &lt;/asp:GridView&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
I would actually love to have an AlternatingItemTemplate on a GridView, but all it offers is an AlternatingItemStyle. In my grid, each two column row (in a table layout), has an image in the first column, and a description in the second column. I would like to have the positioning of the image and description alternate on alternate rows. How can I do this?
You might consider managing this with AlternatingItemStyle for fun. Use 1 column or a repeater: Item Template: ``` <div class="MyImage"><img src="" /></div> <div class="MyDescription">Blah...Blah...</div> ``` CSS: ``` .MyItemStyle .MyImage {width:49%; float:left;} .MyItemStyle .MyDescription {width:49%; float:right;} .MyAltItemStyle .MyImage {width:49%; float:right;} .MyAltItemStyle .MyDescription {width:49%; float:left;} ``` Apply to Gridview/Repeater: ``` ItemStyle = "MyItemStyle" AlternatingItemStyle = "MyAltItemStyle" ``` This would let you change your mind without having to recode event handlers etc.
226,221
<p>I'd like to do something like this</p> <blockquote> <pre><code>raiserror(concat('Error in case @isFishy =', @isFishy, ' @isSmarmy=', @isSmarmy, ' @isTasty = ', @isTasty), 10, 1) --or raiserror('Error in case @isFishy =' + @isFishy + ' @isSmarmy=' + @isSmarmy + ' @isTasty = ' + @isTasty, 10, 1) </code></pre> </blockquote> <p>But it just isn't working. How do I accomplish this? I'm in SQL Server 2005.</p>
[ { "answer_id": 226245, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I use raiserror a lot. We have some stored procedures that are called from a .Net app each night for batch processing, and the .Net app wants to log the procedure output this way. I don't know why, but I generally have to build the string before calling raiserror. </p>\n" }, { "answer_id": 226474, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 5, "selected": true, "text": "<p>The error message in RAISERROR has actually similar syntax to printf function in C, so assuming your arguments are of the type of integer you would need to use:</p>\n\n<pre><code>raiserror(N'Error in case @isFishy = %d @isSmarmy = %d @isTasty = %d',10,1,@isFishy,@isSmarmy,@isTasty)\n</code></pre>\n\n<p>check out <a href=\"http://msdn.microsoft.com/en-us/library/ms178592(SQL.90).aspx\" rel=\"noreferrer\">BOL</a> for details and other options</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8435/" ]
I'd like to do something like this > > > ``` > raiserror(concat('Error in case @isFishy =', @isFishy, ' @isSmarmy=', @isSmarmy, ' @isTasty = ', @isTasty), 10, 1) > --or > raiserror('Error in case @isFishy =' + @isFishy + ' @isSmarmy=' + @isSmarmy + ' @isTasty = ' + @isTasty, 10, 1) > > ``` > > But it just isn't working. How do I accomplish this? I'm in SQL Server 2005.
The error message in RAISERROR has actually similar syntax to printf function in C, so assuming your arguments are of the type of integer you would need to use: ``` raiserror(N'Error in case @isFishy = %d @isSmarmy = %d @isTasty = %d',10,1,@isFishy,@isSmarmy,@isTasty) ``` check out [BOL](http://msdn.microsoft.com/en-us/library/ms178592(SQL.90).aspx) for details and other options
226,271
<p>I know how to find out the current domain name in PHP already, the problem is when I put this code into a file and then include it from another server it shows the domain name of where the file is located. Is there any way for it to find out the domain or the site containing the include() code?</p>
[ { "answer_id": 226283, "author": "Christian P.", "author_id": 9479, "author_profile": "https://Stackoverflow.com/users/9479", "pm_score": 0, "selected": false, "text": "<p>If you include a PHP page from another server, the page will get parsed by the original server and the result will be sent to you - the page you receive is nothing but text, no PHP code included.</p>\n" }, { "answer_id": 226324, "author": "Mitch Haile", "author_id": 28807, "author_profile": "https://Stackoverflow.com/users/28807", "pm_score": 0, "selected": false, "text": "<p>This is a crude hack, but on the remote server, you could look up the domain name of $_ENV['REMOTE_HOST'].</p>\n\n<p>This would be the domain name of the guy doing the \"include\" from the perspective of the remote server.</p>\n\n<p>I assume you have some reason for wanting to implement this strange topology--restrictions in a virtual host environment, or something. I would suggest looking into alternative infrastructure if possible.</p>\n" }, { "answer_id": 226335, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 1, "selected": false, "text": "<p>Are you doing something like:</p>\n\n<pre><code>include 'http://example.com/script.php';\n</code></pre>\n\n<p>?</p>\n\n<p>NB: This approach generally considered to be a bit of no-no from a security point of view.</p>\n\n<p>Anyway, the included script is actually being executed on the other server, then the output of the script is being executed on the current server. You can get around this by echoing actual code, something like this:</p>\n\n<p>Currently:</p>\n\n<pre><code>&lt;? \n//do something\necho '$v = '.$_SERVER['HTTP_HOST'].';'\n?&gt;\n</code></pre>\n\n<p>Other way:</p>\n\n<pre><code>&lt;?\n//do something\n?&gt;\n$v = $_SERVER['HTTP_HOST'];\n</code></pre>\n\n<p>But then maybe I'm misunderstanding your question.</p>\n" }, { "answer_id": 228018, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 1, "selected": true, "text": "<p>You can run it locally using \"eval\" then it should use the proper domain\nstore your script as a text file then download it and then execute:</p>\n\n<pre><code>eval(file_get_contents(\"http://someDomain.com/somePhpscript.txt\"));\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
I know how to find out the current domain name in PHP already, the problem is when I put this code into a file and then include it from another server it shows the domain name of where the file is located. Is there any way for it to find out the domain or the site containing the include() code?
You can run it locally using "eval" then it should use the proper domain store your script as a text file then download it and then execute: ``` eval(file_get_contents("http://someDomain.com/somePhpscript.txt")); ```
226,272
<p>I have one user who gets an error message when he closes his browser. This only happens when he has visited a page which contains my applet. It seems to have been registered as a bug at Sun but that was many years ago. He is using Java 1.6 and IE7.</p> <p>Has anyone seen this before and know a solution or work-around?</p> <pre><code>java.lang.NullPointerException: null pData at sun.awt.windows.WComponentPeer.hide(Native Method) at java.awt.Component.removeNotify(Unknown Source) at java.awt.Container.removeNotify(Unknown Source) at java.awt.Container.removeNotify(Unknown Source) at java.awt.Container.removeAll(Unknown Source) at sun.plugin.viewer.frame.IExplorerEmbeddedFrame.windowClosed(Unknown Source) at java.awt.Window.processWindowEvent(Unknown Source) at java.awt.Window.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) </code></pre> <p><strong>UPDATE</strong> The user removed Google Desktop and the problem has not occured since. So there you go... Thanks everyone!</p>
[ { "answer_id": 226298, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": true, "text": "<p>I used to get that error a lot for just about every applet that was loaded in the browser. I never figured out <em>how</em>, but Google Desktop was breaking java in some way. After uninstalling google desktop the error went away.</p>\n" }, { "answer_id": 226435, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 0, "selected": false, "text": "<p>Have you had them try 1.6u10? It was released last week, and supposedly fixes a number of applet issues. Otherwise, what build of 1.6 are they using?</p>\n" }, { "answer_id": 1458976, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I don't know a solution but I know a prevention of this problem.\nIf javascript is enabled in your web browser then place this code in a script tag inside your head tag of the html file from which applet is opened:</p>\n\n<pre><code>&lt;SCRIPT language = \"JavaScript\"&gt;\n window.onunload = function() { document.body.innerHTML = \"\"; } \n&lt;/script&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11249/" ]
I have one user who gets an error message when he closes his browser. This only happens when he has visited a page which contains my applet. It seems to have been registered as a bug at Sun but that was many years ago. He is using Java 1.6 and IE7. Has anyone seen this before and know a solution or work-around? ``` java.lang.NullPointerException: null pData at sun.awt.windows.WComponentPeer.hide(Native Method) at java.awt.Component.removeNotify(Unknown Source) at java.awt.Container.removeNotify(Unknown Source) at java.awt.Container.removeNotify(Unknown Source) at java.awt.Container.removeAll(Unknown Source) at sun.plugin.viewer.frame.IExplorerEmbeddedFrame.windowClosed(Unknown Source) at java.awt.Window.processWindowEvent(Unknown Source) at java.awt.Window.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) ``` **UPDATE** The user removed Google Desktop and the problem has not occured since. So there you go... Thanks everyone!
I used to get that error a lot for just about every applet that was loaded in the browser. I never figured out *how*, but Google Desktop was breaking java in some way. After uninstalling google desktop the error went away.
226,280
<p>In eclipse 3.4 I'm trying to do some performance tests on a large product, one of the included libraries is the vecmath.jar (javax.vecmath package) from the Java3D project. Everything was working fine and then when trying to run it yesterday I get this exception/error not long after starting it up:</p> <pre><code>java.lang.UnsupportedClassVersionError: javax/vecmath/Point2f (Unsupported major.minor version 49.0) </code></pre> <p>Which I believe means that I'm trying to load a java 1.5 class file into a 1.4 jvm which is unsupported. However when I went to the class file to check this I saw this in the eclipse class file viewer:</p> <pre><code>Compiled from Point2f.java (version 1.2 : 46.0, super bit) </code></pre> <p>So the class loader says it is version 49.0 but the class file says its 46.0. I've tried cleaning and fully rebuilding the project, I've confirmed that the compiler version for the project is 1.4, the JRE is 1.4 and for the run configuration the 1.4 jvm is selected. I'm totally stuck on this, does anyone have any idea what might be causing this?</p> <p>Thanks</p> <p>===EDIT===</p> <p>It turns out that a version of java3d which was incompatible with java 1.4.2 had been installed in C:\Program Files\java\j2re1.4.2_18\lib\ext. I installed a newer version of Java3D to play around with in java6 and i guess it installed the libs in all my JREs even the ones which were incompatible.</p>
[ { "answer_id": 226385, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 0, "selected": false, "text": "<p>I believe JRE 1.5 is required for the latest version of Java3D.</p>\n" }, { "answer_id": 226463, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": true, "text": "<p>Could there be another javax.vecmath.Point2f on your classpath?</p>\n" }, { "answer_id": 226552, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "<p>Have you checked:</p>\n\n<pre><code>Window\n -&gt; Preferences\n -&gt; Java\n -&gt; Compiler\n -&gt; Compiler Compliance Level\n</code></pre>\n\n<p>To see if this value is screwy?</p>\n" }, { "answer_id": 10273847, "author": "carea", "author_id": 1350327, "author_profile": "https://Stackoverflow.com/users/1350327", "pm_score": 0, "selected": false, "text": "<p>You have to add the </p>\n\n<ol>\n<li>\"java_home : C:\\Program Files\\Java\\jdk1.6.0_16\"</li>\n<li>\"path: C:\\Program Files\\Java\\jdk1.6.0_16\\bin;\"</li>\n</ol>\n\n<p>to your Environment Variables!</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25920/" ]
In eclipse 3.4 I'm trying to do some performance tests on a large product, one of the included libraries is the vecmath.jar (javax.vecmath package) from the Java3D project. Everything was working fine and then when trying to run it yesterday I get this exception/error not long after starting it up: ``` java.lang.UnsupportedClassVersionError: javax/vecmath/Point2f (Unsupported major.minor version 49.0) ``` Which I believe means that I'm trying to load a java 1.5 class file into a 1.4 jvm which is unsupported. However when I went to the class file to check this I saw this in the eclipse class file viewer: ``` Compiled from Point2f.java (version 1.2 : 46.0, super bit) ``` So the class loader says it is version 49.0 but the class file says its 46.0. I've tried cleaning and fully rebuilding the project, I've confirmed that the compiler version for the project is 1.4, the JRE is 1.4 and for the run configuration the 1.4 jvm is selected. I'm totally stuck on this, does anyone have any idea what might be causing this? Thanks ===EDIT=== It turns out that a version of java3d which was incompatible with java 1.4.2 had been installed in C:\Program Files\java\j2re1.4.2\_18\lib\ext. I installed a newer version of Java3D to play around with in java6 and i guess it installed the libs in all my JREs even the ones which were incompatible.
Could there be another javax.vecmath.Point2f on your classpath?
226,288
<p>When creating a new build in Team Foundation Server, I get the following error when attempting to run the new build:</p> <blockquote> <p>The path C:\Build\ProductReleases\FullBuildv5.4.2x\Sources is already mapped to workspace BuildServer_23.</p> </blockquote> <p>I am unable to see a workspace by that name in the workspaces dialog.</p>
[ { "answer_id": 226304, "author": "NotMyself", "author_id": 303, "author_profile": "https://Stackoverflow.com/users/303", "pm_score": 8, "selected": true, "text": "<p>Use the command line utility <em>TF - Team Foundation Version Control Tool</em> (<strong>tf</strong>).</p>\n\n<p>You can get a list of all workspaces by bringing up a <em>Visual Studio Command Prompt</em> then changing to your workspace folder and issuing the following commands:</p>\n\n<pre><code>C:\\YourWorkspaceFolder&gt;tf workspaces /owner:*\n</code></pre>\n\n<p>You should see your problem workspace in the list as well as it's owner.</p>\n\n<p>You can delete the workspace with the following command:</p>\n\n<pre><code>C:\\YourWorkspaceFolder&gt;tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAME\n</code></pre>\n" }, { "answer_id": 503817, "author": "YeahStu", "author_id": 1300, "author_profile": "https://Stackoverflow.com/users/1300", "pm_score": 5, "selected": false, "text": "<p>I received this error, which was caused by having two build definitions that pointed to the same source. The issue was that I used a static build directory in the Build Agent.</p>\n\n<p>This forum post describes my issue and resolution exactly:\n<a href=\"http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/60a4138a-9b28-4c46-bdf4-f9775ce43c3e/\" rel=\"noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/tfsbuild/thread/60a4138a-9b28-4c46-bdf4-f9775ce43c3e/</a></p>\n" }, { "answer_id": 5667750, "author": "asuciu", "author_id": 286463, "author_profile": "https://Stackoverflow.com/users/286463", "pm_score": 5, "selected": false, "text": "<p>We had the same problem but deleting the workspace's from the TFS server did not work. \n(I should mention that I grabbed my colleagues VM that was already set up with his credentials.)</p>\n\n<p>For me this worked:\n<a href=\"http://blogs.msdn.com/b/buckh/archive/2006/09/12/path-is-already-mapped-in-workspace.aspx\">http://blogs.msdn.com/b/buckh/archive/2006/09/12/path-is-already-mapped-in-workspace.aspx</a></p>\n\n<p>I just went into the : ...\\Local Settings\\Application Data\\ made a search for VersionControl.config, opened up the folder that contained this file and deleted all of it's contents. </p>\n\n<p>Previous to that I tried manually editing the file but it continued with the same error message.</p>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 6620347, "author": "Lionel Orellana", "author_id": 193755, "author_profile": "https://Stackoverflow.com/users/193755", "pm_score": 2, "selected": false, "text": "<p>If you don't have permissions on the server to delete other people's workspaces, you can just change the name of the build definition. TFS will create a new workspace and map it to \"C:\\Build\\ProductReleases\\new build name here\\Sources\".</p>\n" }, { "answer_id": 7864150, "author": "deadlydog", "author_id": 602585, "author_profile": "https://Stackoverflow.com/users/602585", "pm_score": 4, "selected": false, "text": "<p>For some reason I was having trouble deleting the workspace from the command-line utility. Luckily I found <a href=\"http://www.attrice.info/downloads/index.htm#tfssidekicks2010\" rel=\"noreferrer\">Team Foundation Sidekicks 2010</a> (from <a href=\"http://social.msdn.microsoft.com/Forums/en-US/tfsgeneral/thread/dd2391e4-1941-4d64-bf70-90d60b045c9a/\" rel=\"noreferrer\">this post</a>) which is free and provides a GUI for viewing and deleting TFS workspaces, and many more useful TFS features.</p>\n" }, { "answer_id": 8042115, "author": "Mary Hamlin", "author_id": 426700, "author_profile": "https://Stackoverflow.com/users/426700", "pm_score": 3, "selected": false, "text": "<p>I had a similar problem with Visual Studio 2010 complaining about an already-mapped-workspace, but instead of deleting the entire workspace, I used the following from the Visual Studio Command Prompt: \"tf workspace PROBLEM_WORKSPACE_NAME\". This brought up an \"Edit Workspace\" dialog. From there I was able to remove the path in question from the \"Working Folders\" list, which got rid of the error. </p>\n" }, { "answer_id": 10146154, "author": "Mike Cheel", "author_id": 426422, "author_profile": "https://Stackoverflow.com/users/426422", "pm_score": 3, "selected": false, "text": "<p>Here is what I did (well what I do):</p>\n\n<p>Using TFS Sidekicks clear out the user and server filters so they are blank. This will let you get all workspaces.</p>\n\n<p>Check the build error for the workspace name. In the OPs case it is BuildServer_23. It is different in my environment but basically just match up the error name with the one in the tfs sidekick list.</p>\n\n<p>Click the red x to delete the workspace.</p>\n\n<p>Viola!</p>\n" }, { "answer_id": 14530847, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 1, "selected": false, "text": "<p>I changed</p>\n\n<pre><code>Build Definition -&gt; Workspace -&gt; Build Agent Folder\n</code></pre>\n\n<p>from</p>\n\n<pre><code>c:\\some\\path\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$(SourceDir)\n</code></pre>\n\n<p>and it fixed the issue.</p>\n" }, { "answer_id": 18208864, "author": "Mohamad Pahlavan", "author_id": 1010559, "author_profile": "https://Stackoverflow.com/users/1010559", "pm_score": 3, "selected": false, "text": "<p>the rest was fairly easy.</p>\n\n<p>Simply go to this folder: \nC:\\Users{UserName}\\AppData\\Local\\Microsoft\\Team Foundation\\4\\Cache \nand delete all that's in the folder.</p>\n" }, { "answer_id": 19688991, "author": "Stinky Towel", "author_id": 2779990, "author_profile": "https://Stackoverflow.com/users/2779990", "pm_score": 2, "selected": false, "text": "<p>If applicable, you can also clone the build definition and change its name. This workded for me.</p>\n" }, { "answer_id": 24599533, "author": "Morteza", "author_id": 2508474, "author_profile": "https://Stackoverflow.com/users/2508474", "pm_score": 3, "selected": false, "text": "<p>I was getting an exception telling me that the file was already mapped in another workspace:\n<strong>\"The path {File Path} is already mapped in workspace {Workspace Name}.\"</strong></p>\n\n<p>This workspace was <strong>deleted beofre</strong>.\nWith the help of friend of mine I found out that TFS save workspace info under the user local settings dir. We found a file named:</p>\n\n<p><strong>VersionControl.config</strong> under <strong>{User Documents and Settings dir}\\Local Settings\\Application Data\\Microsoft\\Team Foundation\\1.0\\Cache.</strong>\nThis file contains all the local mapping of TFS. Probably when you use the Map method and don't use:\npublic void DeleteMapping(WorkingFolder mapping); before deleting the workspace the mapping information is not removed from this file which is used by TFS to check if you've alreay mapped a specific path.</p>\n\n<p><strong>To resolve this problem delete all the keys from the config file. Don't delete the file because you'll get it again from the server cache.</strong> </p>\n" }, { "answer_id": 25196199, "author": "rpstex", "author_id": 3920861, "author_profile": "https://Stackoverflow.com/users/3920861", "pm_score": 2, "selected": false, "text": "<p>While trying to 'Get latest version' of a project which I had previously mapped to a local directory and then deleted, I saw this same error message.\nFirst I tried the SideKick tool and then the Visual Studio 2010 command prompt, both of which told me I had no workspaces mapped.</p>\n\n<p>Next I searched for 'VersionControl.config' within <code>c:/users/myuser/appdata</code>, and deleted the 4 references it found.\nI re-opened Visual Studio and I was able to re-map the project, no more error!</p>\n" }, { "answer_id": 25669797, "author": "user2048576", "author_id": 2048576, "author_profile": "https://Stackoverflow.com/users/2048576", "pm_score": 2, "selected": false, "text": "<p>Simplest way to do this is to go to your AppData and delete the TFS cache (depending on the version 3.0 or 4.0)</p>\n\n<p>C:\\Users{UserName}\\AppData\\Local\\Microsoft\\Team Foundation\\3.0\\Cache \nor \nC:\\Users{UserName}\\AppData\\Local\\Microsoft\\Team Foundation\\4.0\\Cache </p>\n" }, { "answer_id": 26758574, "author": "Rahim", "author_id": 1749779, "author_profile": "https://Stackoverflow.com/users/1749779", "pm_score": 6, "selected": false, "text": "<p>Just delete the contents of the following folder(s):</p>\n\n<p><strong>C:\\Users\\UserName\\AppData\\Local\\Microsoft\\Team Foundation\\3.0\\Cache</strong></p>\n\n<p>Where UserName is actual or current user, and 3.0 is the version number.</p>\n" }, { "answer_id": 31032112, "author": "TNV", "author_id": 791587, "author_profile": "https://Stackoverflow.com/users/791587", "pm_score": 5, "selected": false, "text": "<p>I had a similar issue and to remove the workspace that was causing me a problem, I logged into another machine with TFS client installed and performed the following:</p>\n\n<ul>\n<li>On the <strong>File</strong> menu, point to <strong>Source Control</strong>, <strong>Advanced</strong>, and then click\n<strong>Workspaces...</strong>. </li>\n<li>In the <strong>Manage Workspaces</strong> dialog box, tick the <strong>Show remote packages</strong> checkbox. </li>\n<li>Under the <strong>Name</strong> column, select the workspace that you want to remove, and then click <strong>Remove</strong>. </li>\n<li>In\nthe <strong>Confirmation</strong> dialog box, click <strong>OK</strong>.</li>\n</ul>\n" }, { "answer_id": 39237706, "author": "Joe", "author_id": 4097268, "author_profile": "https://Stackoverflow.com/users/4097268", "pm_score": 2, "selected": false, "text": "<p>TDN's solution worked for me when I was having the same issue. The Build server created workspaces under my account. Checking this box allowed me to see and delete them.</p>\n" }, { "answer_id": 40492823, "author": "AyeVeeKay", "author_id": 5292948, "author_profile": "https://Stackoverflow.com/users/5292948", "pm_score": 2, "selected": false, "text": "<p>I tried all the following solutions such as :</p>\n\n<ol>\n<li>Use sidekicks to delete WS.</li>\n<li>Use tf commands to delete remote server workspaces.</li>\n<li>Delete the TFS cache folder.</li>\n</ol>\n\n<p>The following worked for me:</p>\n\n<pre><code>tf workspaces /remove:*\n</code></pre>\n" }, { "answer_id": 42702472, "author": "Serge Voloshenko", "author_id": 5771669, "author_profile": "https://Stackoverflow.com/users/5771669", "pm_score": 2, "selected": false, "text": "<p>I got same issue in Visual Studio 2017 and TFS 2017. DefaultCollection must be mapped first to you local path. Somehow this step was skipped and I got only MyFirstProject mapped.</p>\n\n<p><a href=\"https://i.stack.imgur.com/KoZMm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KoZMm.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>All you need to do is: <br>\n<strong>- 1.</strong> Go to your TFS web page and remove the project from the server.</p>\n\n<p><a href=\"https://i.stack.imgur.com/6wNhr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6wNhr.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>- 2.</strong> Remove the project from your local \"Worksapces\"</p>\n\n<p><a href=\"https://i.stack.imgur.com/U6SQv.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U6SQv.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>- 3.</strong> Go to \"Manage Connections\" which will refresh your Home page in TeamExplorer.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SVrn8.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SVrn8.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>- 4.</strong> You will get Configuration page which will allow you to setup root path to your DefaultCollection.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Txxes.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Txxes.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>- 5.</strong> You should get message that it been done successfully. Now you can create your project.</p>\n\n<p><a href=\"https://i.stack.imgur.com/wpuFu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wpuFu.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>It's important to map root of your collection to your workspace first and then map a new project.</strong></p>\n" }, { "answer_id": 45845104, "author": "Michael Twohey", "author_id": 4279367, "author_profile": "https://Stackoverflow.com/users/4279367", "pm_score": 2, "selected": false, "text": "<p>My issue was related to using multiple accounts. This is how I was able to switch accounts.</p>\n\n<p>Open <strong>Team Explorer</strong></p>\n\n<p>From the big drop down menu near the top of the pane...</p>\n\n<p>Navigate to:\n<strong>Projects and my Teams</strong>><strong>Manage Connections</strong></p>\n\n<p>Navigate to:\n<strong>Manage Connections</strong>><strong>Connect to Team Project</strong></p>\n\n<p>Use the \"Switch User\" link to switch accounts.</p>\n\n<p>Now the workspace names will match the chosen account.</p>\n" }, { "answer_id": 53527242, "author": "Paul M", "author_id": 6722752, "author_profile": "https://Stackoverflow.com/users/6722752", "pm_score": 0, "selected": false, "text": "<p>I had this issue with this with Azure DevOps automated builds in an on-prem TFS build agent. Removing the workspace using TFS Sidekicks did not work. And tf.exe could not even find the workspace to delete it.</p>\n\n<p>This solution should work for TFS 2017, TFS 2018, Azure DevOps, and possibly other versions:</p>\n\n<ol>\n<li>Take note of the workspace GUID in the error message.</li>\n<li>On the machine where the build is taking place, navigate to: %USERPROFILE%\\AppData\\Local\\Microsoft\\Team Foundation\\ (where %USERPROFILE% belongs to the user that triggered the build).</li>\n<li>Search for and remove all instances of the workspace GUID under that directory. There will likely be a folder in a 'cache' directory, as well as entries in 'LocationServerMap.xml' and 'LocalItemExclusions.config'. Remove them all.</li>\n</ol>\n\n<p>That worked in my circumstance.</p>\n" }, { "answer_id": 54839336, "author": "Majid", "author_id": 2040375, "author_profile": "https://Stackoverflow.com/users/2040375", "pm_score": 0, "selected": false, "text": "<p>Simply delete the workspace:</p>\n\n<pre><code>workspace /delete \"the-workspace-name\"\n</code></pre>\n" }, { "answer_id": 60827639, "author": "msteel9999", "author_id": 1481182, "author_profile": "https://Stackoverflow.com/users/1481182", "pm_score": 2, "selected": false, "text": "<p>I couldn't get any other solution to work.</p>\n\n<p>I had a new account created and the old account no longer had permissions (both on same machine).</p>\n\n<p>I tried:\n1) Deleting the workspace (couldn't see in VS with or without remote workspaces checked)\n2) Deleting from the command line\n3) New owner command\n4) Deleting the cache</p>\n\n<p>So I simply opened VS as admin and mapped to a different folder.</p>\n" }, { "answer_id": 63645368, "author": "Jari Kulmala", "author_id": 3069469, "author_profile": "https://Stackoverflow.com/users/3069469", "pm_score": 2, "selected": false, "text": "<p>Deleting the workspace and cache was not sufficient for me.\nI had to also restart the &quot;Visual Studio Team Foundation Build Service Host&quot; service.</p>\n" }, { "answer_id": 70311524, "author": "Demodave", "author_id": 953496, "author_profile": "https://Stackoverflow.com/users/953496", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Go to the Source Control Explorer</li>\n<li>In the toolbar there is a dropdown list of Workspaces.</li>\n<li>Click the dropdown and go to workspaces.</li>\n<li>Remove the unwanted workspace.</li>\n<li>Map to your local.</li>\n</ol>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303/" ]
When creating a new build in Team Foundation Server, I get the following error when attempting to run the new build: > > The path > C:\Build\ProductReleases\FullBuildv5.4.2x\Sources > is already mapped to workspace > BuildServer\_23. > > > I am unable to see a workspace by that name in the workspaces dialog.
Use the command line utility *TF - Team Foundation Version Control Tool* (**tf**). You can get a list of all workspaces by bringing up a *Visual Studio Command Prompt* then changing to your workspace folder and issuing the following commands: ``` C:\YourWorkspaceFolder>tf workspaces /owner:* ``` You should see your problem workspace in the list as well as it's owner. You can delete the workspace with the following command: ``` C:\YourWorkspaceFolder>tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAME ```
226,300
<p>What I want to do is an outer join to a table, where I exclude records from the joined table based on matching a constant, however keep records from the main table. For example:</p> <pre><code>SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id AND b.bar = 'foo' </code></pre> <p>Expected results:</p> <pre> id other baz -- ---------- ------- 1 Has foo Include 2 Has none (null) 3 Has foobar (null) </pre> <p>I can't get the same results by putting it in the filter condition. If I use the following:</p> <pre><code>SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id WHERE (b.bar IS NULL OR b.bar = 'foo') </code></pre> <p>I get these incorrect results:</p> <pre> id other baz -- -------- ------- 1 Has foo Include 2 Has none (null) </pre> <p>Where it excluded records of A that happen to match a record of B where bar = 'foobar'. I don't want that, I want A to be present, but B to be nulls in that case.</p> <p>Table B will have multiple records that need excluding, so I don't think I can filter this on the Crystal side without doing a lot of messing around to avoid problems from duplicate records from table A.</p> <p>I cannot use a SQL command object, as the third party application that we are running the reports from seems to choke on SQL command objects.</p> <p>I cannot use views, as our support contract does not permit database modifications, and our vendor considers adding views a database modification.</p> <p>I am working with Crystal Reports XI, specifically version 11.0.0.895. In case it makes a difference, I am running against a Progress 9.1E04 database using the SQL-92 ODBC driver.</p> <p>The sample tables and data used in the examples can be created with the following:</p> <pre><code>CREATE TABLE a (id INTEGER, other VARCHAR(32)); CREATE TABLE b (id INTEGER, bar VARCHAR(32), baz VARCHAR(32)); insert into A (id, other) values ('1', 'Has foo'); insert into A (id, other) values ('2', 'Has none'); insert into A (id, other) values ('3', 'Has foobar'); insert into B (id, bar, baz) values ('1', 'foo', 'Include'); insert into B (id, bar, baz) values ('1', 'foobar', 'Exclude'); insert into B (id, bar, baz) values ('1', 'another', 'Exclude'); insert into B (id, bar, baz) values ('1', 'More', 'Exclude'); insert into B (id, bar, baz) values ('3', 'foobar', 'Exclude'); </code></pre>
[ { "answer_id": 231338, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 0, "selected": false, "text": "<p>Not sure if you can do this in Crystal but how about joining to a Select?</p>\n\n<pre><code>SELECT a.id, x.baz\nFROM a\nLEFT OUTER JOIN \n (SELECT id, baz FROM b WHERE bar = 'foo') As x ON a.id = x.id\n</code></pre>\n" }, { "answer_id": 255122, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 0, "selected": false, "text": "<p>Can't you create appropriate views in database and base your report on these views? I'm using Crystal Reports on MSSQL and often I just create views to avoid similar problems.</p>\n" }, { "answer_id": 303328, "author": "Arvo", "author_id": 35777, "author_profile": "https://Stackoverflow.com/users/35777", "pm_score": 0, "selected": false, "text": "<p>I can see two solutions:</p>\n\n<p>a) accept presence of multiple (unneeded) rows in B (and repeated values in A), calculate totals using runnign total fields and/or formulas - not easy way, but almost always possible;<br>\nb) move B into subreport (where you can set filter easily) and communicate needed values between main and subreport using shared variables.</p>\n\n<p>Subreports are powerful tool for solving this kind of problems, unless you need to nest them (not possible) or export reports into excel (adds empty lines, at least in CR 9).</p>\n" }, { "answer_id": 2024293, "author": "Thstupit", "author_id": 245991, "author_profile": "https://Stackoverflow.com/users/245991", "pm_score": 3, "selected": false, "text": "<p>Crystal reports can't generate that commonly used SQL statement based on its links and report selection criteria. You have to use a \"command\" or build a view.</p>\n\n<p>In short, Crystal sucks. </p>\n" }, { "answer_id": 5824988, "author": "craig", "author_id": 134367, "author_profile": "https://Stackoverflow.com/users/134367", "pm_score": 0, "selected": false, "text": "<p>Adding </p>\n\n<pre><code>(Isnull({b.bar}) OR {b.bar} = \"foo\")\n</code></pre>\n\n<p>to the record-selection formula should act as you expect.</p>\n\n<p>** edit **</p>\n\n<p>A couple of other things to try:</p>\n\n<ul>\n<li>Use a different database driver--the native driver (that avoids ODBC) may act differently. I first noticed this using the WITH syntax--the SQL Server ODBC driver didn't work, but the SQL Server native driver did.</li>\n<li>While it sacrifices some flexibility, embed the query in a Command, assuming you can get the 3rd-party's product to comply. Added for completeness.</li>\n</ul>\n" }, { "answer_id": 13473350, "author": "nospamthanks", "author_id": 865435, "author_profile": "https://Stackoverflow.com/users/865435", "pm_score": 2, "selected": false, "text": "<p>Is a stored procedure an option for you? If so you could pre-select the data sets that way without having to resort to the command option, and one can import a stored procedure as one would a table.</p>\n\n<p>I would propose stored procedure which does <code>select * from b where bar= 'foo'</code> and join to that, such that the b table is pre-filtered so all you have to do is join on the other join field.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 14170596, "author": "nospamthanks", "author_id": 865435, "author_profile": "https://Stackoverflow.com/users/865435", "pm_score": 0, "selected": false, "text": "<p>Seems to me you don't want to accept anyone's suggestions but here's one last-ditch shot at it anyway. The solution I've used recently where the db has to remain intact is as follows:</p>\n\n<ol>\n<li>Set up Tomcat server so I can run some JSP and Hibernate goodness.</li>\n<li>Grab Crystal reports for eclipse</li>\n<li>Build report in crystal reports designer with faked data on a local db conforming to how I'd have the data in an ideal world</li>\n<li>Using java servlet pass List to each of the table aliases such that the report has the data replaced directly from POJOs. The POJOs can of course be entirely composed in the java by pulling in content from various db tables and mashing them up as you see fit, often enabling one to provide a thoroughly flattened dataset that Crystal reports is only too happy to work with.</li>\n</ol>\n" }, { "answer_id": 43273395, "author": "iMet", "author_id": 5268203, "author_profile": "https://Stackoverflow.com/users/5268203", "pm_score": 0, "selected": false, "text": "<p>You should not add filter condition for table b by <code>b.bar is null or b.bar = 'foo'</code>, but you should also not access attributes from table b directly. You should get all attributes by a condition <code>if b.bar = 'foo'</code> through a formula.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068/" ]
What I want to do is an outer join to a table, where I exclude records from the joined table based on matching a constant, however keep records from the main table. For example: ``` SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id AND b.bar = 'foo' ``` Expected results: ``` id other baz -- ---------- ------- 1 Has foo Include 2 Has none (null) 3 Has foobar (null) ``` I can't get the same results by putting it in the filter condition. If I use the following: ``` SELECT a.id, a.other, b.baz FROM a LEFT OUTER JOIN b ON a.id = b.id WHERE (b.bar IS NULL OR b.bar = 'foo') ``` I get these incorrect results: ``` id other baz -- -------- ------- 1 Has foo Include 2 Has none (null) ``` Where it excluded records of A that happen to match a record of B where bar = 'foobar'. I don't want that, I want A to be present, but B to be nulls in that case. Table B will have multiple records that need excluding, so I don't think I can filter this on the Crystal side without doing a lot of messing around to avoid problems from duplicate records from table A. I cannot use a SQL command object, as the third party application that we are running the reports from seems to choke on SQL command objects. I cannot use views, as our support contract does not permit database modifications, and our vendor considers adding views a database modification. I am working with Crystal Reports XI, specifically version 11.0.0.895. In case it makes a difference, I am running against a Progress 9.1E04 database using the SQL-92 ODBC driver. The sample tables and data used in the examples can be created with the following: ``` CREATE TABLE a (id INTEGER, other VARCHAR(32)); CREATE TABLE b (id INTEGER, bar VARCHAR(32), baz VARCHAR(32)); insert into A (id, other) values ('1', 'Has foo'); insert into A (id, other) values ('2', 'Has none'); insert into A (id, other) values ('3', 'Has foobar'); insert into B (id, bar, baz) values ('1', 'foo', 'Include'); insert into B (id, bar, baz) values ('1', 'foobar', 'Exclude'); insert into B (id, bar, baz) values ('1', 'another', 'Exclude'); insert into B (id, bar, baz) values ('1', 'More', 'Exclude'); insert into B (id, bar, baz) values ('3', 'foobar', 'Exclude'); ```
Crystal reports can't generate that commonly used SQL statement based on its links and report selection criteria. You have to use a "command" or build a view. In short, Crystal sucks.
226,302
<p>It seems safe to cast the result of my vector's <code>size()</code> function to an <code>unsigned int</code>. How can I tell for sure, though? My documentation isn't clear about how <code>size_type</code> is defined.</p>
[ { "answer_id": 226309, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>According to the standard, <em>you cannot be sure</em>. The exact type depends on your machine. You can look at the definition in your compiler's header implementations, though.</p>\n" }, { "answer_id": 226318, "author": "J Francis", "author_id": 19169, "author_profile": "https://Stackoverflow.com/users/19169", "pm_score": 0, "selected": false, "text": "<p>As long as you're sure that an unsigned int on your system will be large enough to hold the number of items you'll have in the vector you should be safe ;-)</p>\n" }, { "answer_id": 226363, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>I can't imagine that it wouldn't be safe on a 32-bit system, but 64-bit could be a problem (since ints remain 32 bit). To be safe, why not just declare your variable to be vector&lt;MyType>::size_type instead of unsigned int?</p>\n" }, { "answer_id": 226413, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": -1, "selected": false, "text": "<p>I'm not sure how well this will work because I'm just thinking off the top of my head, but a compile-time assertion (such as <code>BOOST_STATIC_ASSERT()</code> or see <a href=\"https://stackoverflow.com/questions/174356/ways-to-assert-expressions-at-build-time-in-c\">Ways to ASSERT expressions at build time in C</a>) might help. Something like:</p>\n\n<pre><code>BOOST_STATIC_ASSERT( sizeof( unsigned int) &gt;= sizeof( size_type));\n</code></pre>\n" }, { "answer_id": 226537, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 0, "selected": false, "text": "<p>It should always be safe to cast it to size_t. unsigned int isn't enough on most 64-bit systems, and even unsigned long isn't enough on Windows (which uses the LLP64 model instead of the LP64 model most Unix-like systems use).</p>\n" }, { "answer_id": 226575, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "<p>Do not assume the type of the container size (or anything else typed inside).</p>\n\n<h3>Today?</h3>\n\n<p>The best solution for now is to use:</p>\n\n<pre><code>std::vector&lt;T&gt;::size_type\n</code></pre>\n\n<p>Where T is your type. For example:</p>\n\n<pre><code>std::vector&lt;std::string&gt;::size_type i ;\nstd::vector&lt;int&gt;::size_type j ;\nstd::vector&lt;std::vector&lt;double&gt; &gt;::size_type k ;\n</code></pre>\n\n<p>(Using a typedef could help make this better to read)</p>\n\n<p>The same goes for iterators, and all other types \"inside\" STL containers.</p>\n\n<h3>After C++0x?</h3>\n\n<p>When the compiler will be able to find the type of the variable, you'll be able to use the auto keyword. For example:</p>\n\n<pre><code>void doSomething(const std::vector&lt;double&gt; &amp; p_aData)\n{\n std::vector&lt;double&gt;::size_type i = p_aData.size() ; // Old/Current way\n\n auto j = p_aData.size() ; // New C++0x way, definition\n decltype(p_aData.size()) k; // New C++0x way, declaration\n}\n</code></pre>\n\n<h3>Edit: Question from JF</h3>\n\n<blockquote>\n <blockquote>\n <p>What if he needs to pass the size of the container to some existing code that uses, say, an unsigned int? – JF</p>\n </blockquote>\n</blockquote>\n\n<p>This is a problem common to the use of the STL: You cannot do it without some work.</p>\n\n<p>The first solution is to design the code to always use the STL type. For example:</p>\n\n<pre><code>typedef std::vector&lt;int&gt;::size_type VIntSize ;\n\nVIntSize getIndexOfSomeItem(const std::vector&lt;int&gt; p_aInt)\n{\n return /* the found value, or some kind of std::npos */\n}\n</code></pre>\n\n<p>The second is to make the conversion yourself, using either a static_cast, using a function that will assert if the value goes out of bounds of the destination type (sometimes, I see code using \"char\" because, \"<em>you know, the index will never go beyond 256</em>\" [I quote from memory]).</p>\n\n<p>I believe this could be a full question in itself.</p>\n" }, { "answer_id": 227992, "author": "Don Wakefield", "author_id": 3778, "author_profile": "https://Stackoverflow.com/users/3778", "pm_score": 1, "selected": false, "text": "<p>The C++ standard only states that <em>size_t</em> is found in &lt;cstddef>, which puts the identifiers in &lt;stddef.h>. My copy of <a href=\"https://rads.stackoverflow.com/amzn/click/com/013089592X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Harbison &amp; Steele</a> places the minimum and maximum values for <em>size_t</em> in &lt;stdint.h>. That should give you a notion of how big your recipient variable needs to be for your platform.</p>\n\n<p>Your best bet is to stick with integer types that are large enough to hold a pointer on your platform. In C99, that'd be <em>intptr_t</em> and <em>uintptr_t</em>, also officially located in &lt;stdint.h>.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
It seems safe to cast the result of my vector's `size()` function to an `unsigned int`. How can I tell for sure, though? My documentation isn't clear about how `size_type` is defined.
Do not assume the type of the container size (or anything else typed inside). ### Today? The best solution for now is to use: ``` std::vector<T>::size_type ``` Where T is your type. For example: ``` std::vector<std::string>::size_type i ; std::vector<int>::size_type j ; std::vector<std::vector<double> >::size_type k ; ``` (Using a typedef could help make this better to read) The same goes for iterators, and all other types "inside" STL containers. ### After C++0x? When the compiler will be able to find the type of the variable, you'll be able to use the auto keyword. For example: ``` void doSomething(const std::vector<double> & p_aData) { std::vector<double>::size_type i = p_aData.size() ; // Old/Current way auto j = p_aData.size() ; // New C++0x way, definition decltype(p_aData.size()) k; // New C++0x way, declaration } ``` ### Edit: Question from JF > > > > > > What if he needs to pass the size of the container to some existing code that uses, say, an unsigned int? – JF > > > > > > > > > This is a problem common to the use of the STL: You cannot do it without some work. The first solution is to design the code to always use the STL type. For example: ``` typedef std::vector<int>::size_type VIntSize ; VIntSize getIndexOfSomeItem(const std::vector<int> p_aInt) { return /* the found value, or some kind of std::npos */ } ``` The second is to make the conversion yourself, using either a static\_cast, using a function that will assert if the value goes out of bounds of the destination type (sometimes, I see code using "char" because, "*you know, the index will never go beyond 256*" [I quote from memory]). I believe this could be a full question in itself.
226,315
<p>I'm using polar plots (POLAR(THETA,RHO)) in MATLAB.</p> <p>Is there an easy way to fix the range for the radial axis to say, 1.5?</p> <p>I'm looking for something analogous to the xlim, ylim commands for cartesian axes. Haven't found anything in the docs yet.</p>
[ { "answer_id": 226493, "author": "Tim Whitcomb", "author_id": 24895, "author_profile": "https://Stackoverflow.com/users/24895", "pm_score": 4, "selected": true, "text": "<p>Here's how I was able to do it. </p>\n\n<p>The MATLAB polar plot (if you look at the Handle Graphics options available) does not have anything like xlim or ylim. However, I realized that the first thing plotted sets the range, so I was able to plot a function with radius range [-.5 .5] on a [-1 1] plot as follows:</p>\n\n<pre><code>theta = linspace(0,2*pi,100);\nr = sin(2*theta) .* cos(2*theta);\nr_max = 1;\nh_fake = polar(theta,r_max*ones(size(theta)));\nhold on;\nh = polar(theta, r);\nset(h_fake, 'Visible', 'Off');\n</code></pre>\n\n<p>That doesn't look very good and hopefully there's a better way to do it, but it works.</p>\n" }, { "answer_id": 1358809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>this worked for me... i wanted the radius range to go to 30, so i first plotted this</p>\n\n<pre><code>polar(0,30,'-k')\nhold on\n</code></pre>\n\n<p>and then plotted what i was actually interested in. this first plotted point is hidden behind the grid marks. just make sure to include</p>\n\n<pre><code>hold off\n</code></pre>\n\n<p>after your final plotting command.</p>\n" }, { "answer_id": 1991143, "author": "CalPolyAero", "author_id": 242242, "author_profile": "https://Stackoverflow.com/users/242242", "pm_score": 2, "selected": false, "text": "<p>In case anyone else comes across this, here's <em>the</em> solution:</p>\n\n<p>As <strong><em>Scottie T</em></strong> and <strong><em>gnovice</em></strong> pointed out, Matlab basically uses the polar function as an interface for standard plots, but with alot of formatting behind the scenes to make it look polar. Look at the values of the XLim and YLim properties of a polar plot and you'll notice that they are literally the x and y limits of your plot in Cartesian coordinates. So, to set a radius limit, use xlim and ylim, or axis, and be smart about the values you set:</p>\n\n<pre><code>rlim = 10;\naxis([-1 1 -1 1]*rlim);\n</code></pre>\n\n<p>...that's all there is to it. Happy Matlabbing :)</p>\n" }, { "answer_id": 12380669, "author": "Ayesha Hakim", "author_id": 1664539, "author_profile": "https://Stackoverflow.com/users/1664539", "pm_score": 3, "selected": false, "text": "<p>Simple solution is to make a fake graph and set its color to white.</p>\n\n<pre><code>fake=100;\npolar(0,fake,'w');\nhold on;\n\nreal=10;\npolar(0,real,'w');\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20688/" ]
I'm using polar plots (POLAR(THETA,RHO)) in MATLAB. Is there an easy way to fix the range for the radial axis to say, 1.5? I'm looking for something analogous to the xlim, ylim commands for cartesian axes. Haven't found anything in the docs yet.
Here's how I was able to do it. The MATLAB polar plot (if you look at the Handle Graphics options available) does not have anything like xlim or ylim. However, I realized that the first thing plotted sets the range, so I was able to plot a function with radius range [-.5 .5] on a [-1 1] plot as follows: ``` theta = linspace(0,2*pi,100); r = sin(2*theta) .* cos(2*theta); r_max = 1; h_fake = polar(theta,r_max*ones(size(theta))); hold on; h = polar(theta, r); set(h_fake, 'Visible', 'Off'); ``` That doesn't look very good and hopefully there's a better way to do it, but it works.
226,354
<p>I'm trying to drag a <code>CALayer</code> in an iOS app.</p> <p>As soon as I change its position property it tries to animate to the new position and flickers all over the place:</p> <pre><code> layer.position = CGPointMake(x, y) </code></pre> <p>How can I move <code>CALayers</code> instantly? I can't seem to get my head around the Core Animation API.</p>
[ { "answer_id": 226761, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 8, "selected": true, "text": "<p>You want to wrap your call in the following:</p>\n\n<pre><code>[CATransaction begin]; \n[CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];\nlayer.position = CGPointMake(x, y);\n[CATransaction commit];\n</code></pre>\n" }, { "answer_id": 7409649, "author": "Biclops", "author_id": 465446, "author_profile": "https://Stackoverflow.com/users/465446", "pm_score": 5, "selected": false, "text": "<p>You can also use the convenience function </p>\n\n<pre><code>[CATransaction setDisableActions:YES] \n</code></pre>\n\n<p>as well.</p>\n\n<p>Note: Be sure to read the comments by Yogev Shelly to understand any gotchas that could occur.</p>\n" }, { "answer_id": 16381287, "author": "So Over It", "author_id": 423565, "author_profile": "https://Stackoverflow.com/users/423565", "pm_score": 4, "selected": false, "text": "<p>As others have suggested, you can use <code>CATransaction</code>.<br>\nThe problem comes arises because CALayer has a default implicit animation duration of 0.25 seconds.</p>\n\n<p>Thus, an easier (in my opinion) alternative to <code>setDisableActions</code> is to use <code>setAnimationDuration</code> with a value of <code>0.0</code>.</p>\n\n<pre><code>[CATransaction begin];\n[CATransaction setAnimationDuration:0.0];\nlayer.position = CGPointMake(x, y);\n[CATransaction commit];\n</code></pre>\n" }, { "answer_id": 33961937, "author": "CryingHippo", "author_id": 4720722, "author_profile": "https://Stackoverflow.com/users/4720722", "pm_score": 5, "selected": false, "text": "<p>Swift 3 Extension :</p>\n\n<pre><code>extension CALayer {\n class func performWithoutAnimation(_ actionsWithoutAnimation: () -&gt; Void){\n CATransaction.begin()\n CATransaction.setValue(true, forKey: kCATransactionDisableActions)\n actionsWithoutAnimation()\n CATransaction.commit()\n }\n}\n</code></pre>\n\n<p>Usage : </p>\n\n<pre><code>CALayer.performWithoutAnimation(){\n someLayer.position = newPosition\n}\n</code></pre>\n" }, { "answer_id": 53430084, "author": "Giles", "author_id": 978300, "author_profile": "https://Stackoverflow.com/users/978300", "pm_score": 3, "selected": false, "text": "<p>Combining previous answers here for Swift 4, to clearly make the animation duration explicit...</p>\n\n<pre><code>extension CALayer\n{\n class func perform(withDuration duration: Double, actions: () -&gt; Void) {\n CATransaction.begin()\n CATransaction.setAnimationDuration(duration)\n actions()\n CATransaction.commit()\n }\n}\n</code></pre>\n\n<p>Usage...</p>\n\n<pre><code>CALayer.perform(withDuration: 0.0) {\n aLayer.frame = aFrame\n }\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30420/" ]
I'm trying to drag a `CALayer` in an iOS app. As soon as I change its position property it tries to animate to the new position and flickers all over the place: ``` layer.position = CGPointMake(x, y) ``` How can I move `CALayers` instantly? I can't seem to get my head around the Core Animation API.
You want to wrap your call in the following: ``` [CATransaction begin]; [CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions]; layer.position = CGPointMake(x, y); [CATransaction commit]; ```
226,356
<p>I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone. I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time.</p> <p>I am using .NET 3.5 (thank god) but It's still baffling me.</p> <p>Thanks</p> <p>EDIT: Additional Information: This question was for use in a WPF application environment. The code snippet I left below took the answer example a step further to get exactly what I was looking for. </p>
[ { "answer_id": 226408, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>You can use DateTimeOffset to get the UTC offset so you shouldn't need to dig into the registry for that information.</p>\n\n<p>TimeZone.CurrentTimeZone returns additional time zone data, and TimeZoneInfo.Local has meta data about the time zone (such as whether it supports daylight savings, the names for its various states, etc).</p>\n\n<p>Update: I think this specifically answers your question:</p>\n\n<pre><code>var tzi = TimeZoneInfo.FindSystemTimeZoneById(\"Pacific Standard Time\");\nvar dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);\nConsole.WriteLine(dto);\nConsole.ReadLine();\n</code></pre>\n\n<p>That code creates a DateTime at -8 offset. The default installed time zones are <a href=\"http://msdn.microsoft.com/en-us/library/bb384272.aspx\" rel=\"nofollow noreferrer\">listed on MSDN</a>.</p>\n" }, { "answer_id": 227072, "author": "discorax", "author_id": 30408, "author_profile": "https://Stackoverflow.com/users/30408", "pm_score": 4, "selected": true, "text": "<p>Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide.</p>\n\n<pre><code>// _timeZoneId is the String value found in the System Registry.\n// You can look up the list of TimeZones on your system using this:\n// ReadOnlyCollection&lt;TimeZoneInfo&gt; current = TimeZoneInfo.GetSystemTimeZones();\n// As long as your _timeZoneId string is in the registry \n// the _now DateTime object will contain\n// the current time (adjusted for Daylight Savings Time) for that Time Zone.\nstring _timeZoneId = \"Pacific Standard Time\";\nDateTime startTime = DateTime.UtcNow;\nTimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);\n_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);\n</code></pre>\n\n<p>This is the code snippit I ended up with. Thanks for the help.</p>\n" }, { "answer_id": 5267140, "author": "CZahrobsky", "author_id": 888792, "author_profile": "https://Stackoverflow.com/users/888792", "pm_score": 1, "selected": false, "text": "<pre><code>//C#.NET\n public static bool IsDaylightSavingTime()\n {\n return IsDaylightSavingTime(DateTime.Now);\n }\n public static bool IsDaylightSavingTime(DateTime timeToCheck)\n {\n bool isDST = false;\n System.Globalization.DaylightTime changes \n = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year);\n if (timeToCheck &gt;= changes.Start &amp;&amp; timeToCheck &lt;= changes.End)\n {\n isDST = true;\n }\n return isDST;\n }\n\n\n'' VB.NET\nConst noDate As Date = #1/1/1950#\nPublic Shared Function IsDaylightSavingTime( _ \n Optional ByVal timeToCheck As Date = noDate) As Boolean\n Dim isDST As Boolean = False\n If timeToCheck = noDate Then timeToCheck = Date.Now\n Dim changes As DaylightTime = TimeZone.CurrentTimeZone _\n .GetDaylightChanges(timeToCheck.Year)\n If timeToCheck &gt;= changes.Start And timeToCheck &lt;= changes.End Then\n isDST = True\n End If\n Return isDST\nEnd Function\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30408/" ]
I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone. I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time. I am using .NET 3.5 (thank god) but It's still baffling me. Thanks EDIT: Additional Information: This question was for use in a WPF application environment. The code snippet I left below took the answer example a step further to get exactly what I was looking for.
Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide. ``` // _timeZoneId is the String value found in the System Registry. // You can look up the list of TimeZones on your system using this: // ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones(); // As long as your _timeZoneId string is in the registry // the _now DateTime object will contain // the current time (adjusted for Daylight Savings Time) for that Time Zone. string _timeZoneId = "Pacific Standard Time"; DateTime startTime = DateTime.UtcNow; TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId); _now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst); ``` This is the code snippit I ended up with. Thanks for the help.
226,365
<p>I have a UIImagePickerController as one view in a TabBar setup. Is it possible to tell the UIImagePickerController to not show the Cancel button in the top navigation bar when browsing photos libraries?</p>
[ { "answer_id": 226408, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 2, "selected": false, "text": "<p>You can use DateTimeOffset to get the UTC offset so you shouldn't need to dig into the registry for that information.</p>\n\n<p>TimeZone.CurrentTimeZone returns additional time zone data, and TimeZoneInfo.Local has meta data about the time zone (such as whether it supports daylight savings, the names for its various states, etc).</p>\n\n<p>Update: I think this specifically answers your question:</p>\n\n<pre><code>var tzi = TimeZoneInfo.FindSystemTimeZoneById(\"Pacific Standard Time\");\nvar dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);\nConsole.WriteLine(dto);\nConsole.ReadLine();\n</code></pre>\n\n<p>That code creates a DateTime at -8 offset. The default installed time zones are <a href=\"http://msdn.microsoft.com/en-us/library/bb384272.aspx\" rel=\"nofollow noreferrer\">listed on MSDN</a>.</p>\n" }, { "answer_id": 227072, "author": "discorax", "author_id": 30408, "author_profile": "https://Stackoverflow.com/users/30408", "pm_score": 4, "selected": true, "text": "<p>Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide.</p>\n\n<pre><code>// _timeZoneId is the String value found in the System Registry.\n// You can look up the list of TimeZones on your system using this:\n// ReadOnlyCollection&lt;TimeZoneInfo&gt; current = TimeZoneInfo.GetSystemTimeZones();\n// As long as your _timeZoneId string is in the registry \n// the _now DateTime object will contain\n// the current time (adjusted for Daylight Savings Time) for that Time Zone.\nstring _timeZoneId = \"Pacific Standard Time\";\nDateTime startTime = DateTime.UtcNow;\nTimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);\n_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);\n</code></pre>\n\n<p>This is the code snippit I ended up with. Thanks for the help.</p>\n" }, { "answer_id": 5267140, "author": "CZahrobsky", "author_id": 888792, "author_profile": "https://Stackoverflow.com/users/888792", "pm_score": 1, "selected": false, "text": "<pre><code>//C#.NET\n public static bool IsDaylightSavingTime()\n {\n return IsDaylightSavingTime(DateTime.Now);\n }\n public static bool IsDaylightSavingTime(DateTime timeToCheck)\n {\n bool isDST = false;\n System.Globalization.DaylightTime changes \n = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year);\n if (timeToCheck &gt;= changes.Start &amp;&amp; timeToCheck &lt;= changes.End)\n {\n isDST = true;\n }\n return isDST;\n }\n\n\n'' VB.NET\nConst noDate As Date = #1/1/1950#\nPublic Shared Function IsDaylightSavingTime( _ \n Optional ByVal timeToCheck As Date = noDate) As Boolean\n Dim isDST As Boolean = False\n If timeToCheck = noDate Then timeToCheck = Date.Now\n Dim changes As DaylightTime = TimeZone.CurrentTimeZone _\n .GetDaylightChanges(timeToCheck.Year)\n If timeToCheck &gt;= changes.Start And timeToCheck &lt;= changes.End Then\n isDST = True\n End If\n Return isDST\nEnd Function\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29263/" ]
I have a UIImagePickerController as one view in a TabBar setup. Is it possible to tell the UIImagePickerController to not show the Cancel button in the top navigation bar when browsing photos libraries?
Here is a code snippet in C# that I'm using in my WPF application. This will give you the current time (adjusted for Daylight Savings Time) for the time zone id you provide. ``` // _timeZoneId is the String value found in the System Registry. // You can look up the list of TimeZones on your system using this: // ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones(); // As long as your _timeZoneId string is in the registry // the _now DateTime object will contain // the current time (adjusted for Daylight Savings Time) for that Time Zone. string _timeZoneId = "Pacific Standard Time"; DateTime startTime = DateTime.UtcNow; TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId); _now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst); ``` This is the code snippit I ended up with. Thanks for the help.
226,382
<p>I have SQL query, which is working nice on Oracle and MSSQL. Now I'm trying this on PostgreSQL and it gives a strange exception: <code>org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "main"</code></p> <p>Here is the query: </p> <pre><code>SELECT * FROM "main" main INNER JOIN "something_link" something_link ON main."id" = something_link."mainid" INNER JOIN "something" somehting ON something_link."somethingid" = something."id" INNER JOIN "type" type ON something."typeid" = type."id" </code></pre> <p>This is quite simple query and I can't see why it is not working on Windows XP SP2, PostgreSQL 8.3?</p>
[ { "answer_id": 226497, "author": "l_39217_l", "author_id": 13633, "author_profile": "https://Stackoverflow.com/users/13633", "pm_score": 2, "selected": false, "text": "<p>somehting=>something</p>\n\n<pre>\n\npostgres=# create database test\npostgres-# ;\nCREATE DATABASE\n\npostgres=# \\c test\nYou are now connected to database \"test\".\n\ntest=# select version();\n version \n-----------------------------------------------------------------------------------------------\n PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)\n\ntest=# create table main(id int);\nCREATE TABLE\n\ntest=# create table something_link(mainid int);\nCREATE TABLE\n\ntest=# create table something(id int);\nCREATE TABLE\n\ntest=# create table type(id int);\nCREATE TABLE\n\ntest=# alter table something add column typeid int;\nALTER TABLE\n\ntest=# SELECT *\ntest-# FROM \"main\" main\ntest-# INNER JOIN \"something_link\" something_link ON main.\"id\" = something_link.\"mainid\"\ntest-# INNER JOIN \"something\" somehting ON something_link.\"somethingid\" = something.\"id\"\ntest-# INNER JOIN \"type\" type ON something.\"typeid\" = type.\"id\"\ntest-# ;\nERROR: column something_link.somethingid does not exist\nLINE 4: INNER JOIN \"something\" somehting ON something_link.\"som...\n ^\ntest=# alter table something_link add column somethingid int;\nALTER TABLE\n\ntest=# SELECT * \nFROM \"main\" main\n INNER JOIN \"something_link\" something_link ON main.\"id\" = something_link.\"mainid\"\n INNER JOIN \"something\" *somehting* ON something_link.\"somethingid\" = something.\"id\"\n INNER JOIN \"type\" type ON something.\"typeid\" = type.\"id\"\n;\n\nERROR: invalid reference to FROM-clause entry for table \"something\"\nLINE 4: ...hing\" somehting ON something_link.\"somethingid\" = something....\n ^\nHINT: Perhaps you meant to reference the table alias \"somehting\".\n\ntest=# SELECT *\nFROM \"main\" main\n INNER JOIN \"something_link\" something_link ON main.\"id\" = something_link.\"mainid\"\n INNER JOIN \"something\" something ON something_link.\"somethingid\" = something.\"id\"\n INNER JOIN \"type\" type ON something.\"typeid\" = type.\"id\"\n;\n\n id | mainid | somethingid | id | typeid | id \n\n----+--------+-------------+----+--------+----\n\n(0 rows)\n</pre>\n" }, { "answer_id": 226516, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>According to <a href=\"http://sql-info.de/en/postgresql/postgres-gotchas.html#1_5\" rel=\"nofollow noreferrer\">this</a>, seems like you either mistyped an alias or used a table name in place of it.</p>\n" }, { "answer_id": 228813, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": 2, "selected": false, "text": "<p>The real problem is actually not the query, but the PostgreSQL 8.3 default configuration.\nAfter correcting the spelling mistake (10x Kendrick Wilson), the problem persisted, until I edited the \"postgresql.conf\" file. There should be a line:</p>\n\n<pre><code>add_missing_from = on\n</code></pre>\n\n<p>This line ensures compatibility with the other SQL dialects.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
I have SQL query, which is working nice on Oracle and MSSQL. Now I'm trying this on PostgreSQL and it gives a strange exception: `org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "main"` Here is the query: ``` SELECT * FROM "main" main INNER JOIN "something_link" something_link ON main."id" = something_link."mainid" INNER JOIN "something" somehting ON something_link."somethingid" = something."id" INNER JOIN "type" type ON something."typeid" = type."id" ``` This is quite simple query and I can't see why it is not working on Windows XP SP2, PostgreSQL 8.3?
According to [this](http://sql-info.de/en/postgresql/postgres-gotchas.html#1_5), seems like you either mistyped an alias or used a table name in place of it.
226,392
<p>We have an intranet asp.net web application which uses the OOTB ASP.net membership and role providers. </p> <p>Now we are planning to expose the application to internet, by moving the web server to the DMZ as represented in the following (crappy) text diagram</p> <pre> External Internal internet --- Firewall --- Web server --- Firewall --- App Server --- Database DMZ Intranet </pre> <p>Now the problem is that the asp.net membership and role providers on the web server cant connect to the sql server because of the internal firewall.</p> <p>Have you ever faced such a scenario before? Will you recommend opening up ports in the internal firewall so that the webserver can directly connect to the SQL server? What other alternatives do I have (otherthan wring a custom provider myself)?</p>
[ { "answer_id": 226416, "author": "Chris Tybur", "author_id": 741, "author_profile": "https://Stackoverflow.com/users/741", "pm_score": 1, "selected": false, "text": "<p>We have a couple of Internet-facing web servers in a DMZ and had to open tunnels in our firewall back to the SQL server in our private network that they need to interact with. I think we used something other than port 1433 for the SQL connections. So far it's worked pretty well, i.e. no security breaches.</p>\n" }, { "answer_id": 227055, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 3, "selected": true, "text": "<p>Changing your DMZ policy and opening ports is usually REALLY hard. You might have better success doing what I did: expose a WCF service inside the network and communicate with it over HTTP on port 80.</p>\n\n<p>Zero friction with the LAN folks, and I just mimic the same exact (though crappy) API that .NET gives us :)</p>\n\n<p>Edit: to clarify, this means I have a RemoteRoleProvider that is configured like this:</p>\n\n<pre><code>&lt;roleManager enabled=\"true\" defaultProvider=\"RemoteRoleProvider\"&gt;\n &lt;providers&gt;\n &lt;add name=\"RemoteRoleProvider\" type=\"MyCorp.RemoteRoleProvider, MyCorp\" serviceUrl=\"http://some_internal_url/RoleProviderService.svc\" /&gt;\n &lt;/providers&gt;\n&lt;/roleManager&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747/" ]
We have an intranet asp.net web application which uses the OOTB ASP.net membership and role providers. Now we are planning to expose the application to internet, by moving the web server to the DMZ as represented in the following (crappy) text diagram ``` External Internal internet --- Firewall --- Web server --- Firewall --- App Server --- Database DMZ Intranet ``` Now the problem is that the asp.net membership and role providers on the web server cant connect to the sql server because of the internal firewall. Have you ever faced such a scenario before? Will you recommend opening up ports in the internal firewall so that the webserver can directly connect to the SQL server? What other alternatives do I have (otherthan wring a custom provider myself)?
Changing your DMZ policy and opening ports is usually REALLY hard. You might have better success doing what I did: expose a WCF service inside the network and communicate with it over HTTP on port 80. Zero friction with the LAN folks, and I just mimic the same exact (though crappy) API that .NET gives us :) Edit: to clarify, this means I have a RemoteRoleProvider that is configured like this: ``` <roleManager enabled="true" defaultProvider="RemoteRoleProvider"> <providers> <add name="RemoteRoleProvider" type="MyCorp.RemoteRoleProvider, MyCorp" serviceUrl="http://some_internal_url/RoleProviderService.svc" /> </providers> </roleManager> ```
226,405
<p>Anyone know how to get the position of a node using XPath?</p> <p>Say I have the following xml:</p> <pre><code>&lt;a&gt; &lt;b&gt;zyx&lt;/b&gt; &lt;b&gt;wvu&lt;/b&gt; &lt;b&gt;tsr&lt;/b&gt; &lt;b&gt;qpo&lt;/b&gt; &lt;/a&gt; </code></pre> <p>I can use the following xpath query to select the third &lt;b&gt; node (&lt;b&gt;tsr&lt;/b&gt;):</p> <pre><code>a/b[.='tsr'] </code></pre> <p>Which is all well and good but I want to <strong>return</strong> the ordinal position of that node, something like:</p> <pre><code>a/b[.='tsr']/position() </code></pre> <p>(but a bit more working!)</p> <p>Is it even possible?</p> <p><strong>edit</strong>: Forgot to mention am using .net 2 so it's xpath 1.0!</p> <hr /> <p><strong>Update</strong>: Ended up using <a href="https://stackoverflow.com/users/207/james-sulak">James Sulak</a>'s <a href="https://stackoverflow.com/questions/226405/find-position-of-a-node-using-xpath#227080">excellent answer</a>. For those that are interested here's my implementation in C#:</p> <pre><code>int position = doc.SelectNodes(&quot;a/b[.='tsr']/preceding-sibling::b&quot;).Count + 1; // Check the node actually exists if (position &gt; 1 || doc.SelectSingleNode(&quot;a/b[.='tsr']&quot;) != null) { Console.WriteLine(&quot;Found at position = {0}&quot;, position); } </code></pre>
[ { "answer_id": 226616, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 3, "selected": false, "text": "<p>You can do this with XSLT but I'm not sure about straight XPath.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?&gt;\n&lt;xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"&gt;\n &lt;xsl:output method=\"xml\" encoding=\"utf-8\" indent=\"yes\" \n omit-xml-declaration=\"yes\"/&gt;\n &lt;xsl:template match=\"a/*[text()='tsr']\"&gt;\n &lt;xsl:number value-of=\"position()\"/&gt;\n &lt;/xsl:template&gt;\n &lt;xsl:template match=\"text()\"/&gt;\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 227080, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 8, "selected": true, "text": "<p>Try:</p>\n\n<pre><code>count(a/b[.='tsr']/preceding-sibling::*)+1.\n</code></pre>\n" }, { "answer_id": 228932, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 0, "selected": false, "text": "<p>The problem is that the position of the node doesn't mean much without a context.</p>\n\n<p>The following code will give you the location of the node in its parent child nodes</p>\n\n<pre><code>using System;\nusing System.Xml;\n\npublic class XpathFinder\n{\n public static void Main(string[] args)\n {\n XmlDocument xmldoc = new XmlDocument();\n xmldoc.Load(args[0]);\n foreach ( XmlNode xn in xmldoc.SelectNodes(args[1]) )\n {\n for (int i = 0; i &lt; xn.ParentNode.ChildNodes.Count; i++)\n {\n if ( xn.ParentNode.ChildNodes[i].Equals( xn ) )\n {\n Console.Out.WriteLine( i );\n break;\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 285164, "author": "geoffc", "author_id": 32247, "author_profile": "https://Stackoverflow.com/users/32247", "pm_score": 0, "selected": false, "text": "<p>I do a lot of Novell Identity Manager stuff, and XPATH in that context looks a little different.</p>\n\n<p>Assume the value you are looking for is in a string variable, called TARGET, then the XPATH would be:</p>\n\n<pre><code>count(attr/value[.='$TARGET']/preceding-sibling::*)+1\n</code></pre>\n\n<p>Additionally it was pointed out that to save a few characters of space, the following would work as well:</p>\n\n<pre><code>count(attr/value[.='$TARGET']/preceding::*) + 1\n</code></pre>\n\n<p>I also posted a prettier version of this at Novell's Cool Solutions: <a href=\"http://www.novell.com/communities/node/6276/using-xpath-get-position-node-node-set\" rel=\"nofollow noreferrer\">Using XPATH to get the position node</a></p>\n" }, { "answer_id": 3409755, "author": "Damien", "author_id": 271887, "author_profile": "https://Stackoverflow.com/users/271887", "pm_score": 2, "selected": false, "text": "<p>Unlike stated previously 'preceding-sibling' is really the axis to use, not 'preceding' which does something completely different, it selects everything in the document that is before the start tag of the current node. (see <a href=\"http://www.w3schools.com/xpath/xpath_axes.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/xpath/xpath_axes.asp</a>)</p>\n" }, { "answer_id": 3437009, "author": "user414661", "author_id": 414661, "author_profile": "https://Stackoverflow.com/users/414661", "pm_score": 3, "selected": false, "text": "<p>I realize that the post is ancient.. but..</p>\n\n<p>replace'ing the asterisk with the nodename would give you better results</p>\n\n<pre><code>count(a/b[.='tsr']/preceding::a)+1.\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>count(a/b[.='tsr']/preceding::*)+1.\n</code></pre>\n" }, { "answer_id": 27173072, "author": "Claus Jensen", "author_id": 4300603, "author_profile": "https://Stackoverflow.com/users/4300603", "pm_score": 2, "selected": false, "text": "<p>Just a note to the answer done by James Sulak.</p>\n\n<p>If you want to take into consideration that the node may not exist and want to keep it purely XPATH, then try the following that will return 0 if the node does not exist.</p>\n\n<pre><code>count(a/b[.='tsr']/preceding-sibling::*)+number(boolean(a/b[.='tsr']))\n</code></pre>\n" }, { "answer_id": 32699932, "author": "CroWell", "author_id": 1400990, "author_profile": "https://Stackoverflow.com/users/1400990", "pm_score": 3, "selected": false, "text": "<p>If you ever upgrade to XPath 2.0, note that it provides function <a href=\"http://www.w3.org/TR/xpath-functions/#func-index-of\" rel=\"noreferrer\">index-of</a>, it solves problem this way:</p>\n\n<pre><code>index-of(//b, //b[.='tsr'])\n</code></pre>\n\n<p>Where:</p>\n\n<ul>\n<li>1st parameter is sequence for searching</li>\n<li>2nd is what to search</li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6124/" ]
Anyone know how to get the position of a node using XPath? Say I have the following xml: ``` <a> <b>zyx</b> <b>wvu</b> <b>tsr</b> <b>qpo</b> </a> ``` I can use the following xpath query to select the third <b> node (<b>tsr</b>): ``` a/b[.='tsr'] ``` Which is all well and good but I want to **return** the ordinal position of that node, something like: ``` a/b[.='tsr']/position() ``` (but a bit more working!) Is it even possible? **edit**: Forgot to mention am using .net 2 so it's xpath 1.0! --- **Update**: Ended up using [James Sulak](https://stackoverflow.com/users/207/james-sulak)'s [excellent answer](https://stackoverflow.com/questions/226405/find-position-of-a-node-using-xpath#227080). For those that are interested here's my implementation in C#: ``` int position = doc.SelectNodes("a/b[.='tsr']/preceding-sibling::b").Count + 1; // Check the node actually exists if (position > 1 || doc.SelectSingleNode("a/b[.='tsr']") != null) { Console.WriteLine("Found at position = {0}", position); } ```
Try: ``` count(a/b[.='tsr']/preceding-sibling::*)+1. ```
226,420
<p>Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method.</p> <p>I mean something like this:</p> <pre><code>[TriggersMyCustomAction()] public void DoSomeStuff() { } </code></pre> <p>I am totally clueless how to do it or if it possible at all, but <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx" rel="noreferrer">System.Diagnostic.ConditionalAttribute</a> might do a similar thing in the background. I am not sure though.</p> <p><strong>EDIT</strong>: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.</p>
[ { "answer_id": 226440, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 5, "selected": true, "text": "<p>The only way I know how to do this is with <a href=\"https://www.postsharp.net/\" rel=\"noreferrer\">PostSharp</a>. It post-processes your IL and can do things like what you asked for.</p>\n" }, { "answer_id": 226441, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 0, "selected": false, "text": "<p>I don't think there is a way to do it with just an attribute, but using <a href=\"http://www.codeproject.com/KB/cs/dynamicproxy.aspx\" rel=\"nofollow noreferrer\">proxy classes</a> and reflection you could have a class that knows to intercept instantiations of the classes in which you have attributed methods. </p>\n\n<p>Then the proxy class can trigger an event whenever the attributed methods are called.</p>\n" }, { "answer_id": 226446, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": 0, "selected": false, "text": "<p>An attribute gives information, they are metadata. I don't know of a way to do this offhand, someone might.</p>\n\n<p>You could look at partial methods in .NET which allow you to do some lightweight event handling. You provide the hooks and let someone else handle the implementation. If the method isn't implemented the compiler just ignores it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/wa80x488.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/wa80x488.aspx</a></p>\n" }, { "answer_id": 226472, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": false, "text": "<p>You need some sort of Aspect oriented framework. PostSharp will do it, as will <a href=\"http://castleproject.org/container\" rel=\"noreferrer\">Windsor</a>.</p>\n\n<p>Basically, they subclass your object and override this method...</p>\n\n<p>then it becomes:</p>\n\n<pre><code>//proxy\npublic override void DoSomeStuff()\n{\n if(MethodHasTriggerAttribute)\n Trigger();\n\n _innerClass.DoSomeStuff();\n}\n</code></pre>\n\n<p>of course all this is hidden to you. All you have to do is ask Windsor for the type, and it will do the proxying for you. The attribute becomes a (custom) facility I think in Windsor.</p>\n" }, { "answer_id": 226486, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "<p>You can use ContextBoundObject and IMessageSink. See <a href=\"http://msdn.microsoft.com/nb-no/magazine/cc301356(en-us).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/nb-no/magazine/cc301356(en-us).aspx</a></p>\n\n<p>Be warned that this approach has a severe performance impact compared with a direct method call.</p>\n" }, { "answer_id": 21461846, "author": "Matt", "author_id": 1016343, "author_profile": "https://Stackoverflow.com/users/1016343", "pm_score": 5, "selected": false, "text": "<p>\nThis concept is used in <strong><a href=\"http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework\" rel=\"nofollow noreferrer\">MVC</a> web applications.</strong> </p>\n\n<p>The <strong>.NET Framework 4.x</strong> provides several attributes which trigger actions, e.g.: <code>ExceptionFilterAttribute</code> (handling exceptions), <code>AuthorizeAttribute</code> (handling authorization). Both are defined in <code>System.Web.Http.Filters</code>.</p>\n\n<p>You could for instance define your own authorization attribute as follows:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class myAuthorizationAttribute : AuthorizeAttribute\n{\n protected override bool IsAuthorized(HttpActionContext actionContext)\n {\n // do any stuff here\n // it will be invoked when the decorated method is called\n if (CheckAuthorization(actionContext)) \n return true; // authorized\n else\n return false; // not authorized\n }\n\n}\n</code></pre>\n\n<p>Then, in your <strong>controller</strong> class you decorate the methods which are supposed to use your authorization as follows:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[myAuthorization]\npublic HttpResponseMessage Post(string id)\n{\n // ... your code goes here\n response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status\n return response;\n}\n</code></pre>\n\n<p>Whenever the <code>Post</code> method is invoked, it will call the <code>IsAuthorized</code> method inside the <code>myAuthorization</code> Attribute <em>before</em> the code inside the <code>Post</code> method is executed.</p>\n\n<p>If you return <code>false</code> in the <code>IsAuthorized</code> method, you signal that authorization is not granted and the execution of the method <code>Post</code> aborts.</p>\n\n<hr>\n\n<p>To understand how this works, let's look into a different example: The <strong><code>ExceptionFilter</code></strong>, which allows filtering exceptions by using attributes, the usage is similar as shown above for the <code>AuthorizeAttribute</code> (you can find a more detailed description about its usage <a href=\"https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>To use it, derive the <code>DivideByZeroExceptionFilter</code> class from the <code>ExceptionFilterAttribute</code> as shown <a href=\"http://blog.karbyn.com/articles/handling-errors-in-web-api-using-exception-filters-and-exception-handlers/\" rel=\"nofollow noreferrer\">here</a>, and override the method <code>OnException</code>: </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class DivideByZeroExceptionFilter : ExceptionFilterAttribute\n{\n public override void OnException(HttpActionExecutedContext actionExecutedContext)\n {\n if (actionExecutedContext.Exception is DivideByZeroException)\n {\n actionExecutedContext.Response = new HttpResponseMessage() { \n Content = new StringContent(\"A DIV error occured within the application.\",\n System.Text.Encoding.UTF8, \"text/plain\"), \n StatusCode = System.Net.HttpStatusCode.InternalServerError\n };\n }\n }\n}\n</code></pre>\n\n<p>Then use the following demo code to trigger it:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[DivideByZeroExceptionFilter]\npublic void Delete(int id)\n{\n // Just for demonstration purpose, it\n // causes the DivideByZeroExceptionFilter attribute to be triggered:\n throw new DivideByZeroException(); \n\n // (normally, you would have some code here that might throw \n // this exception if something goes wrong, and you want to make\n // sure it aborts properly in this case)\n}\n</code></pre>\n\n<p>Now that we know how it is used, we're mainly interested in the implementation. The following code is from the .NET Framework. It uses the interface <code>IExceptionFilter</code> internally as a contract:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace System.Web.Http.Filters\n{\n public interface IExceptionFilter : IFilter\n {\n // Executes an asynchronous exception filter.\n // Returns: An asynchronous exception filter.\n Task ExecuteExceptionFilterAsync(\n HttpActionExecutedContext actionExecutedContext, \n CancellationToken cancellationToken);\n }\n}\n</code></pre>\n\n<p>The <code>ExceptionFilterAttribute</code> itself is defined as follows:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>namespace System.Web.Http.Filters\n{\n // Represents the attributes for the exception filter.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, \n Inherited = true, AllowMultiple = true)]\n public abstract class ExceptionFilterAttribute : FilterAttribute, \n IExceptionFilter, IFilter\n {\n // Raises the exception event.\n // actionExecutedContext: The context for the action.\n public virtual void OnException(\n HttpActionExecutedContext actionExecutedContext)\n {\n }\n // Asynchronously executes the exception filter.\n // Returns: The result of the execution.\n Task IExceptionFilter.ExecuteExceptionFilterAsync(\n HttpActionExecutedContext actionExecutedContext, \n CancellationToken cancellationToken)\n {\n if (actionExecutedContext == null)\n {\n throw Error.ArgumentNull(\"actionExecutedContext\");\n }\n this.OnException(actionExecutedContext);\n return TaskHelpers.Completed();\n }\n }\n}\n</code></pre>\n\n<p>Inside <code>ExecuteExceptionFilterAsync</code>, the method <code>OnException</code> is called. Because you have overridden it as shown earlier, the error can now be handled by your own code.</p>\n\n<hr>\n\n<p>There is also a commercial product available as mentioned in OwenP's answer, <a href=\"http://www.postsharp.net/\" rel=\"nofollow noreferrer\">PostSharp</a>, which allows you to do that easily. <a href=\"http://doc.postsharp.net/method-interception#intercepting-method\" rel=\"nofollow noreferrer\">Here</a> is an example how you can do that with PostSharp. Note that there is an Express edition available which you can use for free even for commercial projects.</p>\n\n<p><strong>PostSharp Example</strong> (see the link above for full description):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class CustomerService\n{\n [RetryOnException(MaxRetries = 5)]\n public void Save(Customer customer)\n {\n // Database or web-service call.\n }\n}\n</code></pre>\n\n<p>Here the attribute specifies that the <code>Save</code> method is called up to 5 times if an exception occurs. The following code defines this custom attribute:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>[PSerializable]\npublic class RetryOnExceptionAttribute : MethodInterceptionAspect\n{\n public RetryOnExceptionAttribute()\n {\n this.MaxRetries = 3;\n }\n\n public int MaxRetries { get; set; }\n\n public override void OnInvoke(MethodInterceptionArgs args)\n {\n int retriesCounter = 0;\n\n while (true)\n {\n try\n {\n args.Proceed();\n return;\n }\n catch (Exception e)\n {\n retriesCounter++;\n if (retriesCounter &gt; this.MaxRetries) throw;\n\n Console.WriteLine(\n \"Exception during attempt {0} of calling method {1}.{2}: {3}\",\n retriesCounter, args.Method.DeclaringType, args.Method.Name, e.Message);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 50222029, "author": "balintn", "author_id": 6104083, "author_profile": "https://Stackoverflow.com/users/6104083", "pm_score": 0, "selected": false, "text": "<p>You might take a look at the poor man's solution: see the decorator pattern.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8954/" ]
Is there a way in C# or .NET in general to create an attribute on a method which triggers an event when the method is invoked? Ideally, I would be able to run custom actions before and after the invocation of the method. I mean something like this: ``` [TriggersMyCustomAction()] public void DoSomeStuff() { } ``` I am totally clueless how to do it or if it possible at all, but [System.Diagnostic.ConditionalAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx) might do a similar thing in the background. I am not sure though. **EDIT**: I forgot to mention that due to the circumstances of my specific case, performance is not really an issue.
The only way I know how to do this is with [PostSharp](https://www.postsharp.net/). It post-processes your IL and can do things like what you asked for.
226,436
<p>I have a custom control that exposes a property. When I set it using a fixed value, everything works correctly. But if I try to set its value using the &lt;%= %> tags, it goes a little whacky:</p> <pre><code>&lt;cc:CustomControl ID="CustomControl" runat="server" Property1='&lt;%= MyProperty %&gt;' /&gt; &lt;%= MyProperty %&gt; </code></pre> <p>When this gets rendered, the &lt;%= MyProperty %> tag underneat the custom control is rendered as I expect (with the value of MyProperty). However, when I step into the Render function of the CustomControl, the value for Property1 is literally the string "&lt;%= MyProperty %>" instead of the actual underlying value of MyProperty.</p>
[ { "answer_id": 226452, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>Try &lt;%# MyProperty %> in the CustomControl and see if that works.</p>\n" }, { "answer_id": 226483, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 3, "selected": true, "text": "<p>You control is initialized from the markup during <code>OnInit</code>. So if that syntax worked, it wouldn't have the effect you wanted anyway, since <code>MyProperty</code> would be evaluated during <code>OnInit</code> and not at render time (like it is with the second usage).</p>\n\n<p>You want to use the data binding syntax instead:</p>\n\n<pre><code>&lt;cc:CustomControl ID=\"CustomControl\" runat=\"server\" Property1='&lt;%# MyProperty %&gt;' /&gt;\n</code></pre>\n\n<p>Just make sure to call <code>DataBind()</code> on the container (Page, UserControl, etc).</p>\n\n<p>Alternatively, you can set the property in your code behind:</p>\n\n<pre><code>CustomControl.Property1 = MyProperty;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
I have a custom control that exposes a property. When I set it using a fixed value, everything works correctly. But if I try to set its value using the <%= %> tags, it goes a little whacky: ``` <cc:CustomControl ID="CustomControl" runat="server" Property1='<%= MyProperty %>' /> <%= MyProperty %> ``` When this gets rendered, the <%= MyProperty %> tag underneat the custom control is rendered as I expect (with the value of MyProperty). However, when I step into the Render function of the CustomControl, the value for Property1 is literally the string "<%= MyProperty %>" instead of the actual underlying value of MyProperty.
You control is initialized from the markup during `OnInit`. So if that syntax worked, it wouldn't have the effect you wanted anyway, since `MyProperty` would be evaluated during `OnInit` and not at render time (like it is with the second usage). You want to use the data binding syntax instead: ``` <cc:CustomControl ID="CustomControl" runat="server" Property1='<%# MyProperty %>' /> ``` Just make sure to call `DataBind()` on the container (Page, UserControl, etc). Alternatively, you can set the property in your code behind: ``` CustomControl.Property1 = MyProperty; ```
226,445
<p>As every Haxe developer knows, you could use <code>haxe.Timer.delayed()</code> to delay function call for some time. But this function doesn't exist for Neko at all. Is there a way to achieve the same results?</p>
[ { "answer_id": 226489, "author": "vava", "author_id": 6258, "author_profile": "https://Stackoverflow.com/users/6258", "pm_score": 3, "selected": true, "text": "<p>Have to check it first but </p>\n\n<pre><code>function delayed(f, time) {\n neko.vm.Thread.create(function() {\n neko.Sys.sleep(time);\n f();\n });\n}\n</code></pre>\n\n<p>might be the closest thing possible. The only cons is that application becomes multi threaded which could lead to serious problems.</p>\n" }, { "answer_id": 269643, "author": "Michael Pliskin", "author_id": 9777, "author_profile": "https://Stackoverflow.com/users/9777", "pm_score": 0, "selected": false, "text": "<p>Yes I don't know anything except for what you mention in your first answer. On Linux you can use SIGALARM - but this doesn't look trivial, 100% pure C code, and needs to be handled with great care to avoid crashing the VM.</p>\n" }, { "answer_id": 2861163, "author": "Tom", "author_id": 45974, "author_profile": "https://Stackoverflow.com/users/45974", "pm_score": 1, "selected": false, "text": "<p>I thought about your issue and I think the best way is to create your own Timer class for Neko. I made a Timer class for you:</p>\n\n<p><em>NekoTimer.hx</em></p>\n\n<pre><code>package;\nimport neko.Sys;\n\n class NekoTimer \n {\n private static var threadActive:Bool = false;\n private static var timersList:Array&lt;TimerInfo&gt; = new Array&lt;TimerInfo&gt;();\n private static var timerInterval:Float = 0.1;\n\n public static function addTimer(interval:Int, callMethod:Void-&gt;Void):Int\n {\n //setup timer thread if not yet active\n if (!threadActive) setupTimerThread();\n\n //add the given timer\n return timersList.push(new TimerInfo(interval, callMethod, Sys.time() * 1000)) - 1;\n }\n\n public static function delTimer(id:Int):Void\n {\n timersList.splice(id, 1);\n }\n\n private static function setupTimerThread():Void\n {\n threadActive = true;\n neko.vm.Thread.create(function() {\n while (true) {\n Sys.sleep(timerInterval);\n for (timer in timersList) {\n if (Sys.time() * 1000 - timer.lastCallTimestamp &gt;= timer.interval) {\n timer.callMethod();\n timer.lastCallTimestamp = Sys.time() * 1000;\n }\n }\n }\n });\n }\n}\n\nprivate class TimerInfo\n{\n public var interval:Int;\n public var callMethod:Void-&gt;Void;\n public var lastCallTimestamp:Float;\n\n public function new(interval:Int, callMethod:Void-&gt;Void, lastCallTimestamp:Float) {\n this.interval = interval;\n this.callMethod = callMethod;\n this.lastCallTimestamp = lastCallTimestamp;\n }\n}\n</code></pre>\n\n<p>Call it like this:</p>\n\n<pre><code>package ;\n\nimport neko.Lib;\n\nclass Main \n{\n private var timerId:Int;\n\n public function new()\n {\n trace(\"setting up timer...\");\n timerId = NekoTimer.addTimer(5000, timerCallback);\n trace(timerId);\n\n //idle main app\n while (true) { }\n }\n\n private function timerCallback():Void\n {\n trace(\"it's now 5 seconds later\");\n NekoTimer.delTimer(timerId);\n trace(\"removed timer\");\n }\n\n //neko constructor\n static function main() \n {\n new Main();\n }\n}\n</code></pre>\n\n<p>Hope that helps.</p>\n\n<p>Note: this one has an accuracy of 100ms. You can increase this by decreasing the timerInterval setting.</p>\n" }, { "answer_id": 20688200, "author": "Raul", "author_id": 3120179, "author_profile": "https://Stackoverflow.com/users/3120179", "pm_score": 1, "selected": false, "text": "<p>I used the class as well, and I found one issue. Because is not completely realtime, it sleeps the interval, calls the function, and sleeps the interval again. So, depending on how long the function you are running takes, it ticks slower or faster.</p>\n\n<p>I've solved it by replacing line 39 like so:</p>\n\n<pre><code>//timer.lastCallTimestamp = Sys.time() * 1000;\ntimer.lastCallTimestamp = timer.lastCallTimestamp + timer.interval;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6258/" ]
As every Haxe developer knows, you could use `haxe.Timer.delayed()` to delay function call for some time. But this function doesn't exist for Neko at all. Is there a way to achieve the same results?
Have to check it first but ``` function delayed(f, time) { neko.vm.Thread.create(function() { neko.Sys.sleep(time); f(); }); } ``` might be the closest thing possible. The only cons is that application becomes multi threaded which could lead to serious problems.
226,455
<p>Someone at work just asked for the reasoning behind having to wrap a wait inside a synchronized.</p> <p>Honestly I can't see the reasoning. I understand what the javadocs say--that the thread needs to be the owner of the object's monitor, but why? What problems does it prevent? (And if it's actually necessary, why can't the wait method get the monitor itself?)</p> <p>I'm looking for a fairly in-depth why or maybe a reference to an article. I couldn't find one in a quick google.</p> <p>Oh, also, how does thread.sleep compare?</p> <p>edit: Great set of answers--I really wish I could select more than one because they all helped me understand what was going on.</p>
[ { "answer_id": 226479, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 4, "selected": true, "text": "<p>If the object does not own the object monitor when it calls Object.wait(), it will not be able to access the object to setup a notify listener until the the monitor is released. Instead, it will be treated as a thread attempting to access a method on a synchronized object.</p>\n\n<p>Or to put it another way, there is no difference between:</p>\n\n<pre><code>public void doStuffOnThisObject()\n</code></pre>\n\n<p>and the following method:</p>\n\n<pre><code>public void wait()\n</code></pre>\n\n<p>Both methods will be blocked until the object monitor is released. This is a feature in Java to prevent the state of an object from being updated by more than one thread. It simply has unintended consequences on the wait() method.</p>\n\n<p>Presumably, the wait() method is not synchronized because that could create situations where the Thread has multiple locks on the object. (See <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/memory.html#61803\" rel=\"noreferrer\">Java Language Specifications/Locking</a> for more info on this.) Multiple locks are a problem because the wait() method will only undo one lock. If the method were synchronized, it would guarantee that only the method's lock would be undone while still leaving a potential outer lock undone. This would create a deadlock condition in the code.</p>\n\n<p>To answer your question on Thread.sleep(), Thread.sleep() does not guarantee that whatever condition you are waiting on has been met. Using Object.wait() and Object.notify() allows a programmer to manually implement blocking. The threads will unblock once a notify is sent that a condition has been met. e.g. A read from disk has finished and data can be processed by the thread. Thread.sleep() would require the programmer to poll if the condition has been met, then fall back to sleep if it has not.</p>\n" }, { "answer_id": 226622, "author": "Robin", "author_id": 21925, "author_profile": "https://Stackoverflow.com/users/21925", "pm_score": 3, "selected": false, "text": "<p>It needs to own the monitor, since the purpose of the wait() is to release the monitor and let other threads obtain the monitor to do processing of their own. The purpose of these methods (wait/notify) is to coordinate access to synchronized code blocks between two threads that require each other to perform some functionality. It is not simply a matter of making sure access to a data structure is threadsafe, but to coordinate events between multiple threads.</p>\n\n<p>A classic example would be a producer/consumer case where one thread pushes data to a queue, and another thread consumes the data. The consuming thread would always require the monitor to access the queue, but would release the monitor once the queue is empty. The producer thread would then only get access to write to the thread when the consumer is no longer processing. It would notify the consumer thread once it has pushed more data into the queue, so it can regain the monitor and access the queue again.</p>\n" }, { "answer_id": 226644, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>Wait gives up the monitor, so you must have it to give it up. Notify must have the monitor as well.</p>\n\n<p>The main reason why you want to do this is to ensure that you have the monitor when you come back from wait() -- typically, you are using the wait/notify protocol to protect some shared resource and you want it to be safe to touch it when wait returns. The same with notify -- usually you are changing something and then calling notify() -- you want to have the monitor, make changes, and call notify().</p>\n\n<p>If you made a function like this:</p>\n\n<pre><code>public void synchWait() {\n syncronized { wait(); }\n}\n</code></pre>\n\n<p>You would not have the monitor when wait returned -- you could get it, but you might not get it next.</p>\n" }, { "answer_id": 226672, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 2, "selected": false, "text": "<p>Here's my understanding on why the restriction is actually a requirement. I'm basing this on a C++ monitor implementation I made a while back by combining a mutex and a condition variable. </p>\n\n<p>In a <em>mutex+condition_variable=monitor</em> system, the <a href=\"http://www.opengroup.org/onlinepubs/007908775/xsh/pthread_cond_wait.html\" rel=\"nofollow noreferrer\">wait</a> call sets the condition variable into a wait state and releases the mutex. The condition variable is shared state, so it needs to be locked to avoid race conditions between threads that want to wait and threads that want to notify. Instead of introducing yet another mutex to lock its state, the existing mutex is used. In Java, the mutex is correctly locked when the about-to-wait thread owns the monitor.</p>\n" }, { "answer_id": 227120, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": false, "text": "<p>Lots of good answers here already. But just want to mention here that the other MUST DO when using wait() is to do it in a loop dependent on the condition you are waiting for in case you are seeing spurious wakeups, which in my experience do happen.</p>\n\n<p>To wait for some other thread to change a condition to true and notify:</p>\n\n<pre><code>synchronized(o) {\n while(! checkCondition()) {\n o.wait();\n }\n}\n</code></pre>\n\n<p>Of course, these days, I'd recommend just using the new Condition object as it is clearer and has more features (like allowing multiple conditions per lock, being able to check wait queue length, more flexible schedule/interrupt, etc).</p>\n\n<pre><code> Lock lock = new ReentrantLock();\n Condition condition = lock.newCondition();\n lock.lock();\n try {\n while (! checkCondition()) {\n condition.await();\n }\n } finally {\n lock.unlock();\n }\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 1169781, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Mostly wait is done if there is a condition say a queue is empty. </p>\n\n<pre><code>If(queue is empty)\n queue.wait();\n</code></pre>\n\n<p>Let us assume the queue is empty.\nIn case if the current thread pre-empts after checking the queue, then if another\nthread adds few elements to queue, the current thread will not know and will go for wait\nstate. Thats wrong.\nSo we should have something like</p>\n\n<pre><code>Synchornized(queue)\n{\n if(queue is empty)\n queue.wait();\n}\n</code></pre>\n\n<p>Now let us consider what if they made wait itself as synchronized. As already mentioned in one of the comments, it releases only one lock. That means if wait() was synchronized in the above code only one lock would have been released. Implies that current thread will go for wait with the lock for the queue.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12943/" ]
Someone at work just asked for the reasoning behind having to wrap a wait inside a synchronized. Honestly I can't see the reasoning. I understand what the javadocs say--that the thread needs to be the owner of the object's monitor, but why? What problems does it prevent? (And if it's actually necessary, why can't the wait method get the monitor itself?) I'm looking for a fairly in-depth why or maybe a reference to an article. I couldn't find one in a quick google. Oh, also, how does thread.sleep compare? edit: Great set of answers--I really wish I could select more than one because they all helped me understand what was going on.
If the object does not own the object monitor when it calls Object.wait(), it will not be able to access the object to setup a notify listener until the the monitor is released. Instead, it will be treated as a thread attempting to access a method on a synchronized object. Or to put it another way, there is no difference between: ``` public void doStuffOnThisObject() ``` and the following method: ``` public void wait() ``` Both methods will be blocked until the object monitor is released. This is a feature in Java to prevent the state of an object from being updated by more than one thread. It simply has unintended consequences on the wait() method. Presumably, the wait() method is not synchronized because that could create situations where the Thread has multiple locks on the object. (See [Java Language Specifications/Locking](http://java.sun.com/docs/books/jls/third_edition/html/memory.html#61803) for more info on this.) Multiple locks are a problem because the wait() method will only undo one lock. If the method were synchronized, it would guarantee that only the method's lock would be undone while still leaving a potential outer lock undone. This would create a deadlock condition in the code. To answer your question on Thread.sleep(), Thread.sleep() does not guarantee that whatever condition you are waiting on has been met. Using Object.wait() and Object.notify() allows a programmer to manually implement blocking. The threads will unblock once a notify is sent that a condition has been met. e.g. A read from disk has finished and data can be processed by the thread. Thread.sleep() would require the programmer to poll if the condition has been met, then fall back to sleep if it has not.
226,460
<p>I am trying to write a query for SQL Server 2005 but I can't figure out how to do it. I have a table with the following fields:</p> <p><strong>MessageID int<br/> CategoryID int<br/> Priority tinyint<br/> MessageText NVARCHAR(MAX)<br/></strong></p> <p>I need a query that will return * for each row that has the highest priority within a Category. For example, if I had the following data:</p> <p><strong>MessageID, CategoryID, Priority, MessageText</strong><br/> 1, 100, 1, Error #1234 occurred<br/> 2, 100, 2, Error #243 occurred<br/> 3, 100, 3, Error #976 occurred<br/> 4, 200, 4, Error #194 occurred<br/> 5, 200, 1, Error #736 occurred<br/> 6, 300, 3, Error #54 occurred<br/> 7, 300, 2, Error #888 occurred<br/></p> <p>then the result would be:</p> <p><strong>MessageID, CategoryID, Priority, MessageText</strong><br/> 3, 100, 3, Error #976 occurred<br/> 4, 200, 4, Error #194 occurred<br/> 6, 300, 3, Error #54 occurred<br/></p> <p>Notice that it returns one row per category, and that it is the row which had the highest priority for that Category.</p> <p>Can anyone tell me how I can write this query?</p>
[ { "answer_id": 226490, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 1, "selected": false, "text": "<p>I believe that this should work, table name assumed as Messages</p>\n\n<pre><code>SELECT\n M.MessageId,\n M.CategoryId,\n M.Priority,\n M.MessageText\nFROM \n(\n SELECT \n CategoryId,\n MAX(Priority) AS Priority\n FROM Messages\n GROUP BY CategoryId\n) AS MaxValues\n INNER JOIN Messages M\n ON (MaxValues.CategoryId = M.CategoryId\n AND MaxValues.Priority = M.Priority)\n</code></pre>\n\n<p><strong>NOTE</strong></p>\n\n<p>The only \"gotcha\" in this method is that if you have more than one max priority...</p>\n" }, { "answer_id": 226522, "author": "databyss", "author_id": 9094, "author_profile": "https://Stackoverflow.com/users/9094", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT\n Messages.MessageID\n , Messages.CategoryID\n , Messages.Priority\n , Messages. MessageText\nFROM\n Messages\n INNER JOIN\n (\n SELECT \n CategoryID\n , MAX(Priority) AS Priority\n FROM \n Messages\n GROUP BY\n CategoryID\n ) AS MaxResults\n ON\n (\n Messages.CategoryID = MaxResults.CategoryID\n AND\n Messages.Priority = MaxResults.Priority\n )\n</code></pre>\n\n<p>It looks like this is basically the same answer given above... with the same Caveat.</p>\n\n<p>Although this one will work right off the bat.</p>\n" }, { "answer_id": 226527, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 4, "selected": true, "text": "<p>Verified:</p>\n\n<pre><code>SELECT\n highest_priority_messages.*\nFROM\n(\n SELECT\n m.MessageID\n , m.CategoryID\n , m.Priority\n , m.MessageText\n , Rank() OVER \n (PARTITION BY m.CategoryID ORDER BY m.Priority DESC) AS p_rank\n FROM [Message] m\n GROUP BY \n m.CategoryID \n , m.Priority\n , m.MessageID\n , m.MessageText\n) highest_priority_messages\nWHERE \n p_rank = 1\n</code></pre>\n" }, { "answer_id": 226617, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>This is shorter and easier to read (imo).</p>\n\n<pre><code>select ms.*\nfrom \n messages ms\n ,(\n select ms1.categoryid, max(ms1.priority) as max_priority\n from messages ms1\n group by ms1.categoryid\n ) tmp\nwhere ms.categoryid = tmp.categoryid\n and ms.priority = tmp.max_priority;\n</code></pre>\n" }, { "answer_id": 227404, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>If you'd like to do it without all of the subqueries:</p>\n\n<pre><code>SELECT\n MessageID,\n CategoryID,\n Priority,\n MessageText\nFROM\n dbo.Messages M1\nLEFT OUTER JOIN dbo.Messages M2 ON\n M2.CategoryID = M1.CategoryID AND\n M2.Priority &gt; M1.Priority\nWHERE\n M2.MessageID IS NULL\n</code></pre>\n\n<p>You might have to adjust the query depending on how you want to handle ties. You didn't have any such examples, so I wasn't sure.</p>\n" }, { "answer_id": 227742, "author": "Jeff", "author_id": 5685, "author_profile": "https://Stackoverflow.com/users/5685", "pm_score": 0, "selected": false, "text": "<p>I'm not quite high enough rank (yet) to post a comment, so I'd like to add to cfeduke's solution:</p>\n\n<pre><code>SELECT\n highest_priority_messages.*\nFROM\n(\n SELECT\n m.MessageID\n , m.CategoryID\n , m.Priority\n , m.MessageText\n , Rank() OVER \n (PARTITION BY m.CategoryID ORDER BY m.Priority DESC, m.MessageID DESC) AS p_rank\n FROM [Message] m\n GROUP BY \n m.CategoryID \n , m.Priority\n , m.MessageID\n , m.MessageText\n) highest_priority_messages\nWHERE \n p_rank = 1\n</code></pre>\n\n<p>If you add another CategoryID 100 Message with Priority 3, the original solution would bring back 2 rows, by adding another order condition we eliminate the chance of two items ranking the same.</p>\n\n<p>Here's a copy of the row I inserted to test this.</p>\n\n<pre><code>insert into [Message] (MessageID, CategoryID, Priority, MessageText)\nselect 8, 100, 3, 'Error #976-2 occurred'\n</code></pre>\n" }, { "answer_id": 4002209, "author": "Raj", "author_id": 484825, "author_profile": "https://Stackoverflow.com/users/484825", "pm_score": 1, "selected": false, "text": "<pre><code>select distinct query1.* from\n\n(select categoryId,msgText,max(priorityId) as MAX_PRIORITY\n from message\n group by categoryId,msgText\n order by categoryId\n) query1,\n\n\n(select categoryId,max(priorityId) as MAX_PRIORITY\n from message\n group by categoryId\n order by categoryId\n) query2\n\nwhere query1.MAX_PRIORITY = query2.MAX_PRIORITY\n\norder by query1.categoryId\n</code></pre>\n" }, { "answer_id": 8132344, "author": "Kamy", "author_id": 1027052, "author_profile": "https://Stackoverflow.com/users/1027052", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT DISTINCT CategoryId,PS.Priority,MessageID,MessageText\nFROM Priority_Scene PS\nJOIN (SELECT MAX(Priority) AS Priority FROM Priority_Scene GROUP BY CategoryId) A\nON A.Priority = PS.Priority\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I am trying to write a query for SQL Server 2005 but I can't figure out how to do it. I have a table with the following fields: **MessageID int CategoryID int Priority tinyint MessageText NVARCHAR(MAX)** I need a query that will return \* for each row that has the highest priority within a Category. For example, if I had the following data: **MessageID, CategoryID, Priority, MessageText** 1, 100, 1, Error #1234 occurred 2, 100, 2, Error #243 occurred 3, 100, 3, Error #976 occurred 4, 200, 4, Error #194 occurred 5, 200, 1, Error #736 occurred 6, 300, 3, Error #54 occurred 7, 300, 2, Error #888 occurred then the result would be: **MessageID, CategoryID, Priority, MessageText** 3, 100, 3, Error #976 occurred 4, 200, 4, Error #194 occurred 6, 300, 3, Error #54 occurred Notice that it returns one row per category, and that it is the row which had the highest priority for that Category. Can anyone tell me how I can write this query?
Verified: ``` SELECT highest_priority_messages.* FROM ( SELECT m.MessageID , m.CategoryID , m.Priority , m.MessageText , Rank() OVER (PARTITION BY m.CategoryID ORDER BY m.Priority DESC) AS p_rank FROM [Message] m GROUP BY m.CategoryID , m.Priority , m.MessageID , m.MessageText ) highest_priority_messages WHERE p_rank = 1 ```
226,465
<p>Here's a silly fun question:</p> <p>Let's say we have to perform a simple operation where we need half of the value of a variable. There are <em>typically</em> two ways of doing this:</p> <pre><code>y = x / 2.0; // or... y = x * 0.5; </code></pre> <p>Assuming we're using the standard operators provided with the language, which one has better performance?</p> <p>I'm guessing multiplication is typically better so I try to stick to that when I code, but I would like to confirm this. </p> <p>Although personally I'm interested in the answer for <strong>Python</strong> 2.4-2.5, feel free to also post an answer for other languages! And if you'd like, feel free to post other fancier ways (like using bitwise shift operators) as well.</p>
[ { "answer_id": 226494, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 2, "selected": false, "text": "<p>I have always learned that multiplication is more efficient.</p>\n" }, { "answer_id": 226502, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 2, "selected": false, "text": "<p>If you are working with integers or non floating point types don't forget your bitshifting operators: &lt;&lt; >> </p>\n\n<pre><code> int y = 10;\n y = y &gt;&gt; 1;\n Console.WriteLine(\"value halved: \" + y);\n y = y &lt;&lt; 1;\n Console.WriteLine(\"now value doubled: \" + y);\n</code></pre>\n" }, { "answer_id": 226504, "author": "Dan Hewett", "author_id": 17975, "author_profile": "https://Stackoverflow.com/users/17975", "pm_score": 2, "selected": false, "text": "<p>Multiplication is usually faster - certainly never slower.\nHowever, if it is not speed critical, write whichever is clearest.</p>\n" }, { "answer_id": 226507, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 6, "selected": false, "text": "<p>I think this is getting so nitpicky that you would be better off doing whatever makes the code more readable. Unless you perform the operations thousands, if not millions, of times, I doubt anyone will ever notice the difference.</p>\n\n<p>If you really have to make the choice, benchmarking is the only way to go. Find what function(s) are giving you problems, then find out where in the function the problems occur, and fix those sections. However, I still doubt that a single mathematical operation (even one repeated many, many times) would be a cause of any bottleneck.</p>\n" }, { "answer_id": 226508, "author": "Christopher Lightfoot", "author_id": 24525, "author_profile": "https://Stackoverflow.com/users/24525", "pm_score": 1, "selected": false, "text": "<p>I've read somewhere that multiplication is more efficient in C/C++; No idea regarding interpreted languages - the difference is probably negligible due to all the other overhead.</p>\n\n<p>Unless it becomes an issue stick with what is more maintainable/readable - I hate it when people tell me this but its so true.</p>\n" }, { "answer_id": 226512, "author": "matma", "author_id": 29880, "author_profile": "https://Stackoverflow.com/users/29880", "pm_score": -1, "selected": false, "text": "<p>Well, if we assume that an add/subtrack operation costs 1, then multiply costs 5, and divide costs about 20.</p>\n" }, { "answer_id": 226515, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 5, "selected": false, "text": "<p>Multiplication is faster, division is more accurate. You'll lose some precision if your number isn't a power of 2:</p>\n\n<pre><code>y = x / 3.0;\ny = x * 0.333333; // how many 3's should there be, and how will the compiler round?\n</code></pre>\n\n<p>Even if you let the compiler figure out the inverted constant to perfect precision, the answer can still be different.</p>\n\n<pre><code>x = 100.0;\nx / 3.0 == x * (1.0/3.0) // is false in the test I just performed\n</code></pre>\n\n<p>The speed issue is only likely to matter in C/C++ or JIT languages, and even then only if the operation is in a loop at a bottleneck.</p>\n" }, { "answer_id": 226518, "author": "buti-oxa", "author_id": 2515, "author_profile": "https://Stackoverflow.com/users/2515", "pm_score": 3, "selected": false, "text": "<p>Do whatever you need. Think of your reader first, do not worry about performance until you are sure you have a performance problem.</p>\n\n<p>Let compiler do the performance for you.</p>\n" }, { "answer_id": 226519, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": "<p>Floating-point division is (generally) especially slow, so while floating-point multiplication is also relatively slow, it's probably faster than floating-point division.</p>\n\n<p>But I'm more inclined to answer \"it doesn't really matter\", unless profiling has shown that division is a bit bottleneck vs. multiplication. I'm guessing, though, that the choice of multiplication vs. division isn't going to have a big performance impact in your application.</p>\n" }, { "answer_id": 226547, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 1, "selected": false, "text": "<p>I would suggest multiplication in general, because you don't have to spend the cycles ensuring that your divisor is not 0. This doesn't apply, of course, if your divisor is a constant.</p>\n" }, { "answer_id": 226563, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 6, "selected": false, "text": "<p>Python:</p>\n\n<pre><code>time python -c 'for i in xrange(int(1e8)): t=12341234234.234 / 2.0'\nreal 0m26.676s\nuser 0m25.154s\nsys 0m0.076s\n\ntime python -c 'for i in xrange(int(1e8)): t=12341234234.234 * 0.5'\nreal 0m17.932s\nuser 0m16.481s\nsys 0m0.048s\n</code></pre>\n\n<p>multiplication is 33% faster</p>\n\n<p>Lua:</p>\n\n<pre><code>time lua -e 'for i=1,1e8 do t=12341234234.234 / 2.0 end'\nreal 0m7.956s\nuser 0m7.332s\nsys 0m0.032s\n\ntime lua -e 'for i=1,1e8 do t=12341234234.234 * 0.5 end'\nreal 0m7.997s\nuser 0m7.516s\nsys 0m0.036s\n</code></pre>\n\n<p>=> no real difference</p>\n\n<p>LuaJIT:</p>\n\n<pre><code>time luajit -O -e 'for i=1,1e8 do t=12341234234.234 / 2.0 end'\nreal 0m1.921s\nuser 0m1.668s\nsys 0m0.004s\n\ntime luajit -O -e 'for i=1,1e8 do t=12341234234.234 * 0.5 end'\nreal 0m1.843s\nuser 0m1.676s\nsys 0m0.000s\n</code></pre>\n\n<p>=>it's only 5% faster</p>\n\n<p>conclusions: in Python it's faster to multiply than to divide, but as you get closer to the CPU using more advanced VMs or JITs, the advantage disappears. It's quite possible that a future Python VM would make it irrelevant</p>\n" }, { "answer_id": 226584, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "<p>Write whichever is more clearly states your intent.</p>\n\n<p>After your program works, figure out what's slow, and make that faster.</p>\n\n<p>Don't do it the other way around.</p>\n" }, { "answer_id": 226610, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 6, "selected": false, "text": "<p>Always use whatever is the clearest. Anything else you do is trying to outsmart the compiler. If the compiler is at all intelligent, it will do the best to optimize the result, but nothing can make the next guy not hate you for your crappy bitshifting solution (I love bit manipulation by the way, it's fun. But fun != readable)</p>\n\n<p>Premature optimization is the root of all evil. Always remember the three rules of optimization!</p>\n\n<ol>\n<li>Don't optimize.</li>\n<li>If you are an expert, see rule #1</li>\n<li><p>If you are an expert and can justify the need, then use the following procedure:</p>\n\n<ul>\n<li>Code it unoptimized</li>\n<li>determine how fast is \"Fast enough\"--Note which user requirement/story requires that metric.</li>\n<li>Write a speed test</li>\n<li>Test existing code--If it's fast enough, you're done.</li>\n<li>Recode it optimized</li>\n<li>Test optimized code. IF it doesn't meet the metric, throw it away and keep the original.</li>\n<li>If it meets the test, keep the original code in as comments</li>\n</ul></li>\n</ol>\n\n<p>Also, doing things like removing inner loops when they aren't required or choosing a linked list over an array for an insertion sort are not optimizations, just programming.</p>\n" }, { "answer_id": 226634, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 2, "selected": false, "text": "<p>This becomes more of a question when you are programming in assembly or perhaps C. I figure that with most modern languages that optimization such as this is being done for me.</p>\n" }, { "answer_id": 228058, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Be wary of \"guessing multiplication is typically better so I try to stick to that when I code,\"</p>\n\n<p>In context of this specific question, better here means \"faster\". Which is not very useful.</p>\n\n<p>Thinking about speed can be a serious mistake. There are profound error implications in the specific algebraic form of the calculation. </p>\n\n<p>See <a href=\"http://www.dcs.ed.ac.uk/home/mhe/plume/node10.html\" rel=\"nofollow noreferrer\">Floating Point arithmetic with error analysis</a>. See <a href=\"http://www.cs.berkeley.edu/~demmel/cs267/lecture21/lecture21.html\" rel=\"nofollow noreferrer\">Basic Issues in Floating Point Arithmetic and Error Analysis</a>. </p>\n\n<p>While some floating-point values are exact, most floating point values are an approximation; they are some ideal value plus some error. Every operation applies to the ideal value and the error value.</p>\n\n<p>The biggest problems come from trying to manipulate two nearly-equal numbers. The right-most bits (the error bits) come to dominate the results.</p>\n\n<pre><code>&gt;&gt;&gt; for i in range(7):\n... a=1/(10.0**i)\n... b=(1/10.0)**i\n... print i, a, b, a-b\n... \n0 1.0 1.0 0.0\n1 0.1 0.1 0.0\n2 0.01 0.01 -1.73472347598e-18\n3 0.001 0.001 -2.16840434497e-19\n4 0.0001 0.0001 -1.35525271561e-20\n5 1e-05 1e-05 -1.69406589451e-21\n6 1e-06 1e-06 -4.23516473627e-22\n</code></pre>\n\n<p>In this example, you can see that as the values get smaller, the difference between nearly equal numbers create non-zero results where the correct answer is zero.</p>\n" }, { "answer_id": 656525, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 5, "selected": false, "text": "<p>If you want to optimize your code but still be clear, try this:</p>\n\n<pre><code>y = x * (1.0 / 2.0);\n</code></pre>\n\n<p>The compiler should be able to do the divide at compile-time, so you get a multiply at run-time. I would expect the precision to be the same as in the <code>y = x / 2.0</code> case.</p>\n\n<p>Where this may matter a LOT is in embedded processors where floating-point emulation is required to compute floating-point arithmetic.</p>\n" }, { "answer_id": 1965541, "author": "Carson Myers", "author_id": 84478, "author_profile": "https://Stackoverflow.com/users/84478", "pm_score": 4, "selected": false, "text": "<p>Just going to add something for the \"other languages\" option.<br>\nC: Since this is just an academic exercise that <em>really</em> makes no difference, I thought I would contribute something different.</p>\n\n<p>I compiled to assembly with no optimizations and looked at the result.<br>\nThe code:</p>\n\n<pre><code>int main() {\n\n volatile int a;\n volatile int b;\n\n asm(\"## 5/2\\n\");\n a = 5;\n a = a / 2;\n\n asm(\"## 5*0.5\");\n b = 5;\n b = b * 0.5;\n\n asm(\"## done\");\n\n return a + b;\n\n}\n</code></pre>\n\n<p>compiled with <code>gcc tdiv.c -O1 -o tdiv.s -S</code></p>\n\n<p>the division by 2:</p>\n\n<pre><code>movl $5, -4(%ebp)\nmovl -4(%ebp), %eax\nmovl %eax, %edx\nshrl $31, %edx\naddl %edx, %eax\nsarl %eax\nmovl %eax, -4(%ebp)\n</code></pre>\n\n<p>and the multiplication by 0.5:</p>\n\n<pre><code>movl $5, -8(%ebp)\nmovl -8(%ebp), %eax\npushl %eax\nfildl (%esp)\nleal 4(%esp), %esp\nfmuls LC0\nfnstcw -10(%ebp)\nmovzwl -10(%ebp), %eax\norw $3072, %ax\nmovw %ax, -12(%ebp)\nfldcw -12(%ebp)\nfistpl -16(%ebp)\nfldcw -10(%ebp)\nmovl -16(%ebp), %eax\nmovl %eax, -8(%ebp)\n</code></pre>\n\n<p>However, when I changed those <code>int</code>s to <code>double</code>s (which is what python would probably do), I got this:</p>\n\n<p>division:</p>\n\n<pre><code>flds LC0\nfstl -8(%ebp)\nfldl -8(%ebp)\nflds LC1\nfmul %st, %st(1)\nfxch %st(1)\nfstpl -8(%ebp)\nfxch %st(1)\n</code></pre>\n\n<p>multiplication:</p>\n\n<pre><code>fstpl -16(%ebp)\nfldl -16(%ebp)\nfmulp %st, %st(1)\nfstpl -16(%ebp)\n</code></pre>\n\n<p>I haven't benchmarked any of this code, but just by examining the code you can see that using integers, division by 2 is shorter than multiplication by 2. Using doubles, multiplication is shorter because the compiler uses the processor's floating point opcodes, which probably run faster (but actually I don't know) than not using them for the same operation. So ultimately this answer has shown that the performance of multiplaction by 0.5 vs. division by 2 depends on the implementation of the language and the platform it runs on. Ultimately the difference is negligible and is something you should virtually never ever worry about, except in terms of readability.</p>\n\n<p>As a side note, you can see that in my program <code>main()</code> returns <code>a + b</code>. When I take the volatile keyword away, you'll never guess what the assembly looks like (excluding the program setup):</p>\n\n<pre><code>## 5/2\n\n## 5*0.5\n## done\n\nmovl $5, %eax\nleave\nret\n</code></pre>\n\n<p>it did both the division, multiplication, AND addition in a single instruction! Clearly you don't have to worry about this if the optimizer is any kind of respectable.</p>\n\n<p>Sorry for the overly long answer.</p>\n" }, { "answer_id": 4112754, "author": "Chris", "author_id": 499165, "author_profile": "https://Stackoverflow.com/users/499165", "pm_score": 1, "selected": false, "text": "<p>As with posts #24 (multiplication is faster) and #30 - but sometimes they are both just as easy to understand:</p>\n\n<pre><code>1*1e-6F;\n\n1/1e6F;\n</code></pre>\n\n<p>~ I find them both just as easy to read, and have to repeat them billions of times. So it is useful to know that multiplication is usually faster.</p>\n" }, { "answer_id": 7730288, "author": "PiotrK", "author_id": 151150, "author_profile": "https://Stackoverflow.com/users/151150", "pm_score": 1, "selected": false, "text": "<p>Java android, profiled on Samsung GT-S5830</p>\n\n<pre><code>public void Mutiplication()\n{\n float a = 1.0f;\n\n for(int i=0; i&lt;1000000; i++)\n {\n a *= 0.5f;\n }\n}\npublic void Division()\n{\n float a = 1.0f;\n\n for(int i=0; i&lt;1000000; i++)\n {\n a /= 2.0f;\n }\n}\n</code></pre>\n\n<p>Results?</p>\n\n<pre><code>Multiplications(): time/call: 1524.375 ms\nDivision(): time/call: 1220.003 ms\n</code></pre>\n\n<p>Division is about 20% faster than multiplication (!)</p>\n" }, { "answer_id": 8943848, "author": "satnhak", "author_id": 323316, "author_profile": "https://Stackoverflow.com/users/323316", "pm_score": -1, "selected": false, "text": "<p>Technically there is no such thing as division, there is just multiplication by inverse elements. For example You never divide by 2, you in fact multiply by 0.5.</p>\n\n<p>'Division' - let's kid ourselves that it exists for a second - is always harder that multiplication because to 'divide' <code>x</code> by <code>y</code> one first needs to compute the value <code>y^{-1}</code> such that <code>y*y^{-1} = 1</code> and then do the multiplication <code>x*y^{-1}</code>. If you already know <code>y^{-1}</code> then not calculating it from <code>y</code> must be an optimization.</p>\n" }, { "answer_id": 11266064, "author": "gast128", "author_id": 1079347, "author_profile": "https://Stackoverflow.com/users/1079347", "pm_score": 1, "selected": false, "text": "<p>There is a difference, but it is compiler dependent. At first on vs2003 (c++) I got no significant difference for double types (64 bit floating point). However running the tests again on vs2010, I detected a huge difference, up to factor 4 faster for multiplications. Tracking this down, it seems that vs2003 and vs2010 generates different fpu code.</p>\n\n<p>On a Pentium 4, 2.8 GHz, vs2003:</p>\n\n<ul>\n<li>Multiplication: 8.09</li>\n<li>Division: 7.97</li>\n</ul>\n\n<p>On a Xeon W3530, vs2003:</p>\n\n<ul>\n<li>Multiplication: 4.68</li>\n<li>Division: 4.64</li>\n</ul>\n\n<p>On a Xeon W3530, vs2010:</p>\n\n<ul>\n<li>Multiplication: 5.33</li>\n<li>Division: 21.05</li>\n</ul>\n\n<p>It seems that on vs2003 a division in a loop (so the divisor was used multiple times) was translated to a multiplication with the inverse. On vs2010 this optimization is not applied any more (I suppose because there is slightly different result between the two methods). Note also that the cpu performs divisions faster as soon as your numerator is 0.0. I do not know the precise algorithm hardwired in the chip, but maybe it is number dependent.</p>\n\n<p>Edit 18-03-2013: the observation for vs2010</p>\n" }, { "answer_id": 11271369, "author": "Gene", "author_id": 1161878, "author_profile": "https://Stackoverflow.com/users/1161878", "pm_score": 3, "selected": false, "text": "<p>Actually there is a good reason that as a general rule of thumb multiplication will be faster than division. Floating point division in hardware is done either with shift and conditional subtract algorithms (\"long division\" with binary numbers) or - more likely these days - with iterations like <a href=\"http://en.wikipedia.org/wiki/Division_%28digital%29#Goldschmidt_division\" rel=\"noreferrer\">Goldschmidt's</a> algorithm. Shift and subtract needs at least one cycle per bit of precision (the iterations are nearly impossible to parallelize as are the shift-and-add of multiplication), and iterative algorithms do at least one multiplication <em>per iteration</em>. In either case, it's highly likely that the division will take more cycles. Of course this does not account for quirks in compilers, data movement, or precision. By and large, though, if you are coding an inner loop in a time sensitive part of a program, writing <code>0.5 * x</code> or <code>1.0/2.0 * x</code> rather than <code>x / 2.0</code> is a reasonable thing to do. The pedantry of \"code what's clearest\" is absolutely true, but all three of these are so close in readability that the pedantry is in this case just pedantic.</p>\n" }, { "answer_id": 28870790, "author": "Jean-François", "author_id": 808716, "author_profile": "https://Stackoverflow.com/users/808716", "pm_score": 0, "selected": false, "text": "<p>After such a long and interesting discussion here is my take on this: There is no final answer to this question. As some people pointed out it depends on both, the hardware (cf <a href=\"https://stackoverflow.com/users/151150/piotrk\">piotrk</a> and <a href=\"https://stackoverflow.com/users/1079347/gast128\">gast128</a>) and the compiler (cf <a href=\"https://stackoverflow.com/users/11649/javier\">@Javier</a>'s tests). If speed is not critical, if your application does not need to process in real-time huge amount of data, you may opt for clarity using a division whereas if processing speed or processor load are an issue, multiplication might be the safest.\nFinally, unless you know exactly on what platform your application will be deployed, benchmark is meaningless. And for code clarity, a single comment would do the job!</p>\n" }, { "answer_id": 39461095, "author": "James Podesta", "author_id": 2663013, "author_profile": "https://Stackoverflow.com/users/2663013", "pm_score": 4, "selected": false, "text": "<p>Firstly, unless you are working in C or ASSEMBLY, you're probably in a higher level language where memory stalls and general call overheads will absolutely dwarf the difference between multiply and divide to the point of irrelevance. So, just pick what reads better in that case.</p>\n\n<p>If you're talking from a very high level it won't be measurably slower for anything you're likely to use it for. You'll see in other answers, people need to do a million multiply/divides just to measure some sub-millisecond difference between the two.</p>\n\n<p>If you're still curious, from a low level optimisation point of view:</p>\n\n<p>Divide tends to have a significantly longer pipeline than multiply. This means it takes longer to get the result, but if you can keep the processor busy with non-dependent tasks, then it doesn't end up costing you any more than a multiply.</p>\n\n<p>How long the pipeline difference is is completely hardware dependant. Last hardware I used was something like 9 cycles for a FPU multiply and 50 cycles for a FPU divide. Sounds a lot, but then you'd lose 1000 cycles for a memory miss, so that can put things in perspective.</p>\n\n<p>An analogy is putting a pie in a microwave while you watch a TV show. The total time it took you away from the TV show is how long it was to put it in the microwave, and take it out of the microwave. The rest of your time you still watched the TV show. So if the pie took 10 minutes to cook instead of 1 minute, it didn't actually use up any more of your tv watching time.</p>\n\n<p>In practice, if you're going to get to the level of caring about the difference between Multiply and Divide, you need to understand pipelines, cache, branch stalls, out-of-order prediction, and pipeline dependencies. If this doesn't sound like where you were intending to go with this question, then the correct answer is to ignore the difference between the two. </p>\n\n<p>Many (many) years ago it was absolutely critical to avoid divides and always use multiplies, but back then memory hits were less relevant, and divides were much worse. These days I rate readability higher, but if there's no readability difference, I think its a good habit to opt for multiplies.</p>\n" }, { "answer_id": 50582198, "author": "l33t", "author_id": 419761, "author_profile": "https://Stackoverflow.com/users/419761", "pm_score": 0, "selected": false, "text": "<p>Here's a silly fun answer:</p>\n\n<p><strong>x / 2.0</strong> is <strong>not</strong> equivalent to <strong>x * 0.5</strong></p>\n\n<p>Let's say you wrote this method on Oct 22, 2008.</p>\n\n<pre><code>double half(double x) =&gt; x / 2.0;\n</code></pre>\n\n<p>Now, 10 years later you learn that you can optimize this piece of code. The method is referenced in hundreds of formulas throughout your application. So you change it, and experience a remarkable 5% performance improvement.</p>\n\n<pre><code>double half(double x) =&gt; x * 0.5;\n</code></pre>\n\n<p>Was it the right decision to change the code? In maths, the two expressions are indeed equivalent. In computer science, that does not always hold true. Please read <a href=\"https://en.wikipedia.org/wiki/Floating-point_arithmetic#Minimizing_the_effect_of_accuracy_problems\" rel=\"nofollow noreferrer\">Minimizing the effect of accuracy problems</a> for more details. If your calculated values are - at some point - compared with other values, you will change the outcome of edge cases. E.g.:</p>\n\n<pre><code>double quantize(double x)\n{\n if (half(x) &gt; threshold))\n return 1;\n else\n return -1;\n}\n</code></pre>\n\n<p><strong>Bottom line is; once you settle for either of the two, then stick to it!</strong></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20494/" ]
Here's a silly fun question: Let's say we have to perform a simple operation where we need half of the value of a variable. There are *typically* two ways of doing this: ``` y = x / 2.0; // or... y = x * 0.5; ``` Assuming we're using the standard operators provided with the language, which one has better performance? I'm guessing multiplication is typically better so I try to stick to that when I code, but I would like to confirm this. Although personally I'm interested in the answer for **Python** 2.4-2.5, feel free to also post an answer for other languages! And if you'd like, feel free to post other fancier ways (like using bitwise shift operators) as well.
I think this is getting so nitpicky that you would be better off doing whatever makes the code more readable. Unless you perform the operations thousands, if not millions, of times, I doubt anyone will ever notice the difference. If you really have to make the choice, benchmarking is the only way to go. Find what function(s) are giving you problems, then find out where in the function the problems occur, and fix those sections. However, I still doubt that a single mathematical operation (even one repeated many, many times) would be a cause of any bottleneck.
226,473
<p>I'm betting that someone has already solved this and maybe I'm using the wrong search terms for google to tell me the answer, but here is my situation.</p> <p>I have a script that I want to run, but I want it to run only when scheduled and only one at a time. (can't run the script simultaneously) </p> <p>Now the sticky part is that say I have a table called "myhappyschedule" which has the data I need and the scheduled time. This table can have multiple scheduled times even at the same time, each one would run this script. So essentially I need a queue of each time the script fires and they all need to wait for each one before it to finish. (sometimes this can take just a minute for the script to execute sometimes its many many minutes)</p> <p>What I'm thinking about doing is making a script that checks myhappyschedule every 5 min and gathers up those that are scheduled, puts them into a queue where another script can execute each 'job' or occurrence in the queue in order. Which all of this sounds messy. </p> <p>To make this longer - I should say that I'm allowing users to schedule things in myhappyschedule and not edit crontab. </p> <p>What can be done about this? File locks and scripts calling scripts?</p>
[ { "answer_id": 226531, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 2, "selected": false, "text": "<p>You can use the at(1) command inside your script to schedule its next run. Before it exits, it can check myhappyschedule for the next run time. You don't need cron at all, really.</p>\n" }, { "answer_id": 226661, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 3, "selected": true, "text": "<p>add a column <code>exec_status</code> to <code>myhappytable</code> (maybe also <code>time_started</code> and <code>time_finished</code>, see pseudocode)</p>\n\n<p>run the following cron script every x minutes</p>\n\n<p>pseudocode of cron script:</p>\n\n<pre><code>[create/check pid lock (optional, but see \"A potential pitfall\" below)]\nget number of rows from myhappytable where (exec_status == executing_now)\nif it is &gt; 0, exit\nbegin loop\n get one row from myhappytable\n where (exec_status == not_yet_run) and (scheduled_time &lt;= now)\n order by scheduled_time asc\n if no such row, exit\n set row exec_status to executing_now (maybe set time_started to now)\n execute whatever command the row contains\n set row exec_status to completed\n (maybe also store the command output/return as well, set time_finished to now)\nend loop\n[delete pid lock file (complementary to the starting pid lock check)]\n</code></pre>\n\n<p>This way, the script first checks if none of the commands is running, then runs first not-yet run command, until there are no more commands to be run at the given moment. Also, you can see what command is executing by querying the database.</p>\n\n<p><strong>A potential pitfall:</strong> if the cron script is killed, a scheduled task will remain in \"executing_now\" state. That's what the pid lock at beginning and end is for: to see if the cron script terminated properly. pseudocode of create/check pidlock:</p>\n\n<pre><code>if exists pidlockfile then\n check if process id given in file exists\n if not exists then\n update myhappytable set exec_status = error_cronscript_died_while_executing_this \n where exec_status == executing_now\n delete pidlockfile\n else (previous instance still running)\n exit\n endif\nendif\ncreate pidlockfile containing cron script process id\n</code></pre>\n" }, { "answer_id": 836955, "author": "Nick Zalutskiy", "author_id": 1959, "author_profile": "https://Stackoverflow.com/users/1959", "pm_score": 0, "selected": false, "text": "<p>I came across this question while researching for a solution to the queuing problem. For the benefit of anyone else searching here is my solution.</p>\n\n<p>Combine this with a cron that starts jobs as they are scheduled (even if they are scheduled to run at the same time) and that solves the problem you described as well.</p>\n\n<h1>Problem</h1>\n\n<hr>\n\n<ul>\n<li>At most one instance of the script should be running.</li>\n<li>We want to cue up requests to process them as fast as possible.</li>\n</ul>\n\n<p>ie. We need a pipeline to the script.</p>\n\n<h1>Solution:</h1>\n\n<hr>\n\n<p>Create a pipeline to any script. Done using a small bash script (further down).</p>\n\n<p>The script can be called as<br>\n<code>./pipeline \"&lt;any command and arguments go here&gt;\"</code></p>\n\n<p>Example:</p>\n\n<pre><code>./pipeline sleep 10 &amp;\n./pipeline shabugabu &amp;\n./pipeline single_instance_script some arguments &amp;\n./pipeline single_instance_script some other_argumnts &amp;\n./pipeline \"single_instance_script some yet_other_arguments &gt; output.txt\" &amp;\n..etc\n</code></pre>\n\n<p>The script creates a new <a href=\"http://www.linuxjournal.com/content/using-named-pipes-fifos-bash\" rel=\"nofollow noreferrer\">named pipe</a> for each command. So the above will create named pipes: <code>sleep</code>, <code>shabugabu</code>, and <code>single_instance_script</code></p>\n\n<p>In this case the initial call will start a reader and run <code>single_instance_script</code> with <code>some arguments</code> as arguments. Once the call completes, the reader will grab the next request off the pipe and execute with <code>some other_arguments</code>, complete, grab the next etc...</p>\n\n<p>This script will block requesting processes so call it as a background job (&amp; at the end) or as a detached process with <a href=\"http://linux.die.net/man/1/at\" rel=\"nofollow noreferrer\"><code>at</code></a> (<code>at now &lt;&lt;&lt; \"./pipeline some_script\"</code>)</p>\n\n<pre><code>#!/bin/bash -Eue\n\n# Using command name as the pipeline name\npipeline=$(basename $(expr \"$1\" : '\\(^[^[:space:]]*\\)')).pipe\nis_reader=false\n\nfunction _pipeline_cleanup {\n if $is_reader; then\n rm -f $pipeline\n fi\n rm -f $pipeline.lock\n\n exit\n}\ntrap _pipeline_cleanup INT TERM EXIT\n\n# Dispatch/initialization section, critical\nlockfile $pipeline.lock\n if [[ -p $pipeline ]]\n then\n echo \"$*\" &gt; $pipeline\n exit\n fi\n\n is_reader=true\n mkfifo $pipeline\n echo \"$*\" &gt; $pipeline &amp;\nrm -f $pipeline.lock\n\n# Reader section\nwhile read command &lt; $pipeline\ndo\n echo \"$(date) - Executing $command\"\n ($command) &amp;&gt; /dev/null\ndone\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30413/" ]
I'm betting that someone has already solved this and maybe I'm using the wrong search terms for google to tell me the answer, but here is my situation. I have a script that I want to run, but I want it to run only when scheduled and only one at a time. (can't run the script simultaneously) Now the sticky part is that say I have a table called "myhappyschedule" which has the data I need and the scheduled time. This table can have multiple scheduled times even at the same time, each one would run this script. So essentially I need a queue of each time the script fires and they all need to wait for each one before it to finish. (sometimes this can take just a minute for the script to execute sometimes its many many minutes) What I'm thinking about doing is making a script that checks myhappyschedule every 5 min and gathers up those that are scheduled, puts them into a queue where another script can execute each 'job' or occurrence in the queue in order. Which all of this sounds messy. To make this longer - I should say that I'm allowing users to schedule things in myhappyschedule and not edit crontab. What can be done about this? File locks and scripts calling scripts?
add a column `exec_status` to `myhappytable` (maybe also `time_started` and `time_finished`, see pseudocode) run the following cron script every x minutes pseudocode of cron script: ``` [create/check pid lock (optional, but see "A potential pitfall" below)] get number of rows from myhappytable where (exec_status == executing_now) if it is > 0, exit begin loop get one row from myhappytable where (exec_status == not_yet_run) and (scheduled_time <= now) order by scheduled_time asc if no such row, exit set row exec_status to executing_now (maybe set time_started to now) execute whatever command the row contains set row exec_status to completed (maybe also store the command output/return as well, set time_finished to now) end loop [delete pid lock file (complementary to the starting pid lock check)] ``` This way, the script first checks if none of the commands is running, then runs first not-yet run command, until there are no more commands to be run at the given moment. Also, you can see what command is executing by querying the database. **A potential pitfall:** if the cron script is killed, a scheduled task will remain in "executing\_now" state. That's what the pid lock at beginning and end is for: to see if the cron script terminated properly. pseudocode of create/check pidlock: ``` if exists pidlockfile then check if process id given in file exists if not exists then update myhappytable set exec_status = error_cronscript_died_while_executing_this where exec_status == executing_now delete pidlockfile else (previous instance still running) exit endif endif create pidlockfile containing cron script process id ```
226,505
<p>I have the following regex that does a great job matching urls: </p> <pre><code>((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&amp;]*)` </code></pre> <p>However, it does not handle urls without a prefix, ie. <strong>stackoverflow.com</strong> or <strong>www.google.com</strong> do not match. Anyone know how I can modify this regex to not care if there is a prefix or not?</p> <hr> <p>EDIT: Does my question too vague? Does it need more details?</p> <hr> <pre><code>(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\)))?[\w\d:#@%/;$()~_?\+-=\\\.&amp;]*) </code></pre> <p>I added a ()? around the protocols like <strong>Vinko Vrsalovic</strong> suggested, but now the regex will match nearly any string, as long as it has valid URL characters.</p> <p>My implementation of this is I have a database that I manage the contents, and it has a field that either has plain text, a phone number, a URL or an email address. I was looking for an easy way to validate the input so I can have it properly formatted, ie. creating anchor tags for the url/email, and formatting the phone number how I have the other numbers formatted throughout the site. Any suggestions?</p>
[ { "answer_id": 226556, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": -1, "selected": false, "text": "<p>Just use:</p>\n\n<pre><code>.*\n</code></pre>\n\n<p>i.e. match everything. </p>\n\n<p>The things you want to match are just hostnames, not URL (technically). </p>\n\n<p>There's no structure you can use to definitively identify hostnames. \nPerhaps you could look for things that end in \".com\" but then you'll miss any .co.uk, net, .org, etc.</p>\n\n<p>Edit:</p>\n\n<p>In other words: If you remove the requirement that the URL-like things start with a protocol you won't have any thing to match on. \nDepending on what you are using the regular expression on:</p>\n\n<ol>\n<li>Treat everything as a URL</li>\n<li>Keep the requirement for a protocol</li>\n<li>Hack checks for common endings for hostnames (e.g. .com .net .org) and accept you'll miss some.</li>\n</ol>\n" }, { "answer_id": 226573, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>Your regexp matches everything starting with one of those protocols, including a lot of things that cannot possibly be existent URLs, if you relax the protocol part (making it optional with ?) then you'll just be matching almost everything, including the empty string.</p>\n\n<p>In other words, it does a great job matching URLs because it matches almost anything starting with <a href=\"http://,https://,ftp://\" rel=\"nofollow noreferrer\">http://,https://,ftp://</a> and so on. Well, it also matches ftp:\\\\ and ms-help://, but let's ignore that.</p>\n\n<p>It may make sense, depending on actual usage, because the other regexp approach of whitelisting valid domains becomes non maintainable quickly enough, but making the protocol part optional does not make sense.</p>\n\n<p>An example (with the relaxed protocol part in place):</p>\n\n<pre><code>&gt;&gt;&gt; r = re.compile('(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\\\\\))+)?[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&amp;]*)')\n&gt;&gt;&gt; r.search('oompaloompa_is_not_an_ur%&amp;%%l').groups()[0]\n'oompaloompa_is_not_an_ur%&amp;%%l' #Matches!\n&gt;&gt;&gt; r.search('oompaloompa_isdfjakojfsdi.sdnioknfsdjknfsdjk.fsdnjkfnsdjknfsdjk').groups()[0]\n'oompaloompa_isdfjakojfsdi.sdnioknfsdjknfsdjk.fsdnjkfnsdjknfsdjk' #Matches!\n&gt;&gt;&gt; \n</code></pre>\n\n<p>Given your edit I suggest you either make the user select what is he adding, adding an enum column, or create a simpler regex that'll check for at least a dot, besides the valid characters and maybe some common domains.</p>\n\n<p>A third alternative which will be <strong>VERY SLOW</strong> and only to be used when URL validation is <strong>REALLY REALLY IMPORTANT</strong> is actually accessing the URL and do a HEAD request on it, if you get a host not found or an error you know it's not valid. For emails you could try and see if the MX host exists and has port 25 open. If both fails, it'll be plain text. (I'm not suggesting this either)</p>\n" }, { "answer_id": 226621, "author": "marto", "author_id": 29555, "author_profile": "https://Stackoverflow.com/users/29555", "pm_score": 0, "selected": false, "text": "<p>You can surround the prefix part in brackets and match 0 or 1 occurrences</p>\n\n<p><code>(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\\\\\))+)?</code></p>\n\n<p>So the whole regex will become</p>\n\n<p><code>(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\\\\\))+)?[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&amp;]*)</code></p>\n\n<p>The problem with that is it's going to match more or less any word. For example \"test\" would also be a match. </p>\n\n<p>Where are you going to use that regex? Are you trying to validate a hostname or are you trying to find hostnames inside a paragraph?</p>\n" }, { "answer_id": 226709, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 2, "selected": false, "text": "<p>The below regex is from the wonderful <a href=\"http://www.amazon.co.uk/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=sr_1_1/279-4458937-3540756?ie=UTF8&amp;s=books&amp;qid=1224694042&amp;sr=8-1\" rel=\"nofollow noreferrer\">Mastering Regular Expressions</a> book. If you are not familiar with the <a href=\"http://www.regular-expressions.info/freespacing.html\" rel=\"nofollow noreferrer\">free spacing/comments mode</a>, I suggest you get familiar with it.</p>\n\n<pre><code>\\b\n# Match the leading part (proto://hostname, or just hostname)\n(\n # ftp://, http://, or https:// leading part\n (ftp|https?)://[-\\w]+(\\.\\w[-\\w]*)+\n |\n # or, try to find a hostname with our more specific sub-expression\n (?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \\. )+ # sub domains\n # Now ending .com, etc. For these, require lowercase\n (?-i: com\\b\n | edu\\b\n | biz\\b\n | gov\\b\n | in(?:t|fo)\\b # .int or .info\n | mil\\b\n | net\\b\n | org\\b\n | name\\b\n | coop\\b\n | aero\\b\n | museum\\b\n | [a-z][a-z]\\b # two-letter country codes\n )\n)\n\n# Allow an optional port number\n( : \\d+ )?\n\n# The rest of the URL is optional, and begins with / . . . \n(\n /\n # The rest are heuristics for what seems to work well\n [^.!,?;\"'&lt;&gt;()\\[\\]{}\\s\\x7F-\\xFF]*\n (?:\n [.!,?]+ [^.!,?;\"'&lt;&gt;()\\[\\]{}\\s\\x7F-\\xFF]+\n )*\n)?\n</code></pre>\n\n<p>To explain this regex briefly (for a full explanation get the book) - URLs have one or more dot separated parts ending with either a limited list of final bits, or a two letter country code (.uk .fr ...). In addition the parts may have any alphanumeric characters or hyphens '-', but hyphens may not be the first or last character of the parts. Then there may be a port number, and then the rest of it.</p>\n\n<p>To extract this from the website, go to <a href=\"http://regex.info/listing.cgi?ed=3&amp;p=207\" rel=\"nofollow noreferrer\">http://regex.info/listing.cgi?ed=3&amp;p=207</a> It is from page 207 of the 3rd edition.</p>\n\n<p>And the page says \"Copyright © 2008 Jeffrey Friedl\" so I'm not sure what the conditions for use are exactly, but I would expect that if you own the book you could use it so ... I'm hoping I'm not breaking the rules putting it here.</p>\n" }, { "answer_id": 226893, "author": "caskey", "author_id": 114986, "author_profile": "https://Stackoverflow.com/users/114986", "pm_score": 1, "selected": false, "text": "<p>If you read section 5 of the URL specification (<a href=\"http://www.isi.edu/in-notes/rfc1738.txt\" rel=\"nofollow noreferrer\">http://www.isi.edu/in-notes/rfc1738.txt</a>) you'll see that the syntax of a URL is at a minimum:</p>\n\n<pre><code>scheme ':' schemepart\n</code></pre>\n\n<p>where scheme is 1 or more characters and schemepart is 0 or more characters. Therefore if you don't have a colon, you don't have a URL.</p>\n\n<p>That said, /users/ don't care if they've given you a url, to them it looks like one. So here's what I do:</p>\n\n<p>BEFORE validation, if there isn't a colon in it, prepend http://, then run it through whatever validator you want. This turns any legitimate hostname (which may not include domain info, after all) into something that looks like a URL.</p>\n\n<pre><code>frob -&gt; http://frob\n</code></pre>\n\n<p>(Nearly) the only rule for the host part is that it can't begin with a digit if it contains no dots. Now, there are specific validations that should be performed for specific schemes, which none of the regexes given thus far accomplish. But, spec compliance is probably not what you want to 'validate'. Therefore a dns query on the hostname portion may be useful, but unless you're using the same resolver in the same context as your user, it isn't going to work in all cases.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
I have the following regex that does a great job matching urls: ``` ((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)` ``` However, it does not handle urls without a prefix, ie. **stackoverflow.com** or **www.google.com** do not match. Anyone know how I can modify this regex to not care if there is a prefix or not? --- EDIT: Does my question too vague? Does it need more details? --- ``` (((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\)))?[\w\d:#@%/;$()~_?\+-=\\\.&]*) ``` I added a ()? around the protocols like **Vinko Vrsalovic** suggested, but now the regex will match nearly any string, as long as it has valid URL characters. My implementation of this is I have a database that I manage the contents, and it has a field that either has plain text, a phone number, a URL or an email address. I was looking for an easy way to validate the input so I can have it properly formatted, ie. creating anchor tags for the url/email, and formatting the phone number how I have the other numbers formatted throughout the site. Any suggestions?
The below regex is from the wonderful [Mastering Regular Expressions](http://www.amazon.co.uk/Mastering-Regular-Expressions-Jeffrey-Friedl/dp/0596528124/ref=sr_1_1/279-4458937-3540756?ie=UTF8&s=books&qid=1224694042&sr=8-1) book. If you are not familiar with the [free spacing/comments mode](http://www.regular-expressions.info/freespacing.html), I suggest you get familiar with it. ``` \b # Match the leading part (proto://hostname, or just hostname) ( # ftp://, http://, or https:// leading part (ftp|https?)://[-\w]+(\.\w[-\w]*)+ | # or, try to find a hostname with our more specific sub-expression (?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # sub domains # Now ending .com, etc. For these, require lowercase (?-i: com\b | edu\b | biz\b | gov\b | in(?:t|fo)\b # .int or .info | mil\b | net\b | org\b | name\b | coop\b | aero\b | museum\b | [a-z][a-z]\b # two-letter country codes ) ) # Allow an optional port number ( : \d+ )? # The rest of the URL is optional, and begins with / . . . ( / # The rest are heuristics for what seems to work well [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]* (?: [.!,?]+ [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]+ )* )? ``` To explain this regex briefly (for a full explanation get the book) - URLs have one or more dot separated parts ending with either a limited list of final bits, or a two letter country code (.uk .fr ...). In addition the parts may have any alphanumeric characters or hyphens '-', but hyphens may not be the first or last character of the parts. Then there may be a port number, and then the rest of it. To extract this from the website, go to <http://regex.info/listing.cgi?ed=3&p=207> It is from page 207 of the 3rd edition. And the page says "Copyright © 2008 Jeffrey Friedl" so I'm not sure what the conditions for use are exactly, but I would expect that if you own the book you could use it so ... I'm hoping I'm not breaking the rules putting it here.
226,510
<p>Say I have a form like:</p> <pre><code>class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) </code></pre> <p>And I want to show it twice on a page within one form tag each time with a different prefix e.g.,:</p> <pre><code>rest of page ... &lt;form ..&gt; GeneralForm(data,prefix="form1").as_table() GeneralForm(data,prefix="form2").as_table() &lt;input type="submit" /&gt; &lt;/form&gt; rest of page ... </code></pre> <p>When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it?</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms" rel="noreferrer">This was the only documentation</a> I could find and it's peckish.</p>
[ { "answer_id": 226568, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": true, "text": "<p>You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially.</p>\n\n<p>Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is:</p>\n\n<pre><code>def some_view(request):\n if request.method == 'POST':\n form1 = GeneralForm(request.POST, prefix='form1')\n form2 = GeneralForm(request.POST, prefix='form2')\n if all([form1.is_valid(), form2.is_valid()]):\n pass # Do stuff with the forms\n else:\n form1 = GeneralForm(prefix='form1')\n form2 = GeneralForm(prefix='form2')\n return render_to_response('some_template.html', {\n 'form1': form1,\n 'form2': form2,\n })\n</code></pre>\n\n<p>Here's some real-world sample code which demonstrates processing forms using the prefix:</p>\n\n<p><a href=\"http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/\" rel=\"noreferrer\">http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/</a></p>\n" }, { "answer_id": 276697, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 3, "selected": false, "text": "<p>Even better, I think <a href=\"http://docs.djangoproject.com/en/dev/topics/forms/formsets/\" rel=\"noreferrer\">formsets</a> is exactly what you're looking for. </p>\n\n<pre><code>class GeneralForm(forms.Form):\n field1 = forms.IntegerField(required=False)\n field2 = forms. IntegerField(required=False)\n\nfrom django.forms.formsets import formset_factory\n\n# GeneralSet is a formset with 2 occurrences of GeneralForm \n# ( as a formset allows the user to add new items, this enforces\n# 2 fixed items, no less, no more )\nGeneralSet = formset_factory(GeneralForm, extra=2, max_num=2)\n\n# example view\n\ndef someview(request):\n general_set = GeneralSet(request.POST)\n if general_set.is_valid():\n for form in general_set.forms:\n # do something with data\n return render_to_response(\"template.html\", {'form': general_set}, RequestContext(request))\n</code></pre>\n\n<p>You can even have a formset automatically generated from a model with <a href=\"http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1\" rel=\"noreferrer\">modelformset_factory</a> , which are used by the automated django admin. FormSet handle even more stuff than simple forms, like adding, removing and sorting items.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
Say I have a form like: ``` class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) ``` And I want to show it twice on a page within one form tag each time with a different prefix e.g.,: ``` rest of page ... <form ..> GeneralForm(data,prefix="form1").as_table() GeneralForm(data,prefix="form2").as_table() <input type="submit" /> </form> rest of page ... ``` When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it? [This was the only documentation](http://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms) I could find and it's peckish.
You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially. Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is: ``` def some_view(request): if request.method == 'POST': form1 = GeneralForm(request.POST, prefix='form1') form2 = GeneralForm(request.POST, prefix='form2') if all([form1.is_valid(), form2.is_valid()]): pass # Do stuff with the forms else: form1 = GeneralForm(prefix='form1') form2 = GeneralForm(prefix='form2') return render_to_response('some_template.html', { 'form1': form1, 'form2': form2, }) ``` Here's some real-world sample code which demonstrates processing forms using the prefix: <http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/>
226,514
<p>I seem to remember reading that it's possible to declare taglib directives such as:</p> <pre><code>&lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; </code></pre> <p>in web.xml. This eliminates the need to duplicate this directive in every JSP file where the taglib is used. Could someone tell me <em>how</em> these directives can be added to web.xml?</p>
[ { "answer_id": 226585, "author": "David M. Karr", "author_id": 10508, "author_profile": "https://Stackoverflow.com/users/10508", "pm_score": 3, "selected": false, "text": "<p>Sorry, you're slightly mistaken. If a page uses a taglib, you have to have a taglib directive for it on the page. You could place the common taglib directives in an include file that all of your pages include with an include directive, but at compile time the taglib directive has to be there.</p>\n\n<p>I prefer to NOT have the taglib elements in the web.xml, and instead have the taglib directive specify the URI value that is used in the \"uri\" element in the TLD that is inside the taglib jar file in your WEB-INF/lib.</p>\n" }, { "answer_id": 228430, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 6, "selected": true, "text": "<p>The <code>taglib</code> element in web.xml serves a different purpose to the <code>taglib</code> directive which you have above.</p>\n\n<p>As David said, the <code>taglib</code> directive is required on each page.</p>\n\n<p>If you have many pages which use common taglibs, you can shortcut this by putting the taglib directives into an include file, and including this file each page. But no matter how you do it, the taglib directive has to be on the page somehow.</p>\n\n<p>That tag you need to include on each page looks like this:</p>\n\n<pre><code>&lt;%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %&gt;\n</code></pre>\n\n<p>If you have a custom taglib in a custom location, you can also specify a location relative to the webapp root:</p>\n\n<pre><code> &lt;%@ taglib prefix=\"ex\" uri=\"/taglib.tld\" %&gt;\n</code></pre>\n\n<p><a href=\"http://java.sun.com/products/jsp/syntax/1.2/syntaxref1211.html\" rel=\"noreferrer\">Further reading on the taglib directive</a></p>\n\n<p>The <code>taglib</code> directive from web.xml maps tag uris to the physical location of your taglib. It is optional since JSP 2.0, as compliant containers will look in a set of standard locations to try to auto-discover the taglib: /WEB-INF and its subdirectories, /META-INF as well for JAR files.</p>\n\n<p>It looks like this, in web.xml:</p>\n\n<pre><code>&lt;taglib&gt;\n &lt;taglib-uri&gt;\n http://www.example.com/taglib\n &lt;/taglib-uri&gt;\n &lt;taglib-location&gt;\n /taglib.tld\n &lt;/taglib-location&gt;\n&lt;/taglib&gt;\n</code></pre>\n\n<p>And the taglib is referenced in the JSP page like this (the taglib directive on each page is unavoidable!):</p>\n\n<pre><code>&lt;%@ taglib prefix=\"ex\" uri=\"http://www.example.com/taglib\" %&gt;\n</code></pre>\n\n<p>This is equivalent to the second example I gave for the taglib directive above. The biggest difference is in how you point to the taglib location. </p>\n\n<p><a href=\"http://wiki.metawerx.net/wiki/Web.xml.TagLib\" rel=\"noreferrer\">This page</a> contains a bit more information.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I seem to remember reading that it's possible to declare taglib directives such as: ``` <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ``` in web.xml. This eliminates the need to duplicate this directive in every JSP file where the taglib is used. Could someone tell me *how* these directives can be added to web.xml?
The `taglib` element in web.xml serves a different purpose to the `taglib` directive which you have above. As David said, the `taglib` directive is required on each page. If you have many pages which use common taglibs, you can shortcut this by putting the taglib directives into an include file, and including this file each page. But no matter how you do it, the taglib directive has to be on the page somehow. That tag you need to include on each page looks like this: ``` <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ``` If you have a custom taglib in a custom location, you can also specify a location relative to the webapp root: ``` <%@ taglib prefix="ex" uri="/taglib.tld" %> ``` [Further reading on the taglib directive](http://java.sun.com/products/jsp/syntax/1.2/syntaxref1211.html) The `taglib` directive from web.xml maps tag uris to the physical location of your taglib. It is optional since JSP 2.0, as compliant containers will look in a set of standard locations to try to auto-discover the taglib: /WEB-INF and its subdirectories, /META-INF as well for JAR files. It looks like this, in web.xml: ``` <taglib> <taglib-uri> http://www.example.com/taglib </taglib-uri> <taglib-location> /taglib.tld </taglib-location> </taglib> ``` And the taglib is referenced in the JSP page like this (the taglib directive on each page is unavoidable!): ``` <%@ taglib prefix="ex" uri="http://www.example.com/taglib" %> ``` This is equivalent to the second example I gave for the taglib directive above. The biggest difference is in how you point to the taglib location. [This page](http://wiki.metawerx.net/wiki/Web.xml.TagLib) contains a bit more information.
226,528
<p>In Django templates, is there a variable in the context (e.g. <code>{{ BASE\_URL }}</code>, <code>{{ ROOT\_URL }}</code>, or <code>{{ MEDIA\_URL }}</code> that one can use to link to the <code>home</code> url of a project?</p> <p>I.e. if Django is running in the root of a project, the variable (let's call it R) <code>{{ R }}</code> in a template would be <code>/</code>. If the root url is a sub-folder <code>http://host/X/</code> the variable <code>{{ R }}</code> would be <code>/X/</code> (or <code>http://host/X/</code>).</p> <p>It seems painfully simple, but I can't find an answer. :) Thank you!</p>
[ { "answer_id": 226536, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 4, "selected": false, "text": "<p>I always use something like <code>&lt;a href=\"/\"&gt;</code> (assuming your home is at the root, of course). I seem to recall looking this up once, and couldn't find a Django variable for this path; at any rate, <code>/</code> seemed pretty easy, anyway.</p>\n" }, { "answer_id": 226540, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "<p>You could give the URL configuration which you're using to handle the home page a name and use that:</p>\n\n<p>urls.py:</p>\n\n<pre><code>from django.conf.urls.defaults import *\n\nurlpatterns = patterns('myproject.views',\n url(r'^$', 'index', name='index'),\n)\n</code></pre>\n\n<p>Templates:</p>\n\n<pre><code>&lt;a href=\"{% url index %}\"&gt;...\n</code></pre>\n\n<p><strong>UPDATE:</strong> Newer versions of Django require quotation marks around the name of the view:</p>\n\n<pre><code>&lt;a href=\"{% url 'index' %}\"&gt;...\n</code></pre>\n\n<p>This note in the Django Book has some tips about deploying your applications to a subdirectory:</p>\n\n<p><a href=\"http://www.djangobook.com/en/1.0/chapter20/#cn43\" rel=\"noreferrer\">http://www.djangobook.com/en/1.0/chapter20/#cn43</a></p>\n" }, { "answer_id": 226793, "author": "ryansholin", "author_id": 23980, "author_profile": "https://Stackoverflow.com/users/23980", "pm_score": 3, "selected": false, "text": "<p>In your admin, go to \"sites\" and set the domain.</p>\n\n<p>Pass <code>context_instance=RequestContext(request)</code> to the templates in question.</p>\n\n<p>Now use <code>{{ SITE_URL }}</code> in any of those templates and you're golden. </p>\n\n<p><a href=\"http://www.djangobook.com/en/1.0/chapter10/\" rel=\"noreferrer\">Chapter 10 of the Django Book</a> has more information than you'll need regading that context processor bit.</p>\n" }, { "answer_id": 3374528, "author": "justin jools", "author_id": 407048, "author_profile": "https://Stackoverflow.com/users/407048", "pm_score": 2, "selected": false, "text": "<pre><code>(r'^$', 'django.views.generic.simple.redirect_to', {'url': '/home/'}),\n</code></pre>\n\n<p>works fine :)</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
In Django templates, is there a variable in the context (e.g. `{{ BASE\_URL }}`, `{{ ROOT\_URL }}`, or `{{ MEDIA\_URL }}` that one can use to link to the `home` url of a project? I.e. if Django is running in the root of a project, the variable (let's call it R) `{{ R }}` in a template would be `/`. If the root url is a sub-folder `http://host/X/` the variable `{{ R }}` would be `/X/` (or `http://host/X/`). It seems painfully simple, but I can't find an answer. :) Thank you!
You could give the URL configuration which you're using to handle the home page a name and use that: urls.py: ``` from django.conf.urls.defaults import * urlpatterns = patterns('myproject.views', url(r'^$', 'index', name='index'), ) ``` Templates: ``` <a href="{% url index %}">... ``` **UPDATE:** Newer versions of Django require quotation marks around the name of the view: ``` <a href="{% url 'index' %}">... ``` This note in the Django Book has some tips about deploying your applications to a subdirectory: <http://www.djangobook.com/en/1.0/chapter20/#cn43>
226,555
<p>I am trying to make a view slide from top to bottom. This is not a big deal, I used <code>CABasicAnimation</code> for this. The problem is when I want to remove the view. I use this animation.</p> <pre><code>CABasicAnimation *animation; animation = [CABasicAnimation animationWithKeyPath:@"position"]; [animation setDelegate:self]; animation.toValue = [NSValue valueWithCGPoint:CGPointMake(self.view.layer.position.x, 0 - self.view.bounds.size.height / 2)]; animation.fromValue = [NSValue valueWithCGPoint:self.view.layer.position]; animation.autoreverses = NO; animation.repeatCount = 0; animation.duration = 0.25; animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]; [self.view.layer addAnimation:animation forKey:@"moveX"]; </code></pre> <p>Which animates the view perfectly. But, after the animation finishes, my view appears again. So I added this line :</p> <pre><code>[self.view removeFromSuperview]; </code></pre> <p>Which removes the view, but with no animation. So I decided to add the remove code to this delegate:</p> <pre><code>-(void) animationDidStop:(CAAnimation *) animation finished:(bool) flag </code></pre> <p>So now, the animation works, the view disappears, but sometimes, I can see the view appear and disappear faster, is like after the animation, the view appears, then the <code>animationDidStop</code> delegate is called, and the view disappears, obviously this is awful. What am I doing wrong?</p>
[ { "answer_id": 226645, "author": "Rob Drimmie", "author_id": 24213, "author_profile": "https://Stackoverflow.com/users/24213", "pm_score": -1, "selected": false, "text": "<p>Can you set the view's hidden property to YES?</p>\n\n<p>I think it would be:</p>\n\n<pre><code>self.view.hidden = YES;\n</code></pre>\n\n<p>But it might be:</p>\n\n<pre><code>[self.view setHidden:YES];\n</code></pre>\n\n<p>I turns out I am pretty lame at figuring out the proper way to access properties of properties.</p>\n" }, { "answer_id": 226707, "author": "danimal", "author_id": 29263, "author_profile": "https://Stackoverflow.com/users/29263", "pm_score": 0, "selected": false, "text": "<p>Setting the view to hidden as Rob suggests should do it. </p>\n\n<p>For properties of properties I would stick with the ObjC 2.0 style like you already have in your code. </p>\n\n<pre><code>set.view.hidden = YES;\n</code></pre>\n" }, { "answer_id": 226786, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 0, "selected": false, "text": "<p>This one bit me too. You want to set the animation's removedOnCompletion flag to NO. It defaults to YES, which means after the animation is complete, it's removed, and the view reverts to its initial state.</p>\n" }, { "answer_id": 227798, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 5, "selected": true, "text": "<p>Well, according to the Apple sample \"MoveMe\", this (<b>removedOnCompletion</b>) should work, however, it doesn't seem to. </p>\n\n<p>So, add these lines after your code:\n<code><pre>\n[self.view.layer addAnimation:animation forKey:@\"moveX\"];\nself.view.layer.position = [animation.toValue CGPointValue];\n</pre></code></p>\n\n<p>This ensures that after the animation runs, the layer is properly positioned.</p>\n" }, { "answer_id": 250754, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Might want to set these properties. They cause the presentation to be preserved at the end of the animation.</p>\n\n<p><code>animation.fillMode = kCAFillModeForwards;<br>\nanimation.removedOnCompletion = NO;</code></p>\n\n<p>Then the \"animationDidStop:\" method can be used to remove the view at the end of the animation:</p>\n\n<pre><code>-(void) animationDidStop:(CAAnimation *) animation finished:(bool) flag {\n if (animation == [containerView.layer animationForKey:@\"moveX\"]) {\n // remove view here, add another view and/or start another transition\n }\n}\n</code></pre>\n" }, { "answer_id": 15075455, "author": "FreeAsInBeer", "author_id": 632736, "author_profile": "https://Stackoverflow.com/users/632736", "pm_score": 2, "selected": false, "text": "<p>I had this issue when performing several animations in an animation group. I had to set a couple properties on the animation group itself, not the individual animations.</p>\n\n<pre><code>CAAnimationGroup *animGroup = [CAAnimationGroup animation];\n\n// MAKE SURE YOU HAVE THESE TWO LINES.\nanimGroup.removedOnCompletion = NO;\nanimGroup.fillMode = kCAFillModeForwards;\n\nanimGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim, nil];\nanimGroup.duration = tAnimationDuration;\n[tImageView.layer addAnimation:animGroup forKey:nil];\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29642/" ]
I am trying to make a view slide from top to bottom. This is not a big deal, I used `CABasicAnimation` for this. The problem is when I want to remove the view. I use this animation. ``` CABasicAnimation *animation; animation = [CABasicAnimation animationWithKeyPath:@"position"]; [animation setDelegate:self]; animation.toValue = [NSValue valueWithCGPoint:CGPointMake(self.view.layer.position.x, 0 - self.view.bounds.size.height / 2)]; animation.fromValue = [NSValue valueWithCGPoint:self.view.layer.position]; animation.autoreverses = NO; animation.repeatCount = 0; animation.duration = 0.25; animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]; [self.view.layer addAnimation:animation forKey:@"moveX"]; ``` Which animates the view perfectly. But, after the animation finishes, my view appears again. So I added this line : ``` [self.view removeFromSuperview]; ``` Which removes the view, but with no animation. So I decided to add the remove code to this delegate: ``` -(void) animationDidStop:(CAAnimation *) animation finished:(bool) flag ``` So now, the animation works, the view disappears, but sometimes, I can see the view appear and disappear faster, is like after the animation, the view appears, then the `animationDidStop` delegate is called, and the view disappears, obviously this is awful. What am I doing wrong?
Well, according to the Apple sample "MoveMe", this (**removedOnCompletion**) should work, however, it doesn't seem to. So, add these lines after your code: ```` [self.view.layer addAnimation:animation forKey:@"moveX"]; self.view.layer.position = [animation.toValue CGPointValue]; ```` This ensures that after the animation runs, the layer is properly positioned.
226,561
<p>The auto-collapse feature for <em>code</em> properties is neat AFTER you've got your properties all worked out, but while you're still editing them I find the feature to be REALLY annoying.</p> <p><strong>How can you disable it?</strong></p> <p>(I'm in VS2008 if it makes a difference)</p> <p>Edit: I'm not talking about the Property Window... I'm talking about properties in code.</p> <pre><code>Private _firstName As String Public Property FirstName() As String Implements IPerson.FirstName Get Return _firstName End Get Set(ByVal value As String) _firstName = value End Set End Property </code></pre> <p>displays as </p> <pre><code>Public Property FirstName()... </code></pre>
[ { "answer_id": 226673, "author": "matt.mercieca", "author_id": 30407, "author_profile": "https://Stackoverflow.com/users/30407", "pm_score": -1, "selected": false, "text": "<p>When the window is open, click on the pin in the upper right hand corner (the middle icon between the X and the down arrow). When you're done, click it again to enable auto hide again.</p>\n" }, { "answer_id": 226768, "author": "Shane Miskin", "author_id": 16415, "author_profile": "https://Stackoverflow.com/users/16415", "pm_score": 2, "selected": false, "text": "<p>From the EDIT menu, choose OUTLINING, STOP OUTLINING. You can also use the keyboard shortcut CTRL+M, CTRL+P.</p>\n" }, { "answer_id": 281371, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The stop outlining option never works for me. Also the Ctrl+M, Ctrl+M option only seems to work if I have the region collapsed highlighted. Ctrl+M, Ctrl+P does nothing for me. I went into options and unchecked the enter Outlining mode, but that didn't do anything either. At one point, when I had VS 2005 (now I have 2008), I managed to turn it off through a regedit hack. Though once I had to re-install VS 2005 and forgot the hack, so I've been living with this ever since. It's ultra annoying when you are looking for something where you are looking for a pattern of code and not the specific words of the code. I don't know why it is, but I do that a lot. Any helpwould be appreciated. Ty.</p>\n" }, { "answer_id": 986080, "author": "Tom Juergens", "author_id": 2899, "author_profile": "https://Stackoverflow.com/users/2899", "pm_score": 1, "selected": false, "text": "<p>This seems to be a \"feature\" of DevX Refactor for VB, which I also find <em>terribly</em> annoying. I found <a href=\"http://community.devexpress.com/forums/t/75568.aspx\" rel=\"nofollow noreferrer\">this thread</a> on their forum which provides a couple of suggested solutions:</p>\n\n<ul>\n<li>Add a key to the registry to make the DevExpress menu visible in VS and then go to the options page to disable auto-collapse or</li>\n<li>Install a newer version of the add-in (Release 9.1.4 or above) which apparently doesn't behave this way anymore.</li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
The auto-collapse feature for *code* properties is neat AFTER you've got your properties all worked out, but while you're still editing them I find the feature to be REALLY annoying. **How can you disable it?** (I'm in VS2008 if it makes a difference) Edit: I'm not talking about the Property Window... I'm talking about properties in code. ``` Private _firstName As String Public Property FirstName() As String Implements IPerson.FirstName Get Return _firstName End Get Set(ByVal value As String) _firstName = value End Set End Property ``` displays as ``` Public Property FirstName()... ```
From the EDIT menu, choose OUTLINING, STOP OUTLINING. You can also use the keyboard shortcut CTRL+M, CTRL+P.
226,562
<p>I am not very good with Regex but I am learning.</p> <p>I would like to remove some html tag by the class name. This is what I have so far :</p> <pre><code>&lt;div class=&quot;footer&quot;.*?&gt;(.*?)&lt;/div&gt; </code></pre> <p>The first .*? is because it might contain other attribute and the second is it might contain other html stuff.</p> <p>What am I doing wrong? I have try a lot of set without success.</p> <h3>Update</h3> <p>Inside the DIV it can contain multiple line and I am playing with Perl regex.</p>
[ { "answer_id": 226583, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 0, "selected": false, "text": "<p>Partly depends on the exact regex engine you are using - which language etc. But one possibility is that you need to escape the quotes and/or the forward slash. You might also want to make it case insensitive.</p>\n\n<pre><code>&lt;div class=\\\"footer\\\".*?&gt;(.*?)&lt;\\/div&gt;\n</code></pre>\n\n<p>Otherwise please say what language/platform you are using - .NET, java, perl ...</p>\n" }, { "answer_id": 226586, "author": "Nick", "author_id": 26161, "author_profile": "https://Stackoverflow.com/users/26161", "pm_score": -1, "selected": false, "text": "<p>why not <code>&lt;div class=\"footer\".*?&lt;/div&gt;</code> I'm not a regex guru either, but I don't think you need to specify that last bracket for your open div tag</p>\n" }, { "answer_id": 226591, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": true, "text": "<p>You will also want to allow for other things before class in the div tag</p>\n\n<pre><code>&lt;div[^&gt;]*class=\"footer\"[^&gt;]*&gt;(.*?)&lt;/div&gt;\n</code></pre>\n\n<p>Also, go case-insensitive. You may need to escape things like the quotes, or the slash in the closing tag. What context are you doing this in?</p>\n\n<p>Also note that HTML parsing with regular expressions can be very nasty, depending on the input. A good point is brought up in an answer below - suppose you have a structure like: </p>\n\n<pre><code>&lt;div&gt;\n &lt;div class=\"footer\"&gt;\n &lt;div&gt;Hi!&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Trying to build a regex for that is a recipe for disaster. Your best bet is to load the document into a DOM, and perform manipulations on that.</p>\n\n<p>Pseudocode that should map closely to XML::DOM:</p>\n\n<pre><code>document = //load document\ndivs = document.getElementsByTagName(\"div\");\nfor(div in divs) {\n if(div.getAttributes[\"class\"] == \"footer\") {\n parent = div.getParent();\n for(child in div.getChildren()) {\n // filter attribute types?\n parent.insertBefore(div, child);\n }\n parent.removeChild(div);\n }\n}\n</code></pre>\n\n<p><hr>\nHere is a perl library, <a href=\"http://search.cpan.org/dist/HTML-DOM/\" rel=\"noreferrer\">HTML::DOM</a>, and another, <a href=\"http://search.cpan.org/src/ENNO/libxml-enno-1.02/html/XML/DOM/Node.html\" rel=\"noreferrer\">XML::DOM</a><br>\n.NET has built-in libraries to handle dom parsing.</p>\n" }, { "answer_id": 226594, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;([^\\s]+).*?class=\"footer\".*?&gt;([.\\n]*?)&lt;/([^\\s]+)&gt;\n</code></pre>\n\n<p>Your biggest problem is going to be nested tags. For example:</p>\n\n<pre><code>&lt;div class=\"footer\"&gt;&lt;b&gt;&lt;/b&gt;&lt;/div&gt;\n</code></pre>\n\n<p>The regexp given would match everything through the <code>&lt;/b&gt;</code>, leaving the <code>&lt;/div&gt;</code> dangling on the end. You will have to either assume that the tag you're looking for has no nested elements, or you will need to use some sort of parser from HTML to DOM and an XPath query to remove an entire sub-tree.</p>\n" }, { "answer_id": 226601, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "<p>In Perl you need the <code>/s</code> modifier, otherwise the dot won't match a newline. </p>\n\n<p>That said, using a proper HTML or XML parser to remove unwanted parts of a HTML file is much more appropriate.</p>\n" }, { "answer_id": 226604, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 0, "selected": false, "text": "<p>This will be tricky because of the greediness of regular expressions, (Note that my examples <em>may</em> be specific to perl, but I know that greediness is a general issue with REs.) The second <code>.*?</code> will match as much as possible before the <code>&lt;/div&gt;</code>, so if you have the following:</p>\n\n<p><code>&lt;div class=\"SomethingElse\"&gt;&lt;div class=\"footer\"&gt; stuff &lt;/div&gt;&lt;/div&gt;</code></p>\n\n<p>The expression will match:</p>\n\n<p><code>&lt;div class=\"footer\"&gt; stuff &lt;/div&gt;&lt;/div&gt;</code></p>\n\n<p>which is not likely what you want.</p>\n" }, { "answer_id": 226669, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 4, "selected": false, "text": "<p>As other people said, HTML is notoriously tricky to deal with using regexes, and a DOM approach might be better. E.g.:</p>\n\n<pre><code>use HTML::TreeBuilder::XPath;\n\nmy $tree = HTML::TreeBuilder::XPath-&gt;new;\n$tree-&gt;parse_file( 'yourdocument.html' );\n\nfor my $node ( $tree-&gt;findnodes( '//*[@class=\"footer\"]' ) ) {\n $node-&gt;replace_with_content; # delete element, but not the children\n}\n\nprint $tree-&gt;as_HTML;\n</code></pre>\n" }, { "answer_id": 514525, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;div[^&gt;]*class=\"footer\"[^&gt;]*&gt;(.*?)&lt;/div&gt;\n</code></pre>\n\n<p>Worked for me, but needed to use backslashes before special characters </p>\n\n<pre><code>&lt;div[^&gt;]*class=\\\"footer\\\"[^&gt;]*&gt;(.*?)&lt;\\/div&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
I am not very good with Regex but I am learning. I would like to remove some html tag by the class name. This is what I have so far : ``` <div class="footer".*?>(.*?)</div> ``` The first .\*? is because it might contain other attribute and the second is it might contain other html stuff. What am I doing wrong? I have try a lot of set without success. ### Update Inside the DIV it can contain multiple line and I am playing with Perl regex.
You will also want to allow for other things before class in the div tag ``` <div[^>]*class="footer"[^>]*>(.*?)</div> ``` Also, go case-insensitive. You may need to escape things like the quotes, or the slash in the closing tag. What context are you doing this in? Also note that HTML parsing with regular expressions can be very nasty, depending on the input. A good point is brought up in an answer below - suppose you have a structure like: ``` <div> <div class="footer"> <div>Hi!</div> </div> </div> ``` Trying to build a regex for that is a recipe for disaster. Your best bet is to load the document into a DOM, and perform manipulations on that. Pseudocode that should map closely to XML::DOM: ``` document = //load document divs = document.getElementsByTagName("div"); for(div in divs) { if(div.getAttributes["class"] == "footer") { parent = div.getParent(); for(child in div.getChildren()) { // filter attribute types? parent.insertBefore(div, child); } parent.removeChild(div); } } ``` --- Here is a perl library, [HTML::DOM](http://search.cpan.org/dist/HTML-DOM/), and another, [XML::DOM](http://search.cpan.org/src/ENNO/libxml-enno-1.02/html/XML/DOM/Node.html) .NET has built-in libraries to handle dom parsing.
226,577
<p>Strange program hang, what does this mean in debug?</p> <p>After attaching windbg I found the following:</p> <pre> (1714.258): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=015b5c74 ebx=178a13e0 ecx=dddddddd edx=009a8ca0 esi=09fbf698 edi=09fbf594 eip=005ae2f7 esp=09fbf4a4 ebp=09fbf594 iopl=0 nv up ei ng nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010286 TestApplication!std::_Container_base::_Orphan_all+0x57: 005ae2f7 c70100000000 mov dword ptr [ecx],0 ds:0023:dddddddd=???????? </pre> <p>Call stack:</p> <pre> TestApplication!std::_Container_base::_Orphan_all+0x57 TestApplication!std::vector >::operator=+0x37 TestApplication!boost::asio::detail::win_iocp_io_service::do_one+0x189 TestApplication!boost::asio::detail::win_iocp_io_service::run+0xa2 TestApplication!boost::asio::io_service::run+0x3a </pre>
[ { "answer_id": 226590, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<p>The ecx register has an invalid address (dddddddd). I would suggest this is a case of memory corruption. Consider turning gflags on for the process.</p>\n" }, { "answer_id": 226659, "author": "MSN", "author_id": 6210, "author_profile": "https://Stackoverflow.com/users/6210", "pm_score": 3, "selected": false, "text": "<p>If you are using MSVC and the Debug build configuration, <code>0xdddddddd</code> usually means that you are attempting to access freed memory. The debug CRT memory manager fills free memory with <code>0xdd</code>.</p>\n" }, { "answer_id": 226674, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 3, "selected": true, "text": "<p><strong>The problem</strong></p>\n\n<ol>\n<li><p>First chance exceptions means that the debugger is giving you, the person who is using the debugger, the first chance to debug the exception, before it throws it back at the program to handle the issue.</p></li>\n<li><p>In this case the exception is \"Access violation\". This means that your program is trying to read / write from an illegal memory location. </p></li>\n<li><p>Access violations are serious coz it could be corrupting some memory which is critical for your program and this would be the likely reason that your program hangs. </p></li>\n<li><p>From the faulting instruction it seems as if you are trying to get the contents of a 4 byte value from an illegal instruction. </p></li>\n</ol>\n\n<p><strong>Debugging the Problem</strong></p>\n\n<ol start=\"5\">\n<li><p>If this is your code then you can easily debug this issue by setting the debug symbol location to the output folder of your compiler (this would contain the relevant pdb files)</p></li>\n<li><p>When you get this exception get the call stack (one of the view windows would have it)</p></li>\n<li><p>This would show you the location in your code where the faulting stack has originated. </p></li>\n<li><p>Now open the file that contains this source and set a breakpoint there and the program would hit this point and stop inside the windebugger. Debug from this point and you would know exactly from which line of code this violation is thrown</p></li>\n</ol>\n\n<p>Tip : Boost comes with source so you can easily put a break point inside this code. Be sure to press F11 while debugging when you get to asio::detail::win_iocp_io_service::do_one. </p>\n" }, { "answer_id": 227239, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The callstack is entirely STL/Boost code. Unless something what you're doing is out of the ordinary, I wont assume that the bug is in any section of the callstack you pasted.</p>\n\n<p>A couple of things to check:</p>\n\n<ol>\n<li><p>Any Boost specific #defines that should be defined but arent?</p></li>\n<li><p>Secure SCL &amp; Iterator debugging. Try enabling/disabling it.</p></li>\n<li><p>Are you mixing debug &amp; release code. (bad idea with STL/Boost containers)</p></li>\n</ol>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
Strange program hang, what does this mean in debug? After attaching windbg I found the following: ``` (1714.258): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. eax=015b5c74 ebx=178a13e0 ecx=dddddddd edx=009a8ca0 esi=09fbf698 edi=09fbf594 eip=005ae2f7 esp=09fbf4a4 ebp=09fbf594 iopl=0 nv up ei ng nz na pe nc cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010286 TestApplication!std::_Container_base::_Orphan_all+0x57: 005ae2f7 c70100000000 mov dword ptr [ecx],0 ds:0023:dddddddd=???????? ``` Call stack: ``` TestApplication!std::_Container_base::_Orphan_all+0x57 TestApplication!std::vector >::operator=+0x37 TestApplication!boost::asio::detail::win_iocp_io_service::do_one+0x189 TestApplication!boost::asio::detail::win_iocp_io_service::run+0xa2 TestApplication!boost::asio::io_service::run+0x3a ```
**The problem** 1. First chance exceptions means that the debugger is giving you, the person who is using the debugger, the first chance to debug the exception, before it throws it back at the program to handle the issue. 2. In this case the exception is "Access violation". This means that your program is trying to read / write from an illegal memory location. 3. Access violations are serious coz it could be corrupting some memory which is critical for your program and this would be the likely reason that your program hangs. 4. From the faulting instruction it seems as if you are trying to get the contents of a 4 byte value from an illegal instruction. **Debugging the Problem** 5. If this is your code then you can easily debug this issue by setting the debug symbol location to the output folder of your compiler (this would contain the relevant pdb files) 6. When you get this exception get the call stack (one of the view windows would have it) 7. This would show you the location in your code where the faulting stack has originated. 8. Now open the file that contains this source and set a breakpoint there and the program would hit this point and stop inside the windebugger. Debug from this point and you would know exactly from which line of code this violation is thrown Tip : Boost comes with source so you can easily put a break point inside this code. Be sure to press F11 while debugging when you get to asio::detail::win\_iocp\_io\_service::do\_one.
226,587
<p><strong>NOTE:</strong> Using .NET 2.0, and VS2005 as IDE</p> <p>Hello all,</p> <p>I'm working on logging webservice calls to our database, and finally got the SoapExtension configured and running using a very stripped-down implementation that was ported over from another project. I've set it up in the configuration file so it will run for all methods. When I call my webservice, and the soap extension fires, a NullPointerException is thrown when the SoapServerMessage attempts to call its MethodInfo property:</p> <pre><code>System.Web.Services.Protocols.SoapException: There was an exception running the extensions specified in the config file. ---&gt; System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Services.Protocols.SoapServerProtocol.get_MethodInfo() at System.Web.Services.Protocols.SoapServerMessage.get_MethodInfo() at MyService.SOAPLoggingExtension.LogInput(SoapMessage message) at MyService.SOAPLoggingExtension.ProcessMessage(SoapMessage message) at System.Web.Services.Protocols.SoapMessage.RunExtensions(SoapExtension[] extensions, Boolean throwOnException) at System.Web.Services.Protocols.SoapServerProtocol.Initialize() --- End of inner exception stack trace --- at System.Web.Services.Protocols.SoapServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing) </code></pre> <p>The LogInput method is called during the BeforeDeserialize stage of ProcessMessage(SoapMessage):</p> <pre><code>SoapMessageStage.BeforeDeserialize: CopyStream(_oldStream, _newStream); _newStream.Position = 0; if(_enabled) LogInput(message); break; </code></pre> <p>And the LogInput method is failing when attempting to access the MethodInfo property of the message object it is trying to log. Here is the block of code where the property is called:</p> <pre><code>entry = new MyServerLogEntry(); entry.ServerURL = message.Url; entry.Method = (message.MethodInfo == null) ? null : message.MethodInfo.Name; </code></pre> <p>When message.MethodInfo is called, it bubbles over to SoapServerProtocol.get_MethodInfo(), and the null reference exception gets thrown in there. I've googled, and checked around here on Stack Overflow, but haven't been able to find out why the MethodInfo property would be throwing an exception.</p> <p>Does anyone know how to ensure this MethodInfo property is properly initialized during the web service call?</p> <p><strong>ADDITIONAL DETAILS:</strong> If I do not attempt to access the MethodInfo property, the extension works correctly and logs to my database.</p>
[ { "answer_id": 226800, "author": "Jay S", "author_id": 30440, "author_profile": "https://Stackoverflow.com/users/30440", "pm_score": 3, "selected": true, "text": "<p>After some trial and error, I have been able to solve this issue. While I do not entirely understand why, the SoapMessage object is not completely initialized at the BeforeDeserialize stage. Both the Action and MethodInfo properties throw errors at this stage.</p>\n\n<p>However, during the AfterSerialize stage, these objects seem to be properly initialized. By moving the line which reads the message name to a later stage, the log entry object can be properly filled without throwing an exception.</p>\n\n<p>It appears the correct order is:</p>\n\n<ol>\n<li><p>BeforeDeserialize</p>\n\n<p>a. Read Server URL</p>\n\n<p>b. Retrieve request information (certificates, user host address, etc.)</p>\n\n<p>c. Read request contents from stream</p></li>\n<li><p>AfterSerialize</p>\n\n<p>a. Read Exceptions</p>\n\n<p>b. Read MethodInfo information (and Action information if necessary)</p>\n\n<p>c. Read response contents from stream</p></li>\n</ol>\n" }, { "answer_id": 226857, "author": "Thedric Walker", "author_id": 26166, "author_profile": "https://Stackoverflow.com/users/26166", "pm_score": 1, "selected": false, "text": "<p>According to MSDN the method information is only available during AfterDeserialization and BeforeSerialization. So that would be part of the problem.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30440/" ]
**NOTE:** Using .NET 2.0, and VS2005 as IDE Hello all, I'm working on logging webservice calls to our database, and finally got the SoapExtension configured and running using a very stripped-down implementation that was ported over from another project. I've set it up in the configuration file so it will run for all methods. When I call my webservice, and the soap extension fires, a NullPointerException is thrown when the SoapServerMessage attempts to call its MethodInfo property: ``` System.Web.Services.Protocols.SoapException: There was an exception running the extensions specified in the config file. ---> System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Services.Protocols.SoapServerProtocol.get_MethodInfo() at System.Web.Services.Protocols.SoapServerMessage.get_MethodInfo() at MyService.SOAPLoggingExtension.LogInput(SoapMessage message) at MyService.SOAPLoggingExtension.ProcessMessage(SoapMessage message) at System.Web.Services.Protocols.SoapMessage.RunExtensions(SoapExtension[] extensions, Boolean throwOnException) at System.Web.Services.Protocols.SoapServerProtocol.Initialize() --- End of inner exception stack trace --- at System.Web.Services.Protocols.SoapServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) ``` The LogInput method is called during the BeforeDeserialize stage of ProcessMessage(SoapMessage): ``` SoapMessageStage.BeforeDeserialize: CopyStream(_oldStream, _newStream); _newStream.Position = 0; if(_enabled) LogInput(message); break; ``` And the LogInput method is failing when attempting to access the MethodInfo property of the message object it is trying to log. Here is the block of code where the property is called: ``` entry = new MyServerLogEntry(); entry.ServerURL = message.Url; entry.Method = (message.MethodInfo == null) ? null : message.MethodInfo.Name; ``` When message.MethodInfo is called, it bubbles over to SoapServerProtocol.get\_MethodInfo(), and the null reference exception gets thrown in there. I've googled, and checked around here on Stack Overflow, but haven't been able to find out why the MethodInfo property would be throwing an exception. Does anyone know how to ensure this MethodInfo property is properly initialized during the web service call? **ADDITIONAL DETAILS:** If I do not attempt to access the MethodInfo property, the extension works correctly and logs to my database.
After some trial and error, I have been able to solve this issue. While I do not entirely understand why, the SoapMessage object is not completely initialized at the BeforeDeserialize stage. Both the Action and MethodInfo properties throw errors at this stage. However, during the AfterSerialize stage, these objects seem to be properly initialized. By moving the line which reads the message name to a later stage, the log entry object can be properly filled without throwing an exception. It appears the correct order is: 1. BeforeDeserialize a. Read Server URL b. Retrieve request information (certificates, user host address, etc.) c. Read request contents from stream 2. AfterSerialize a. Read Exceptions b. Read MethodInfo information (and Action information if necessary) c. Read response contents from stream
226,596
<p>What's the best way to initialize an array in PowerShell?</p> <p>For example, the code</p> <pre><code>$array = @() for($i=0; $i -lt 5;$i++) { $array[$i] = $FALSE } </code></pre> <p>generates the error</p> <pre><code>Array assignment failed because index '0' was out of range. At H:\Software\PowerShell\TestArray.ps1:4 char:10 + $array[$ &lt;&lt;&lt;&lt; i] = $FALSE </code></pre>
[ { "answer_id": 226600, "author": "Eric Ness", "author_id": 18891, "author_profile": "https://Stackoverflow.com/users/18891", "pm_score": 3, "selected": false, "text": "<p>The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.</p>\n\n<pre><code>$array = new-object object[] 5 \nfor($i=0; $i -lt $array.Length;$i++)\n{\n $array[$i] = $FALSE\n}\n</code></pre>\n" }, { "answer_id": 226631, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": false, "text": "<p>If I don't know the size up front, I use an arraylist instead of an array.</p>\n\n<pre><code>$al = New-Object System.Collections.ArrayList\nfor($i=0; $i -lt 5; $i++)\n{\n $al.Add($i)\n}\n</code></pre>\n" }, { "answer_id": 226649, "author": "David Mohundro", "author_id": 4570, "author_profile": "https://Stackoverflow.com/users/4570", "pm_score": 7, "selected": true, "text": "<p>Yet another alternative:</p>\n\n<pre><code>for ($i = 0; $i -lt 5; $i++) \n{ \n $arr += @($false) \n}\n</code></pre>\n\n<p>This one works if $arr isn't defined yet.</p>\n\n<p><strong>NOTE</strong> - there are better (and more performant) ways to do this... see <a href=\"https://stackoverflow.com/a/234060/4570\">https://stackoverflow.com/a/234060/4570</a> below as an example.</p>\n" }, { "answer_id": 226657, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 4, "selected": false, "text": "<pre><code>$array = @()\nfor($i=0; $i -lt 5; $i++)\n{\n $array += $i\n}\n</code></pre>\n" }, { "answer_id": 226947, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 6, "selected": false, "text": "<p>You can also rely on the <strong>default value of the constructor</strong> if you wish to create a typed array:</p>\n\n<pre><code>&gt; $a = new-object bool[] 5\n&gt; $a\nFalse\nFalse\nFalse\nFalse\nFalse\n</code></pre>\n\n<p>The default value of a <strong>bool</strong> is apparently <strong>false</strong> so this works in your case. Likewise if you create a typed <strong>int[]</strong> array, you'll get the default value of 0.</p>\n\n<p>Another cool way that I use to initialze arrays is with the following shorthand:</p>\n\n<pre><code>&gt; $a = ($false, $false, $false, $false, $false)\n&gt; $a\nFalse\nFalse\nFalse\nFalse\nFalse\n</code></pre>\n\n<p>Or if you can you want to initialize a range, I've sometimes found this useful:</p>\n\n<pre>\n> $a = (1..5) \n> $a\n1\n2\n3\n4\n5\n</pre>\n\n<p>Hope this was somewhat helpful!</p>\n" }, { "answer_id": 230195, "author": "Peter Seale", "author_id": 25911, "author_profile": "https://Stackoverflow.com/users/25911", "pm_score": 4, "selected": false, "text": "<pre><code>$array = 1..5 | foreach { $false }\n</code></pre>\n" }, { "answer_id": 234060, "author": "halr9000", "author_id": 6637, "author_profile": "https://Stackoverflow.com/users/6637", "pm_score": 7, "selected": false, "text": "<p>Here's two more ways, both very concise.</p>\n\n<pre><code>$arr1 = @(0) * 20\n$arr2 = ,0 * 20\n</code></pre>\n" }, { "answer_id": 28015246, "author": "Celery Man", "author_id": 4467899, "author_profile": "https://Stackoverflow.com/users/4467899", "pm_score": 5, "selected": false, "text": "<p>The original example returns an error because the array is created empty, then you try to access the nth element to assign it a value. </p>\n\n<p>The are a number of creative answers here, many I didn't know before reading this post. All are fine for a small array, but as n0rd points out, there are significant differences in performance. </p>\n\n<p>Here I use Measure-Command to find out how long each initialization takes. As you might guess, any approach that uses an explicit PowerShell loop is slower than those that use .Net constructors or PowerShell operators (which would be compiled in IL or native code).</p>\n\n<h2>Summary</h2>\n\n<ul>\n<li><code>New-Object</code> and <code>@(somevalue)*n</code> are fast (around 20k ticks for 100k elements). </li>\n<li>Creating an array with the range operator <code>n..m</code> is 10x slower (200k ticks). </li>\n<li>Using an ArrayList with the <code>Add()</code> method is 1000x slower than the baseline (20M ticks), as is looping through an already-sized array using <code>for()</code> or <code>ForEach-Object</code> (a.k.a. <code>foreach</code>,<code>%</code>). </li>\n<li>Appending with <code>+=</code> is the worst (2M ticks for just 1000 elements). </li>\n</ul>\n\n<p>Overall, I'd say <strong><em>array</em>*<em>n</em></strong> is \"best\" because: </p>\n\n<ul>\n<li>It's fast.</li>\n<li>You can use any value, not just the default for the type.</li>\n<li>You can create repeating values (to illustrate, type this at the powershell prompt: <code>(1..10)*10 -join \" \"</code> or <code>('one',2,3)*3</code>)</li>\n<li>Terse syntax. </li>\n</ul>\n\n<p>The only drawback: </p>\n\n<ul>\n<li>Non-obvious. If you haven't seen this construct before, it's not apparent what it does. </li>\n</ul>\n\n<p>But keep in mind that for many cases where you would want to initialize the array elements to some value, then a strongly-typed array is exactly what you need. If you're initializing everything to <code>$false</code>, then is the array ever going to hold anything other than <code>$false</code> or <code>$true</code>? If not, then <code>New-Object type[] n</code> is the \"best\" approach. </p>\n\n<h2>Testing</h2>\n\n<p>Create and size a default array, then assign values: </p>\n\n<pre><code>PS&gt; Measure-Command -Expression {$a = new-object object[] 100000} | Format-List -Property \"Ticks\"\nTicks : 20039\n\nPS&gt; Measure-Command -Expression {for($i=0; $i -lt $a.Length;$i++) {$a[$i] = $false}} | Format-List -Property \"Ticks\"\nTicks : 28866028\n</code></pre>\n\n<p>Creating an array of Boolean is bit little slower than and array of Object: </p>\n\n<pre><code>PS&gt; Measure-Command -Expression {$a = New-Object bool[] 100000} | Format-List -Property \"Ticks\"\nTicks : 130968\n</code></pre>\n\n<p>It's not obvious what this does, the documentation for New-Object just says that the second parameter is an argument list which is passed to the .Net object constructor. In the case of arrays, the parameter evidently is the desired size. </p>\n\n<p>Appending with +=</p>\n\n<pre><code>PS&gt; $a=@()\nPS&gt; Measure-Command -Expression { for ($i=0; $i -lt 100000; $i++) {$a+=$false} } | Format-List -Property \"Ticks\"\n</code></pre>\n\n<p>I got tired of waiting for that to complete, so ctrl+c then: </p>\n\n<pre><code>PS&gt; $a=@()\nPS&gt; Measure-Command -Expression { for ($i=0; $i -lt 100; $i++) {$a+=$false} } | Format-List -Property \"Ticks\"\nTicks : 147663\nPS&gt; $a=@()\nPS&gt; Measure-Command -Expression { for ($i=0; $i -lt 1000; $i++) {$a+=$false} } | Format-List -Property \"Ticks\"\nTicks : 2194398\n</code></pre>\n\n<p>Just as (6 * 3) is conceptually similar to (6 + 6 + 6), so ($somearray * 3) ought to give the same result as ($somearray + $somearray + $somearray). But with arrays, + is concatenation rather than addition. </p>\n\n<p>If $array+=$element is slow, you might expect $array*$n to also be slow, but it's not: </p>\n\n<pre><code>PS&gt; Measure-Command -Expression { $a = @($false) * 100000 } | Format-List -Property \"Ticks\"\nTicks : 20131\n</code></pre>\n\n<p>Just like Java has a StringBuilder class to avoid creating multiple objects when appending, so it seems PowerShell has an ArrayList. </p>\n\n<pre><code>PS&gt; $al = New-Object System.Collections.ArrayList\nPS&gt; Measure-Command -Expression { for($i=0; $i -lt 1000; $i++) {$al.Add($false)} } | Format-List -Property \"Ticks\"\nTicks : 447133\nPS&gt; $al = New-Object System.Collections.ArrayList\nPS&gt; Measure-Command -Expression { for($i=0; $i -lt 10000; $i++) {$al.Add($false)} } | Format-List -Property \"Ticks\"\nTicks : 2097498\nPS&gt; $al = New-Object System.Collections.ArrayList\nPS&gt; Measure-Command -Expression { for($i=0; $i -lt 100000; $i++) {$al.Add($false)} } | Format-List -Property \"Ticks\"\nTicks : 19866894\n</code></pre>\n\n<p>Range operator, and <code>Where-Object</code> loop: </p>\n\n<pre><code>PS&gt; Measure-Command -Expression { $a = 1..100000 } | Format-List -Property \"Ticks\"\nTicks : 239863\nMeasure-Command -Expression { $a | % {$false} } | Format-List -Property \"Ticks\"\nTicks : 102298091\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>I nulled the variable between each run (<code>$a=$null</code>).</li>\n<li>Testing was on a tablet with Atom processor; you would probably see faster speeds on other machines. [edit: About twice as fast on a desktop machine.]</li>\n<li>There was a fair bit of variation when I tried multiple runs. Look for the orders of magnitude rather than exact numbers. </li>\n<li>Testing was with PowerShell 3.0 in Windows 8. </li>\n</ul>\n\n<h2>Acknowledgements</h2>\n\n<p>Thanks to @halr9000 for array*n, @Scott Saad and Lee Desmond for New-Object, and @EBGreen for ArrayList.</p>\n\n<p>Thanks to @n0rd for getting me to think about performance. </p>\n" }, { "answer_id": 34995276, "author": "AdamL", "author_id": 1980228, "author_profile": "https://Stackoverflow.com/users/1980228", "pm_score": 4, "selected": false, "text": "<p>Here's another idea. You have to remember, that it's .NET underneath:</p>\n\n<pre><code>$arr = [System.Array]::CreateInstance([System.Object], 5)\n$arr.GetType()\n$arr.Length\n\n$arr = [Object[]]::new(5)\n$arr.GetType()\n$arr.Length\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>IsPublic IsSerial Name BaseType \n-------- -------- ---- -------- \nTrue True Object[] System.Array \n5\nTrue True Object[] System.Array \n5\n</code></pre>\n\n<p>Using <code>new()</code> has one distinct advantage: when you're programming in ISE and want to create an object, ISE will give you hint with all paramer combinations and their types. You don't have that with <code>New-Object</code>, where you have to remember the types and order of arguments. </p>\n\n<p><a href=\"https://i.stack.imgur.com/QEUCF.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QEUCF.jpg\" alt=\"ISE IntelliSense for new object\"></a></p>\n" }, { "answer_id": 52958445, "author": "Michael Koza", "author_id": 10548845, "author_profile": "https://Stackoverflow.com/users/10548845", "pm_score": 0, "selected": false, "text": "<p>Or try this an idea. Works with powershell 5.0+.</p>\n\n<pre><code>[bool[]]$tf=((,$False)*5)\n</code></pre>\n" }, { "answer_id": 58343378, "author": "js2010", "author_id": 6654942, "author_profile": "https://Stackoverflow.com/users/6654942", "pm_score": 1, "selected": false, "text": "<p>Here's another typical way:</p>\n\n<pre><code>$array = for($i = 0; $i -le 4; $i++) { $false }\n</code></pre>\n" }, { "answer_id": 69179109, "author": "MarredCheese", "author_id": 5405967, "author_profile": "https://Stackoverflow.com/users/5405967", "pm_score": 0, "selected": false, "text": "<pre><code>$array = foreach($i in 1..5) { $false }\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18891/" ]
What's the best way to initialize an array in PowerShell? For example, the code ``` $array = @() for($i=0; $i -lt 5;$i++) { $array[$i] = $FALSE } ``` generates the error ``` Array assignment failed because index '0' was out of range. At H:\Software\PowerShell\TestArray.ps1:4 char:10 + $array[$ <<<< i] = $FALSE ```
Yet another alternative: ``` for ($i = 0; $i -lt 5; $i++) { $arr += @($false) } ``` This one works if $arr isn't defined yet. **NOTE** - there are better (and more performant) ways to do this... see <https://stackoverflow.com/a/234060/4570> below as an example.
226,599
<p>So I have xml that looks like this: </p> <pre class="lang-html prettyprint-override"><code>&lt;todo-list&gt; &lt;id type="integer"&gt;#{id}&lt;/id&gt; &lt;name&gt;#{name}&lt;/name&gt; &lt;description&gt;#{description}&lt;/description&gt; &lt;project-id type="integer"&gt;#{project_id}&lt;/project-id&gt; &lt;milestone-id type="integer"&gt;#{milestone_id}&lt;/milestone-id&gt; &lt;position type="integer"&gt;#{position}&lt;/position&gt; &lt;!-- if user can see private lists --&gt; &lt;private type="boolean"&gt;#{private}&lt;/private&gt; &lt;!-- if the account supports time tracking --&gt; &lt;tracked type="boolean"&gt;#{tracked}&lt;/tracked&gt; &lt;!-- if todo-items are included in the response --&gt; &lt;todo-items type="array"&gt; &lt;todo-item&gt; ... &lt;/todo-item&gt; &lt;todo-item&gt; ... &lt;/todo-item&gt; ... &lt;/todo-items&gt; &lt;/todo-list&gt; </code></pre> <p>How would I go about using .NET's serialization library to deserialize this into C# objects? </p> <p>Currently I'm using reflection and I map between the xml and my objects using the naming conventions.</p>
[ { "answer_id": 226614, "author": "Steve Horn", "author_id": 10589, "author_profile": "https://Stackoverflow.com/users/10589", "pm_score": 5, "selected": false, "text": "<p>Boils down to using xsd.exe from tools in VS:</p>\n\n<pre><code>xsd.exe \"%xsdFile%\" /c /out:\"%outDirectory%\" /l:\"%language%\"\n</code></pre>\n\n<p>Then load it with reader and deserializer:</p>\n\n<pre><code>public GeneratedClassFromXSD GetObjectFromXML()\n{\n var settings = new XmlReaderSettings();\n var obj = new GeneratedClassFromXSD();\n var reader = XmlReader.Create(urlToService, settings);\n var serializer = new System.Xml.Serialization.XmlSerializer(typeof(GeneratedClassFromXSD));\n obj = (GeneratedClassFromXSD)serializer.Deserialize(reader);\n\n reader.Close();\n return obj;\n}\n</code></pre>\n" }, { "answer_id": 226620, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>There are a couple different options.</p>\n\n<ul>\n<li>Visual Studio includes a command line program called xsd.exe. You use that program to create a schema document, and use the program again on the schema document to creates classes you can use with <code>system.xml.serialization.xmlserializer</code></li>\n<li>You might just be able to call Dataset.ReadXml() on it.</li>\n</ul>\n" }, { "answer_id": 226626, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Well, you'd have to have classes in your assembly that match, roughly, the XML (property called Private, a collection property called ToDo, etc).</p>\n\n<p>The problem is that <strong>the XML has elements that are invalid for class names</strong>. So you'd have to implement IXmlSerializable in these classes to control how they are serialized to and from XML. You might be able to get away with using some of the xml serialization specific attributes as well, but that depends on your xml's schema.</p>\n\n<p>That's a step above using reflection, but it might not be exactly what you're hoping for.</p>\n" }, { "answer_id": 226628, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 7, "selected": true, "text": "<p>Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement(\"todo-list\") attribute.</p>\n\n<p>A shourtcut is to load your XML into Visual Studio, click the \"Infer Schema\" button and run \"xsd.exe /c schema.xsd\" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.</p>\n" }, { "answer_id": 2649694, "author": "Deepfreezed", "author_id": 318089, "author_profile": "https://Stackoverflow.com/users/318089", "pm_score": 2, "selected": false, "text": "<p>Checkout <a href=\"http://xsd2code.codeplex.com/\" rel=\"nofollow noreferrer\">http://xsd2code.codeplex.com/</a></p>\n\n<p>Xsd2Code is a CSharp or Visual Basic Business Entity class Generator from XSD schema.</p>\n" }, { "answer_id": 12556344, "author": "Keith", "author_id": 65775, "author_profile": "https://Stackoverflow.com/users/65775", "pm_score": 4, "selected": false, "text": "<p>Deserialize any object, as long as the type <code>T</code> is marked Serializable:</p>\n\n<pre><code>function T Deserialize&lt;T&gt;(string serializedResults)\n{\n var serializer = new XmlSerializer(typeof(T));\n using (var stringReader = new StringReader(serializedResults))\n return (T)serializer.Deserialize(stringReader);\n}\n</code></pre>\n" }, { "answer_id": 12563479, "author": "Savaratkar", "author_id": 942301, "author_profile": "https://Stackoverflow.com/users/942301", "pm_score": -1, "selected": false, "text": "<p>i had the same questions few years back that how abt mapping xml to C# classes or creating C# classes which are mapped to our XMLs, jst like we do in entity Framework (we map tables to C# classes). I created a framework finally, which can create C# classes out of your XML and these classes can be used to read/write your xml. Have a <a href=\"http://www.stepupframeworks.com/Home/products/xml-object-mapping-xom/\" rel=\"nofollow\">look</a></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401/" ]
So I have xml that looks like this: ```html <todo-list> <id type="integer">#{id}</id> <name>#{name}</name> <description>#{description}</description> <project-id type="integer">#{project_id}</project-id> <milestone-id type="integer">#{milestone_id}</milestone-id> <position type="integer">#{position}</position> <!-- if user can see private lists --> <private type="boolean">#{private}</private> <!-- if the account supports time tracking --> <tracked type="boolean">#{tracked}</tracked> <!-- if todo-items are included in the response --> <todo-items type="array"> <todo-item> ... </todo-item> <todo-item> ... </todo-item> ... </todo-items> </todo-list> ``` How would I go about using .NET's serialization library to deserialize this into C# objects? Currently I'm using reflection and I map between the xml and my objects using the naming conventions.
Create a class for each element that has a property for each element and a List or Array of objects (use the created one) for each child element. Then call System.Xml.Serialization.XmlSerializer.Deserialize on the string and cast the result as your object. Use the System.Xml.Serialization attributes to make adjustments, like to map the element to your ToDoList class, use the XmlElement("todo-list") attribute. A shourtcut is to load your XML into Visual Studio, click the "Infer Schema" button and run "xsd.exe /c schema.xsd" to generate the classes. xsd.exe is in the tools folder. Then go through the generated code and make adjustments, such as changing shorts to ints where appropriate.
226,618
<p>How can I transform a time value into YYYY-MM-DD format in Java?</p> <pre><code>long lastmodified = file.lastModified(); String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/ </code></pre>
[ { "answer_id": 226638, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 6, "selected": true, "text": "<p>Something like:</p>\n\n<pre><code>Date lm = new Date(lastmodified);\nString lasmod = new SimpleDateFormat(\"yyyy-MM-dd\").format(lm);\n</code></pre>\n\n<p>See the javadoc for <a href=\"http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html\" rel=\"noreferrer\">SimpleDateFormat</a>.</p>\n" }, { "answer_id": 226650, "author": "Instantsoup", "author_id": 9861, "author_profile": "https://Stackoverflow.com/users/9861", "pm_score": 2, "selected": false, "text": "<pre><code>String lasmod = new SimpleDateFormat(\"yyyy-MM-dd\").format(new Date(lastmodified));\n</code></pre>\n\n<p>Look up the correct pattern you want for SimpleDateFormat... I may have included the wrong one from memory.</p>\n" }, { "answer_id": 226651, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<pre><code>Date d = new Date(lastmodified);\nDateFormat form = new SimpleDateFormat(\"yyyy-MM-dd\");\nString lasmod = form.format(d);\n</code></pre>\n" }, { "answer_id": 226653, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 2, "selected": false, "text": "<pre><code>final Date modDate = new Date(lastmodified);\nfinal SimpleDateFormat f = new SimpleDateFormat(\"yyyy-MM-dd\");\nfinal String lasmod = f.format(modDate);\n</code></pre>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html\" rel=\"nofollow noreferrer\">SimpleDateFormat</a></p>\n" }, { "answer_id": 226662, "author": "James Cooper", "author_id": 25198, "author_profile": "https://Stackoverflow.com/users/25198", "pm_score": 1, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>import java.text.SimpleDateFormat;\nimport java.util.Date;\n\nlong lastmodified = file.lastModified();\nSimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\nString lastmod = format.format(new Date(lastmodified));\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
How can I transform a time value into YYYY-MM-DD format in Java? ``` long lastmodified = file.lastModified(); String lasmod = /*TODO: Transform it to this format YYYY-MM-DD*/ ```
Something like: ``` Date lm = new Date(lastmodified); String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm); ``` See the javadoc for [SimpleDateFormat](http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html).
226,637
<p>On a page from a website (one of ours) I can enter in the url the following code:</p> <pre><code>javascript:createNewWindow('Something', 100, 100, 'Text') </code></pre> <p>Is there a way someone can exploit this?</p> <pre><code>function createNewWindow(url, widthIn, heightIn, title) { var strOptions='toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width=' + widthIn + ',height=' + heightIn; var newWin = open( url,title,strOptions ); newWin.focus(); } </code></pre>
[ { "answer_id": 226877, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 1, "selected": false, "text": "<p>Given that code, the createNewWindow() script isn't any more vulnerable than the raw javascript. </p>\n" }, { "answer_id": 226882, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 1, "selected": false, "text": "<p>The function createNewWindow() has exactly the same vulnerabilities as window.open(). You probably don't need to be concerned about that.</p>\n\n<p>If your comment about adding the code means that you were able to submit</p>\n\n<pre><code>javascript:createNewWindow('Something', 100, 100, 'Text')\n</code></pre>\n\n<p>in a form input (or as a query string parameter) and have it show up in the rendered HTML, then your application is indeed very vulnerable to several types of attacks, but not due to the createNewWindow() function. In that case, the problem would be rendering unchecked data from the browser.</p>\n" }, { "answer_id": 599252, "author": "Diego Jancic", "author_id": 72350, "author_profile": "https://Stackoverflow.com/users/72350", "pm_score": 1, "selected": false, "text": "<p>That will be not unsafe itself, you need to take care in the other parts of the application to prevent exploits. Be sure to validate all the information that becomes from the browser, your database, an external service, an anything else that you do not control.</p>\n\n<p>Learning about Cross-Site-Scripting (aka XSS or CSS) will help you understand the risks of that code.</p>\n" }, { "answer_id": 2163742, "author": "rook", "author_id": 183528, "author_profile": "https://Stackoverflow.com/users/183528", "pm_score": 0, "selected": false, "text": "<p>In general javascript running on your site is not the source of vulnerabilities. You should be worrying about the server side of the application.</p>\n\n<p>However! You can introduce vulnerabilities into your site using javascript. Its called <a href=\"http://www.owasp.org/index.php/DOM_Based_XSS\" rel=\"nofollow noreferrer\">DOM Based XSS</a>. The code you posted isn't vulnerable to DOM Based XSS.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357/" ]
On a page from a website (one of ours) I can enter in the url the following code: ``` javascript:createNewWindow('Something', 100, 100, 'Text') ``` Is there a way someone can exploit this? ``` function createNewWindow(url, widthIn, heightIn, title) { var strOptions='toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width=' + widthIn + ',height=' + heightIn; var newWin = open( url,title,strOptions ); newWin.focus(); } ```
Given that code, the createNewWindow() script isn't any more vulnerable than the raw javascript.
226,643
<p>If I've created a label in TFS, assigning it to several files, my coworkers cannot change the versions of files (nor add other files) to that label. We get this error:</p> <pre><code>TF14077: The owner of a label cannot be changed. </code></pre> <p>Researching the problem, I found <a href="http://tinyurl.com/6zuw9e" rel="nofollow noreferrer">this article</a>, which states:</p> <blockquote> <p>It is possible that a user could be allowed to manipulate a <strong>shared label</strong> in the development folder but only manipulate labels that they own in a production folder. (emphasis mine)</p> </blockquote> <p>Try as I might, I can't find any reference to "shared labels". So far as I can see, a label must have an owner.</p> <p>FWIW, what I'm trying to do is employ a "floating" label so that developers can indicate that their code is ready to become part of the build by tagging it with a particular label. Then the build process would just need to get everything having that label, and automatically get the most recent stuff that's actually ready to be built, ignoring both past versions as well as newer stuff that's not ready for prime time.</p> <hr> <p><em>Update:</em> I figure if I can't make a truly shared label, I can at least give users the right to edit labels created by their coworkers. This is pretty explicitly supported. Regular <em>Contributor</em> users don't have this right, but according to MSDN (see article <em>Team Foundation Server Permissions</em>, under <em>Source Control Permissions</em>), it can be granted by way of the <em>LabelOther</em> permission:</p> <blockquote> <p>Source control permissions are specific to source code files and folders. You can set these permissions by right-clicking the folder or file in Source Control Explorer, clicking Properties, and on the Security tab, selecting the user or group for which you want to change permissions, and then editing the permissions listed in Permissions. You can set these permissions by using the tf command-line utility for source control.</p> </blockquote> <p>...</p> <blockquote> <p>Administer labels | tf: <strong>LabelOther</strong> | Users who have this permission can edit or delete labels created by another user.</p> </blockquote> <p>So I've assigned that right to the Domain group that contains all the developers, as suggested above. I can verify that it's set using the <strong>tf permission</strong> command:</p> <pre><code>tf permission /group:"CORP\Web Team" </code></pre> <p>and the result is as expected (I also assigned Label, just for fun)</p> <pre><code>=============================================================================== Server item: $/Test1/TeamBuildTypes (Inherit: Yes) Identity: CORP\Web Team Allow: Deny: Allow (Inherited): Label, LabelOther Deny (Inherited): </code></pre> <p>Yet my test user still is not being allowed to edit a label I created.</p>
[ { "answer_id": 226666, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 1, "selected": false, "text": "<p>Would shelve sets be a better solution for what you are doing? IIRC there is a fairly rich API for working with shelve sets such as committing them as part of a build (or other) process.</p>\n\n<p>I found labels in TFS to be very limited when I used it.</p>\n" }, { "answer_id": 3095311, "author": "Chris Wuestefeld", "author_id": 10082, "author_profile": "https://Stackoverflow.com/users/10082", "pm_score": 1, "selected": true, "text": "<p>I never was able to make this work with labels. Instead, we devised a whole different process using branching, which I now strongly recommend to anyone reading this. </p>\n\n<p>We set up a branching scheme so that there's a general development branch; from that, each developer has his/her own branch with which they can do what they want, and there's a Production branch. </p>\n\n<ul>\n<li>Developers do their \"dirty\" work in their private branch without fear of accidentally releasing stuff, or even interfering with their coworkers. </li>\n<li>When they've got something ready to integrate they merge the changes into the development branch. We do continuous builds there, and test the results.</li>\n<li>When an integrated build is fully tested and ready for deployment, the changes are merged to the Production branch. This is built and deployed.</li>\n</ul>\n\n<p>I had said I wanted </p>\n\n<blockquote>\n <p>what I'm trying to do is employ a\n \"floating\" label so that developers\n can indicate that their code is ready\n to become part of the build by tagging\n it with a particular label.</p>\n</blockquote>\n\n<p>The scheme that I outlined above fully achieves this, and more.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10082/" ]
If I've created a label in TFS, assigning it to several files, my coworkers cannot change the versions of files (nor add other files) to that label. We get this error: ``` TF14077: The owner of a label cannot be changed. ``` Researching the problem, I found [this article](http://tinyurl.com/6zuw9e), which states: > > It is possible that a user could be > allowed to manipulate a **shared label** > in the development folder but only > manipulate labels that they own in a > production folder. > (emphasis mine) > > > Try as I might, I can't find any reference to "shared labels". So far as I can see, a label must have an owner. FWIW, what I'm trying to do is employ a "floating" label so that developers can indicate that their code is ready to become part of the build by tagging it with a particular label. Then the build process would just need to get everything having that label, and automatically get the most recent stuff that's actually ready to be built, ignoring both past versions as well as newer stuff that's not ready for prime time. --- *Update:* I figure if I can't make a truly shared label, I can at least give users the right to edit labels created by their coworkers. This is pretty explicitly supported. Regular *Contributor* users don't have this right, but according to MSDN (see article *Team Foundation Server Permissions*, under *Source Control Permissions*), it can be granted by way of the *LabelOther* permission: > > Source control permissions are > specific to source code files and > folders. You can set these permissions > by right-clicking the folder or file > in Source Control Explorer, clicking > Properties, and on the Security tab, > selecting the user or group for which > you want to change permissions, and > then editing the permissions listed in > Permissions. You can set these > permissions by using the tf > command-line utility for source > control. > > > ... > > Administer labels | tf: **LabelOther** | Users who have this permission can edit or delete labels created by another user. > > > So I've assigned that right to the Domain group that contains all the developers, as suggested above. I can verify that it's set using the **tf permission** command: ``` tf permission /group:"CORP\Web Team" ``` and the result is as expected (I also assigned Label, just for fun) ``` =============================================================================== Server item: $/Test1/TeamBuildTypes (Inherit: Yes) Identity: CORP\Web Team Allow: Deny: Allow (Inherited): Label, LabelOther Deny (Inherited): ``` Yet my test user still is not being allowed to edit a label I created.
I never was able to make this work with labels. Instead, we devised a whole different process using branching, which I now strongly recommend to anyone reading this. We set up a branching scheme so that there's a general development branch; from that, each developer has his/her own branch with which they can do what they want, and there's a Production branch. * Developers do their "dirty" work in their private branch without fear of accidentally releasing stuff, or even interfering with their coworkers. * When they've got something ready to integrate they merge the changes into the development branch. We do continuous builds there, and test the results. * When an integrated build is fully tested and ready for deployment, the changes are merged to the Production branch. This is built and deployed. I had said I wanted > > what I'm trying to do is employ a > "floating" label so that developers > can indicate that their code is ready > to become part of the build by tagging > it with a particular label. > > > The scheme that I outlined above fully achieves this, and more.
226,663
<p>I want to use jQuery to parse RSS feeds. Can this be done with the base jQuery library out of the box or will I need to use a plugin?</p>
[ { "answer_id": 226679, "author": "Nathan Strutz", "author_id": 5918, "author_profile": "https://Stackoverflow.com/users/5918", "pm_score": 8, "selected": false, "text": "<p><a href=\"https://github.com/jfhovinne/jFeed\" rel=\"noreferrer\">Use jFeed</a> - a jQuery RSS/Atom plugin. According to the docs, it's as simple as:</p>\n\n<pre><code>jQuery.getFeed({\n url: 'rss.xml',\n success: function(feed) {\n alert(feed.title);\n }\n});\n</code></pre>\n" }, { "answer_id": 226744, "author": "yogman", "author_id": 24349, "author_profile": "https://Stackoverflow.com/users/24349", "pm_score": 3, "selected": false, "text": "<p>Use Google AJAX Feed API unless your RSS data is private. It's fast, of course.</p>\n\n<p><a href=\"https://developers.google.com/feed/\" rel=\"nofollow noreferrer\">https://developers.google.com/feed/</a></p>\n" }, { "answer_id": 226814, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://plugins.jquery.com/project/jFeed\" rel=\"noreferrer\">Using JFeed</a></p>\n\n<pre><code>function getFeed(sender, uri) {\n jQuery.getFeed({\n url: 'proxy.php?url=' + uri,\n success: function(feed) {\n jQuery(sender).append('&lt;h2&gt;'\n + '&lt;a href=\"'\n + feed.link\n + '\"&gt;'\n + feed.title\n + '&lt;/a&gt;'\n + '&lt;/h2&gt;');\n\n var html = '';\n\n for(var i = 0; i &lt; feed.items.length &amp;&amp; i &lt; 5; i++) {\n\n var item = feed.items[i];\n\n html += '&lt;h3&gt;'\n + '&lt;a href=\"'\n + item.link\n + '\"&gt;'\n + item.title\n + '&lt;/a&gt;'\n + '&lt;/h3&gt;';\n\n html += '&lt;div class=\"updated\"&gt;'\n + item.updated\n + '&lt;/div&gt;';\n\n html += '&lt;div&gt;'\n + item.description\n + '&lt;/div&gt;';\n }\n\n jQuery(sender).append(html);\n } \n });\n}\n\n&lt;div id=\"getanewbrowser\"&gt;\n &lt;script type=\"text/javascript\"&gt;\n getFeed($(\"#getanewbrowser\"), 'http://feeds.feedburner.com/getanewbrowser')\n &lt;/script&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 2345012, "author": "kabuski", "author_id": 282392, "author_profile": "https://Stackoverflow.com/users/282392", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;script type=\"text/javascript\" src=\"./js/jquery/jquery.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"./js/jFeed/build/dist/jquery.jfeed.pack.js\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n function loadFeed(){\n $.getFeed({\n url: 'url=http://sports.espn.go.com/espn/rss/news/',\n success: function(feed) {\n\n //Title\n $('#result').append('&lt;h2&gt;&lt;a href=\"' + feed.link + '\"&gt;' + feed.title + '&lt;/a&gt;' + '&lt;/h2&gt;');\n\n //Unordered List\n var html = '&lt;ul&gt;';\n\n $(feed.items).each(function(){\n var $item = $(this);\n\n //trace( $item.attr(\"link\") );\n html += '&lt;li&gt;' +\n '&lt;h3&gt;&lt;a href =\"' + $item.attr(\"link\") + '\" target=\"_new\"&gt;' +\n $item.attr(\"title\") + '&lt;/a&gt;&lt;/h3&gt; ' +\n '&lt;p&gt;' + $item.attr(\"description\") + '&lt;/p&gt;' +\n // '&lt;p&gt;' + $item.attr(\"c:date\") + '&lt;/p&gt;' +\n '&lt;/li&gt;';\n });\n\n html += '&lt;/ul&gt;';\n\n $('#result').append(html);\n }\n });\n }\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 2627568, "author": "saturngod", "author_id": 215939, "author_profile": "https://Stackoverflow.com/users/215939", "pm_score": 2, "selected": false, "text": "<p>I'm using jquery with yql for feed. You can retrieve twitter,rss,buzz with yql. I read from <a href=\"http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/\" rel=\"nofollow noreferrer\">http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/</a> . It's very useful for me.</p>\n" }, { "answer_id": 3012293, "author": "Alderete", "author_id": 11062, "author_profile": "https://Stackoverflow.com/users/11062", "pm_score": 2, "selected": false, "text": "<p>jFeed is somewhat obsolete, working only with older versions of jQuery. It has been two years since it was updated.</p>\n\n<p>zRSSFeed is perhaps a little less flexible, but it is easy to use, and it works with the current version of jQuery (currently 1.4). <a href=\"http://www.zazar.net/developers/zrssfeed/\" rel=\"nofollow noreferrer\">http://www.zazar.net/developers/zrssfeed/</a></p>\n\n<p>Here's a quick example from the zRSSFeed docs:</p>\n\n<pre><code>&lt;div id=\"test\"&gt;&lt;div&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n$(document).ready(function () {\n $('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {\n limit: 5\n });\n});\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 3029971, "author": "Mark Steggles", "author_id": 365380, "author_profile": "https://Stackoverflow.com/users/365380", "pm_score": 4, "selected": false, "text": "<p>jFeed doesn't work in IE.</p>\n\n<p>Use <a href=\"http://www.zazar.net/developers/zrssfeed/\" rel=\"nofollow noreferrer\">zRSSFeed</a>. Had it working in 5 minutes</p>\n" }, { "answer_id": 6271906, "author": "Andrew Childs", "author_id": 440094, "author_profile": "https://Stackoverflow.com/users/440094", "pm_score": 9, "selected": true, "text": "<p><strong>WARNING</strong></p>\n\n<blockquote>\n <p><a href=\"https://developers.google.com/feed/\" rel=\"nofollow noreferrer\">The Google Feed API</a> is officially <strong>deprecated</strong> and <strong>doesn't work anymore</strong>!</p>\n</blockquote>\n\n<hr>\n\n<p>No need for a whole plugin. This will return your RSS as a JSON object to a callback function:</p>\n\n<pre><code>function parseRSS(url, callback) {\n $.ajax({\n url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(url),\n dataType: 'json',\n success: function(data) {\n callback(data.responseData.feed);\n }\n });\n}\n</code></pre>\n" }, { "answer_id": 7067582, "author": "David Hammond", "author_id": 331541, "author_profile": "https://Stackoverflow.com/users/331541", "pm_score": 7, "selected": false, "text": "<p>For those of us coming to the discussion late, starting with 1.5 jQuery has built-in xml parsing capabilities, which makes it pretty easy to do this without plugins or 3rd party services. It has a parseXml function, and will also auto-parse xml when using the $.get function. E.g.:</p>\n\n<pre><code>$.get(rssurl, function(data) {\n var $xml = $(data);\n $xml.find(\"item\").each(function() {\n var $this = $(this),\n item = {\n title: $this.find(\"title\").text(),\n link: $this.find(\"link\").text(),\n description: $this.find(\"description\").text(),\n pubDate: $this.find(\"pubDate\").text(),\n author: $this.find(\"author\").text()\n }\n //Do something with item here...\n });\n});\n</code></pre>\n" }, { "answer_id": 7407723, "author": "Dylan Valade", "author_id": 638452, "author_profile": "https://Stackoverflow.com/users/638452", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/6271906/30433\">I agree with @Andrew</a>, using Google is a solid, reusable way to do it with the huge benefit that you get JSON back instead of XML. An added advantage of using Google as a proxy is that services that might block your direct access to their data are unlikely to stop Google. Here is an example using ski report and conditions data. This has all of the common real world applications: 1) Third party RSS/XML 2) JSONP 3) Cleaning strings and string to array when you can't get the data exactly the way you want it 4) on load add elements to the DOM. Hope this helps some people!</p>\n\n<pre><code>&lt;!-- Load RSS Through Google as JSON using jQuery --&gt;\n&lt;script type=\"text/javascript\"&gt;\n\n function displaySkiReport (feedResponse) {\n\n // Get ski report content strings\n var itemString = feedResponse.entries[0].content;\n var publishedDate = feedResponse.entries[0].publishedDate;\n\n // Clean up strings manually as needed\n itemString = itemString.replace(\"Primary: N/A\", \"Early Season Conditions\"); \n publishedDate = publishedDate.substring(0,17);\n\n // Parse ski report data from string\n var itemsArray = itemString.split(\"/\");\n\n\n //Build Unordered List\n var html = '&lt;h2&gt;' + feedResponse.entries[0].title + '&lt;/h2&gt;';\n html += '&lt;ul&gt;';\n\n html += '&lt;li&gt;Skiing Status: ' + itemsArray[0] + '&lt;/li&gt;';\n // Last 48 Hours\n html += '&lt;li&gt;' + itemsArray[1] + '&lt;/li&gt;';\n // Snow condition\n html += '&lt;li&gt;' + itemsArray[2] + '&lt;/li&gt;';\n // Base depth\n html += '&lt;li&gt;' + itemsArray[3] + '&lt;/li&gt;';\n\n html += '&lt;li&gt;Ski Report Date: ' + publishedDate + '&lt;/li&gt;';\n\n html += '&lt;/ul&gt;';\n\n $('body').append(html); \n\n }\n\n\n function parseRSS(url, callback) {\n $.ajax({\n url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(url),\n dataType: 'json',\n success: function(data) {\n callback(data.responseData.feed);\n }\n });\n }\n\n $(document).ready(function() { \n\n // Ski report\n parseRSS(\"http://www.onthesnow.com/michigan/boyne-highlands/snow.rss\", displaySkiReport);\n\n });\n\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 7493653, "author": "Guruprasad Balaji", "author_id": 569307, "author_profile": "https://Stackoverflow.com/users/569307", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.zazar.net/developers/jquery/zrssfeed/\" rel=\"nofollow\">zRSSfeed</a> is built on <em>jQuery</em> and the simple theme is awesome.<br>\nGive it a try.</p>\n" }, { "answer_id": 7902369, "author": "sdepold", "author_id": 568203, "author_profile": "https://Stackoverflow.com/users/568203", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p><strong>Update (Oct 15, 2019)</strong></p>\n</blockquote>\n\n<p>I extracted the core logic from jquery-rss to a new library called <a href=\"https://github.com/sdepold/vanilla-rss\" rel=\"nofollow noreferrer\">Vanilla RSS</a> which is using the fetch API and can work without any additional dependencies:</p>\n\n<pre><code>const RSS = require('vanilla-rss');\nconst rss = new RSS(\n document.querySelector(\"#your-div\"),\n \"http://www.recruiter.com/feed/career.xml\",\n { \n // options go here\n }\n);\nrss.render().then(() =&gt; {\n console.log('Everything is loaded and rendered');\n});\n\n</code></pre>\n\n<blockquote>\n <p>Original</p>\n</blockquote>\n\n<p>post:</p>\n\n<p>You can also use <a href=\"https://github.com/sdepold/jquery-rss\" rel=\"nofollow noreferrer\">jquery-rss</a>, which comes with nice templating and is super easy to use:</p>\n\n<pre><code>$(\"#your-div\").rss(\"http://www.recruiter.com/feed/career.xml\", {\n limit: 3,\n layoutTemplate: '&lt;ul class=\"inline\"&gt;{entries}&lt;/ul&gt;',\n entryTemplate: '&lt;li&gt;&lt;a href=\"{url}\"&gt;[{author}@{date}] {title}&lt;/a&gt;&lt;br/&gt;{shortBodyPlain}&lt;/li&gt;'\n})\n</code></pre>\n\n<p>yields (as of Sept 18, 2013):</p>\n\n<pre><code>&lt;div id=\"your-div\"&gt;\n &lt;ul class=\"inline\"&gt;\n &lt;entries&gt;&lt;/entries&gt;\n &lt;/ul&gt;\n &lt;ul class=\"inline\"&gt;\n &lt;li&gt;&lt;a href=\"http://www.recruiter.com/i/when-to-go-over-a-recruiter%e2%80%99s-head/\"&gt;[@Tue, 10 Sep 2013 22:23:51 -0700] When to Go Over a Recruiter's Head&lt;/a&gt;&lt;br&gt;Job seekers tend to have a certain \"fear\" of recruiters and hiring managers, and I mean fear in the reverence and respect ...&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"http://www.recruiter.com/i/the-perfect-job/\"&gt;[@Tue, 10 Sep 2013 14:52:40 -0700] The Perfect Job&lt;/a&gt;&lt;br&gt;Having long ago dealt with the \"perfect resume\" namely God's, in a previous article of mine, it makes sense to consider the ...&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"http://www.recruiter.com/i/unemployment-benefits-applications-remain-near-5-year-low-decline-again/\"&gt;[@Mon, 09 Sep 2013 12:49:17 -0700] Unemployment Benefits Applications Remain Near 5-Year Low, Decline Again&lt;/a&gt;&lt;br&gt;As reported by the U.S. Department of Labor, the number of workers seeking unemployment benefits continued to sit near ...&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>See <a href=\"http://jsfiddle.net/sdepold/ozq2dn9e/1/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/sdepold/ozq2dn9e/1/</a> for a working example.</p>\n" }, { "answer_id": 9328162, "author": "John Magnolia", "author_id": 560287, "author_profile": "https://Stackoverflow.com/users/560287", "pm_score": 3, "selected": false, "text": "<pre><code>(function(url, callback) {\n jQuery.ajax({\n url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(url),\n dataType: 'json',\n success: function(data) {\n callback(data.responseData.feed);\n }\n });\n})('http://news.hitb.org/rss.xml', function(feed){ // Change to desired URL\n var entries = feed.entries, feedList = '';\n for (var i = 0; i &lt; entries.length; i++) {\n feedList +='&lt;li&gt;&lt;a href=\"' + entries[i].link + '\"&gt;' + entries[i].title + '&lt;/a&gt;&lt;/li&gt;';\n }\n jQuery('.feed &gt; ul').append(feedList);\n});\n\n\n&lt;div class=\"feed\"&gt;\n &lt;h4&gt;Hacker News&lt;/h4&gt;\n &lt;ul&gt;&lt;/ul&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 10545095, "author": "Rimian", "author_id": 63810, "author_profile": "https://Stackoverflow.com/users/63810", "pm_score": -1, "selected": false, "text": "<p>jFeed is easy and has an <a href=\"https://github.com/jfhovinne/jFeed/blob/master/example.html\" rel=\"nofollow\">example</a> for you to test. But if you're parsing a feed from another server, you'll need to allow <a href=\"http://en.wikipedia.org/wiki/Cross-origin_resource_sharing\" rel=\"nofollow\">Cross Origin Resource Sharing</a> (CORS) on the feed's server. You'll also need to <a href=\"http://caniuse.com/cors\" rel=\"nofollow\">check browser support</a>. </p>\n\n<p>I uploaded <a href=\"https://raw.github.com/jfhovinne/jFeed/master/example.html\" rel=\"nofollow\">the sample</a> but still did not get support from IE in any version when I changed the url in the example to something like example.com/feed.rss via the http protocol. CORS should be supported for IE 8 and above but the jFeed example did not render the feed.</p>\n\n<p>Your best bet is to use Google's API:<br>\n<a href=\"https://developers.google.com/feed/v1/devguide\" rel=\"nofollow\">https://developers.google.com/feed/v1/devguide</a></p>\n\n<p>See:<br>\n<a href=\"https://github.com/jfhovinne/jFeed\" rel=\"nofollow\">https://github.com/jfhovinne/jFeed</a><br>\n<a href=\"http://en.wikipedia.org/wiki/Cross-origin_resource_sharing\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Cross-origin_resource_sharing</a><br>\n<a href=\"http://en.wikipedia.org/wiki/Same_origin_policy\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Same_origin_policy</a><br>\n<a href=\"http://caniuse.com/cors\" rel=\"nofollow\">http://caniuse.com/cors</a></p>\n" }, { "answer_id": 11463376, "author": "camagu", "author_id": 1517983, "author_profile": "https://Stackoverflow.com/users/1517983", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://github.com/camagu/jquery-feeds\" rel=\"nofollow\">jQuery Feeds</a> is a nice option, it has a built-in templating system and uses the Google Feed API, so it has cross-domain support.</p>\n" }, { "answer_id": 12788982, "author": "Daniel Magnusson", "author_id": 63678, "author_profile": "https://Stackoverflow.com/users/63678", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"https://developers.google.com/feed/v1/jsondevguide\" rel=\"nofollow\">google ajax api</a>, cached by google and any output format you want.</p>\n\n<p>Code sample;\n<a href=\"http://code.google.com/apis/ajax/playground/#load_feed\" rel=\"nofollow\">http://code.google.com/apis/ajax/playground/#load_feed</a></p>\n\n<pre><code>&lt;script src=\"http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0\" type=\"text/javascript\"&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\"&gt;\n/*\n* How to load a feed via the Feeds API.\n*/\n\ngoogle.load(\"feeds\", \"1\");\n\n// Our callback function, for when a feed is loaded.\nfunction feedLoaded(result) {\n if (!result.error) {\n // Grab the container we will put the results into\n var container = document.getElementById(\"content\");\n container.innerHTML = '';\n\n // Loop through the feeds, putting the titles onto the page.\n // Check out the result object for a list of properties returned in each entry.\n // http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON\n for (var i = 0; i &lt; result.feed.entries.length; i++) {\n var entry = result.feed.entries[i];\n var div = document.createElement(\"div\");\n div.appendChild(document.createTextNode(entry.title));\n container.appendChild(div);\n }\n }\n}\n\nfunction OnLoad() {\n // Create a feed instance that will grab Digg's feed.\n var feed = new google.feeds.Feed(\"http://www.digg.com/rss/index.xml\");\n\n // Calling load sends the request off. It requires a callback function.\n feed.load(feedLoaded);\n}\n\ngoogle.setOnLoadCallback(OnLoad);\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 13771909, "author": "SpYk3HH", "author_id": 900807, "author_profile": "https://Stackoverflow.com/users/900807", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p><strong><em>UPDATE</em></strong> [<em>4/25/2016</em>] Now better written and fully supported version with more options and abilities hosted at <a href=\"https://github.com/JDMcKinstry/jQRSS\" rel=\"nofollow noreferrer\"><strong>GitHub.jQRSS</strong></a></p>\n</blockquote>\n\n<p>I saw the <a href=\"https://stackoverflow.com/questions/226663/parse-rss-with-jquery#answer-226679\"><em>Selected</em> Answer</a> by <a href=\"https://stackoverflow.com/users/5918/nathan-strutz\">Nathan Strutz</a>, however, the jQuery Plugin page link is still down and the home page for that site did not seem to load. I tried a few other solutions and found most of them to be, not only out-dated, but <strong>EASY</strong>! Thus I threw my hat out there and made my own plugin, and with the dead links here, this seems like a great place to submit an answer. If you're looking for this answer in 2012 (soon to b 2013) you may notice the frustration of dead links and old advice here as I did. Below is a link to my <em>modern</em> plugin example as well as the code to the plugin! Simply copy the code into a JS file &amp; link it in your header like any other plugin. Use is EXTREMELY EZ!</p>\n\n<p><a href=\"http://jsfiddle.net/SpYk3/Pp44S/\" rel=\"nofollow noreferrer\"><h1>jsFiddle</h1></a></p>\n\n<blockquote>\n <p><strong>Plugin Code</strong><br/><sub>2/9/2015 - made long overdue update to check for <code>console</code> before sending commands to it! Should help with older IE issues.</sub></p>\n</blockquote>\n\n<pre><code>(function($) {\n if (!$.jQRSS) { \n $.extend({ \n jQRSS: function(rss, options, func) {\n if (arguments.length &lt;= 0) return false;\n\n var str, obj, fun;\n for (i=0;i&lt;arguments.length;i++) {\n switch(typeof arguments[i]) {\n case \"string\":\n str = arguments[i];\n break;\n case \"object\":\n obj = arguments[i];\n break;\n case \"function\":\n fun = arguments[i];\n break;\n }\n }\n\n if (str == null || str == \"\") {\n if (!obj['rss']) return false;\n if (obj.rss == null || obj.rss == \"\") return false;\n }\n\n var o = $.extend(true, {}, $.jQRSS.defaults);\n\n if (typeof obj == \"object\") {\n if ($.jQRSS.methods.getObjLength(obj) &gt; 0) {\n o = $.extend(true, o, obj);\n }\n }\n\n if (str != \"\" &amp;&amp; !o.rss) o.rss = str;\n o.rss = escape(o.rss);\n\n var gURL = $.jQRSS.props.gURL \n + $.jQRSS.props.type \n + \"?v=\" + $.jQRSS.props.ver\n + \"&amp;q=\" + o.rss\n + \"&amp;callback=\" + $.jQRSS.props.callback;\n\n var ajaxData = {\n num: o.count,\n output: o.output,\n };\n\n if (o.historical) ajaxData.scoring = $.jQRSS.props.scoring;\n if (o.userip != null) ajaxData.scoring = o.userip;\n\n $.ajax({\n url: gURL,\n beforeSend: function (jqXHR, settings) { if (window['console']) { console.log(new Array(30).join('-'), \"REQUESTING RSS XML\", new Array(30).join('-')); console.log({ ajaxData: ajaxData, ajaxRequest: settings.url, jqXHR: jqXHR, settings: settings, options: o }); console.log(new Array(80).join('-')); } },\n dataType: o.output != \"xml\" ? \"json\" : \"xml\",\n data: ajaxData,\n type: \"GET\",\n xhrFields: { withCredentials: true },\n error: function (jqXHR, textStatus, errorThrown) { return new Array(\"ERROR\", { jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown } ); },\n success: function (data, textStatus, jqXHR) { \n var f = data['responseData'] ? data.responseData['feed'] ? data.responseData.feed : null : null,\n e = data['responseData'] ? data.responseData['feed'] ? data.responseData.feed['entries'] ? data.responseData.feed.entries : null : null : null\n if (window['console']) {\n console.log(new Array(30).join('-'), \"SUCCESS\", new Array(30).join('-'));\n console.log({ data: data, textStatus: textStatus, jqXHR: jqXHR, feed: f, entries: e });\n console.log(new Array(70).join('-'));\n }\n\n if (fun) {\n return fun.call(this, data['responseData'] ? data.responseData['feed'] ? data.responseData.feed : data.responseData : null);\n }\n else {\n return { data: data, textStatus: textStatus, jqXHR: jqXHR, feed: f, entries: e };\n }\n }\n });\n }\n });\n $.jQRSS.props = {\n callback: \"?\",\n gURL: \"http://ajax.googleapis.com/ajax/services/feed/\",\n scoring: \"h\",\n type: \"load\",\n ver: \"1.0\"\n };\n $.jQRSS.methods = {\n getObjLength: function(obj) {\n if (typeof obj != \"object\") return -1;\n var objLength = 0;\n $.each(obj, function(k, v) { objLength++; })\n return objLength;\n }\n };\n $.jQRSS.defaults = {\n count: \"10\", // max 100, -1 defaults 100\n historical: false,\n output: \"json\", // json, json_xml, xml\n rss: null, // url OR search term like \"Official Google Blog\"\n userip: null\n };\n }\n})(jQuery);\n</code></pre>\n\n<blockquote>\n <p><strong>USE</strong></p>\n</blockquote>\n\n<pre><code>// Param ORDER does not matter, however, you must have a link and a callback function\n// link can be passed as \"rss\" in options\n// $.jQRSS(linkORsearchString, callbackFunction, { options })\n\n$.jQRSS('someUrl.xml', function(feed) { /* do work */ })\n\n$.jQRSS(function(feed) { /* do work */ }, 'someUrl.xml', { count: 20 })\n\n$.jQRSS('someUrl.xml', function(feed) { /* do work */ }, { count: 20 })\n\n$.jQRSS({ count: 20, rss: 'someLink.xml' }, function(feed) { /* do work */ })\n</code></pre>\n\n<p><strike> $.jQRSS('Search Words Here instead of a Link', function(feed) { /* do work */ })\n</strike> // TODO: Needs fixing</p>\n\n<blockquote>\n <p><strong>Options</strong></p>\n</blockquote>\n\n<pre><code>{\n count: // default is 10; max is 100. Setting to -1 defaults to 100\n historical: // default is false; a value of true instructs the system to return any additional historical entries that it might have in its cache. \n output: // default is \"json\"; \"json_xml\" retuns json object with xmlString / \"xml\" returns the XML as String\n rss: // simply an alternate place to put news feed link or search terms\n userip: // as this uses Google API, I'll simply insert there comment on this:\n /* Reference: https://developers.google.com/feed/v1/jsondevguide\n This argument supplies the IP address of the end-user on \n whose behalf the request is being made. Google is less \n likely to mistake requests for abuse when they include \n userip. In choosing to utilize this parameter, please be \n sure that you're in compliance with any local laws, \n including any laws relating to disclosure of personal \n information being sent.\n */\n}\n</code></pre>\n" }, { "answer_id": 18003983, "author": "Jeromy French", "author_id": 1430996, "author_profile": "https://Stackoverflow.com/users/1430996", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://github.com/sdepold/jquery-rss\" rel=\"nofollow\">The jQuery-rss project</a> is pretty lightweight and doesn't impose any particular styling.</p>\n\n<p>The syntax can be as simple as </p>\n\n<pre><code>$(\"#rss-feeds\").rss(\"http://www.recruiter.com/feed/career.xml\")\n</code></pre>\n\n<p>See a <a href=\"http://jsfiddle.net/jhfrench/AFHfn/\" rel=\"nofollow\">working example at http://jsfiddle.net/jhfrench/AFHfn/</a></p>\n" }, { "answer_id": 21318510, "author": "Julien Genestoux", "author_id": 73987, "author_profile": "https://Stackoverflow.com/users/73987", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://superfeedr.com\" rel=\"nofollow\">Superfeedr</a> has a <a href=\"http://plugins.jquery.com/superfeedr/\" rel=\"nofollow\">jquery plugin</a> which does that very well.\nYou won't have any Cross Origin Policy issue and the updates are propagated in realtime.</p>\n" }, { "answer_id": 34233982, "author": "jQP", "author_id": 4149457, "author_profile": "https://Stackoverflow.com/users/4149457", "pm_score": 2, "selected": false, "text": "<p>I advice you to use <a href=\"http://jquery-plugins.net/FeedEk/FeedEk.html\" rel=\"nofollow\">FeedEk</a>. After Google Feed API is officially deprecated most of plugins doesn't work. But FeedEk is still working. It's very easy to use and has many options to customize.</p>\n\n<pre><code>$('#divRss').FeedEk({\n FeedUrl:'http://jquery-plugins.net/rss'\n});\n</code></pre>\n\n<p>With options</p>\n\n<pre><code>$('#divRss').FeedEk({\n FeedUrl:'http://jquery-plugins.net/rss',\n MaxCount : 5,\n ShowDesc : true,\n ShowPubDate:true,\n DescCharacterLimit:100,\n TitleLinkTarget:'_blank',\n DateFormat: 'MM/DD/YYYY',\n DateFormatLang:'en'\n});\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12442/" ]
I want to use jQuery to parse RSS feeds. Can this be done with the base jQuery library out of the box or will I need to use a plugin?
**WARNING** > > [The Google Feed API](https://developers.google.com/feed/) is officially **deprecated** and **doesn't work anymore**! > > > --- No need for a whole plugin. This will return your RSS as a JSON object to a callback function: ``` function parseRSS(url, callback) { $.ajax({ url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url), dataType: 'json', success: function(data) { callback(data.responseData.feed); } }); } ```
226,664
<p>I have a web service in C# and would like to have a nested inner class, that abstracts away the session collection, something like this: </p> <pre> <code> public class Service : System.Web.Services.WebService { [WebMethod] public string Foo(string ticket) { SessionPool.getSession(ticket); } private class SessionPool { public static Session getSession(string ticket) { // this is what i want to do, but I can't access Context return (Session)Context.Session[ticket]; } } } </code> </pre> <p>Is it possible to access the HTTP context of the WebService class via a nested class? If not, is there way I can store the reference to it?</p>
[ { "answer_id": 226670, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 0, "selected": false, "text": "<pre><code>System.Web.HttpContext.Current\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 226687, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Nested classes in C# aren't like (non-static) inner classes in Java. There is no implicit reference to an instance of the containing class - so you can't use any instance members of the containing class without an explicit reference.</p>\n\n<p>However, you do have access to all private members of the containing class - with a suitable reference for instance members.</p>\n" }, { "answer_id": 226697, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "<p>I can think of a couple things.</p>\n\n<p>First, you might try using getContext() instead of just accessing Context. If that works, you're done.</p>\n\n<p>If not, you could pass the Service in as an initializer to your SessionPool. Add a WebService handle to SessionPool that you initialize via a call to setService() before calling getSession() from Foo().</p>\n\n<p>Although, at that point, why not just pass in the Context as an argument to getSession()?</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have a web service in C# and would like to have a nested inner class, that abstracts away the session collection, something like this: ``` public class Service : System.Web.Services.WebService { [WebMethod] public string Foo(string ticket) { SessionPool.getSession(ticket); } private class SessionPool { public static Session getSession(string ticket) { // this is what i want to do, but I can't access Context return (Session)Context.Session[ticket]; } } } ``` Is it possible to access the HTTP context of the WebService class via a nested class? If not, is there way I can store the reference to it?
Nested classes in C# aren't like (non-static) inner classes in Java. There is no implicit reference to an instance of the containing class - so you can't use any instance members of the containing class without an explicit reference. However, you do have access to all private members of the containing class - with a suitable reference for instance members.
226,683
<p>I've got a ant <code>build.xml</code> that uses the <code>&lt;copy&gt;</code> task to copy a variety of xml files. It uses filtering to merge in properties from a <code>build.properties</code> file. Each environment (dev, stage, prod) has a different <code>build.properties</code> that stores configuration for that environment.</p> <p>Sometimes we add new properties to the Spring XML or other config files that requires updating the <code>build.properties</code> file.</p> <p>I want ant to fail fast if there are properties missing from <code>build.properties</code>. That is, if any raw <code>@...@</code> tokens make it into the generated files, I want the build to die so that the user knows they need to add one or more properties to their local build.properties.</p> <p>Is this possible with the built in tasks? I couldn't find anything in the docs. I'm about to write a custom ant task, but maybe I can spare myself the effort.</p> <p>Thanks</p>
[ { "answer_id": 226731, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<p>I was going to suggest that you attempt to use <code>&lt;property file=\"${filter.file}\" prefix=\"filter\"&gt;</code> to actually load the properties into Ant, and then <code>fail</code> if any of them are not set, but I think I was interpreting your problem wrong (that you wanted to fail if a specified property was not set in the properties file).</p>\n\n<p>I think your best bet might be to use <code>&lt;exec&gt;</code> to (depending on your dev platform) do a grep for the \"@\" character, and then set a property to the number of occurences found. Not sure of exact syntax but...</p>\n\n<pre><code>&lt;exec command=\"grep \\\"@\\\" ${build.dir} | wc -l\" outputproperty=\"token.count\"/&gt;\n&lt;condition property=\"token.found\"&gt;\n &lt;not&gt;\n &lt;equals arg1=\"${token.count}\" arg2=\"0\"/&gt;\n &lt;/not&gt;\n&lt;/condition&gt;\n&lt;fail if=\"token.found\" message=\"Found token @ in files\"/&gt;\n</code></pre>\n" }, { "answer_id": 291371, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>if exec command is deprecated in your version of ant you can use redirectors, something like:</p>\n\n<pre><code>&lt;exec executable=\"grep\"&gt;\n &lt;arg line=\"@ ${build.dir}\"/&gt;\n &lt;redirector outputproperty=\"grep.out\"/&gt;\n&lt;/exec&gt;\n&lt;exec executable=\"wc\" inputstring=\"${grep.out}\"&gt;\n &lt;arg line=\"-l\"/&gt;\n &lt;redirector outputproperty=\"token.found\"/&gt;\n&lt;/exec&gt;\n</code></pre>\n\n<p>to create the token.found property</p>\n\n<pre><code>&lt;condition property=\"token.found\"&gt;\n &lt;not&gt;\n &lt;equals arg1=\"${token.count}\" arg2=\"0\"/&gt;\n &lt;/not&gt;\n&lt;/condition&gt;\n&lt;fail if=\"token.found\" message=\"Found token @ in files\"/&gt;\n</code></pre>\n\n<p>for the conditonal</p>\n" }, { "answer_id": 291515, "author": "Jason Day", "author_id": 737, "author_profile": "https://Stackoverflow.com/users/737", "pm_score": 5, "selected": true, "text": "<p>You can do it in ant 1.7, using a combination of the <code>LoadFile</code> task and the <code>match</code> condition.</p>\n\n<pre><code>&lt;loadfile property=\"all-build-properties\" srcFile=\"build.properties\"/&gt;\n&lt;condition property=\"missing-properties\"&gt;\n &lt;matches pattern=\"@[^@]*@\" string=\"${all-build-properties}\"/&gt;\n&lt;/condition&gt;\n&lt;fail message=\"Some properties not set!\" if=\"missing-properties\"/&gt;\n</code></pre>\n" }, { "answer_id": 653844, "author": "dovetalk", "author_id": 78972, "author_profile": "https://Stackoverflow.com/users/78972", "pm_score": 7, "selected": false, "text": "<p>If you are looking for a specific property, you can just use the fail task with the unless attribute, e.g.:</p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;fail unless=&quot;my.property&quot;&gt;Computer says no. You forgot to set 'my.property'!&lt;/fail&gt;\n</code></pre>\n<p>Refer to <a href=\"https://ant.apache.org/manual/Tasks/fail.html\" rel=\"nofollow noreferrer\" title=\"Ant fail documentation\">the documentation for Ant's fail task</a> for more detail.</p>\n" }, { "answer_id": 19533292, "author": "Vadzim", "author_id": 603516, "author_profile": "https://Stackoverflow.com/users/603516", "pm_score": 0, "selected": false, "text": "<p>Since Ant 1.6.2 <code>condition</code> can also be nested inside <code>fail</code>.</p>\n\n<p>The following macro makes it easy to conditionally check multiple properties.</p>\n\n<pre><code>&lt;macrodef name=\"required-property\"&gt;\n &lt;attribute name=\"name\"/&gt;\n &lt;attribute name=\"prop\" default=\"@{name}\"/&gt;\n &lt;attribute name=\"if\" default=\"___\"/&gt;\n &lt;attribute name=\"unless\" default=\"___\"/&gt;\n &lt;sequential&gt;\n &lt;fail message=\"You must set property '@{name}'\"&gt;\n &lt;condition&gt;\n &lt;and&gt;\n &lt;not&gt;&lt;isset property=\"@{prop}\"/&gt;&lt;/not&gt;\n &lt;or&gt;\n &lt;equals arg1=\"@{if}\" arg2=\"___\"/&gt;\n &lt;isset property=\"@{if}\"/&gt;\n &lt;/or&gt;\n &lt;or&gt;\n &lt;equals arg1=\"@{unless}\" arg2=\"___\"/&gt;\n &lt;not&gt;&lt;isset property=\"@{unless}\"/&gt;&lt;/not&gt;\n &lt;/or&gt;\n &lt;/and&gt;\n &lt;/condition&gt;\n &lt;/fail&gt;\n &lt;/sequential&gt;\n&lt;/macrodef&gt;\n\n&lt;target name=\"required-property.test\"&gt;\n &lt;property name=\"prop\" value=\"\"/&gt;\n &lt;property name=\"cond\" value=\"set\"/&gt;\n &lt;required-property name=\"prop\"/&gt;\n &lt;required-property name=\"prop\" if=\"cond\"/&gt;\n &lt;required-property name=\"prop\" unless=\"cond\"/&gt;\n &lt;required-property name=\"prop\" if=\"cond2\"/&gt;\n &lt;required-property name=\"prop\" unless=\"cond2\"/&gt;\n &lt;required-property name=\"prop\" if=\"cond\" unless=\"cond\"/&gt;\n &lt;required-property name=\"prop\" if=\"cond\" unless=\"cond2\"/&gt;\n &lt;required-property name=\"prop\" if=\"cond2\" unless=\"cond\"/&gt;\n &lt;required-property name=\"prop\" if=\"cond2\" unless=\"cond2\"/&gt;\n &lt;required-property name=\"prop2\" unless=\"cond\"/&gt;\n &lt;required-property name=\"prop2\" if=\"cond2\"/&gt;\n &lt;required-property name=\"prop2\" if=\"cond2\" unless=\"cond\"/&gt;\n &lt;required-property name=\"prop2\" if=\"cond\" unless=\"cond\"/&gt;\n &lt;required-property name=\"prop2\" if=\"cond2\" unless=\"cond2\"/&gt;\n &lt;required-property name=\"success\"/&gt;\n&lt;/target&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25198/" ]
I've got a ant `build.xml` that uses the `<copy>` task to copy a variety of xml files. It uses filtering to merge in properties from a `build.properties` file. Each environment (dev, stage, prod) has a different `build.properties` that stores configuration for that environment. Sometimes we add new properties to the Spring XML or other config files that requires updating the `build.properties` file. I want ant to fail fast if there are properties missing from `build.properties`. That is, if any raw `@...@` tokens make it into the generated files, I want the build to die so that the user knows they need to add one or more properties to their local build.properties. Is this possible with the built in tasks? I couldn't find anything in the docs. I'm about to write a custom ant task, but maybe I can spare myself the effort. Thanks
You can do it in ant 1.7, using a combination of the `LoadFile` task and the `match` condition. ``` <loadfile property="all-build-properties" srcFile="build.properties"/> <condition property="missing-properties"> <matches pattern="@[^@]*@" string="${all-build-properties}"/> </condition> <fail message="Some properties not set!" if="missing-properties"/> ```
226,689
<p>I'm writing a GreaseMonkey script where I'm iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The element itself doesn't have an <code>id</code> attribute, and I can't modify the original document to give it one (although I can make DOM changes in my script). I can't store the references in my script because when I need them, the GreaseMonkey script itself will have gone out of scope. Is there some way to get at an "internal" ID that the browser uses, for example? A Firefox-only solution is fine; a cross-browser solution that could be applied in other scenarios would be awesome.</p> <p>Edit:</p> <ul> <li><p><strong>If the GreaseMonkey script is out of scope, how are you referencing the elements later?</strong> They GreaseMonkey script is adding events to DOM objects. I can't store the references in an array or some other similar mechanism because when the event fires, the array will be gone because the GreaseMonkey script will have gone out of scope. So the event needs some way to know about the element reference that the script had when the event was attached. And the element in question is not the one to which it is attached.</p></li> <li><p><strong>Can't you just use a custom property on the element?</strong> Yes, but the problem is on the lookup. I'd have to resort to iterating through all the elements looking for the one that has that custom property set to the desired id. That would work, sure, but in large documents it could be very time consuming. I'm looking for something where the browser can do the lookup grunt work.</p></li> <li><p><strong>Wait, can you or can you not modify the document?</strong> I can't modify the source document, but I can make DOM changes in the script. I'll clarify in the question.</p></li> <li><p><strong>Can you not use closures?</strong> Closuses did turn out to work, although I initially thought they wouldn't. See my later post.</p></li> </ul> <p>It sounds like the answer to the question: "Is there some internal browser ID I could use?" is "No."</p>
[ { "answer_id": 226715, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>In javascript, you could attach a custom ID field to the node</p>\n\n<pre><code>if(node.id) {\n node.myId = node.id;\n} else {\n node.myId = createId();\n}\n\n// store myId\n</code></pre>\n\n<p>It's a bit of hack, but it'll give each and every node an id you can use. Of course, <code>document.getElementById()</code> won't pay attention to it.</p>\n" }, { "answer_id": 226780, "author": "Michael", "author_id": 27966, "author_profile": "https://Stackoverflow.com/users/27966", "pm_score": 2, "selected": false, "text": "<p>You can set the id attribute to a computed value. There is a function in the prototype library that can do this for you.</p>\n\n<p><a href=\"http://www.prototypejs.org/api/element/identify\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/element/identify</a></p>\n\n<p>My favorite javascript library is jQuery. Unfortunately jQuery does not have a function like identify. However, you can still set the id attribute to a value that you generate on your own.</p>\n\n<p><a href=\"http://docs.jquery.com/Attributes/attr#keyfn\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Attributes/attr#keyfn</a></p>\n\n<p>Here is a partial snippet from jQuery docs that sets id for divs based on the position in the page:</p>\n\n<pre><code> $(document).ready(function(){\n\n $(\"div\").attr(\"id\", function (arr) {\n return \"div-id\" + arr;\n });\n });\n</code></pre>\n" }, { "answer_id": 226804, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "<p>If you're not modifying the DOM you can get them all by indexed order:</p>\n\n<p>(<a href=\"http://prototypejs.org\" rel=\"nofollow noreferrer\">Prototype</a> example)</p>\n\n<pre><code>myNodes = document.body.descendants()\nalert(document.body.descendants()[1].innerHTML)\n</code></pre>\n\n<p>You could loop through all of the nodes and give them a unique className that you could later select easily.</p>\n" }, { "answer_id": 226809, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 3, "selected": false, "text": "<p>The answer is no, there isn't an internal id you can access. Opera and IE (maybe Safari?) support <code>.sourceIndex</code> (which changes if DOM does) but Firefox has nothing of this sort. </p>\n\n<p>You can simulate source-index by generating Xpath to a given node or finding the index of the node from <code>document.getElementsByTagName('*')</code> which will always return elements in source order.</p>\n\n<p>All of this requires a completely static file of course. Changes to DOM will break the lookup.</p>\n\n<p>What I don't understand is how you can loose references to nodes but not to (theoretical) internal id's? Either closures and assignments work or they don't. Or am I missing something?</p>\n" }, { "answer_id": 226850, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": false, "text": "<p>A bit confused by the wording of your question - you say that you \"need a string ID that [you] can use to reference that element later, \" but that you \"can't store the references in [your] script because when [you] need them, the GreaseMonkey script itself will have gone out of scope.\"</p>\n\n<p>If the script will have gone out of scope, then how are you referencing them later?!</p>\n\n<p>I am going to ignore the fact that I am confused by what you are getting at and tell you that I write Greasemonkey scripts quite often and <em>can</em> modify the DOM elements I access to give them an ID property. This is code you can use to get a pseudo-unique value for temporary use:</p>\n\n<pre><code>var PseudoGuid = new (function() {\n this.empty = \"00000000-0000-0000-0000-000000000000\";\n this.GetNew = function() {\n var fourChars = function() {\n return (((1 + Math.random()) * 0x10000)|0).toString(16).substring(1).toUpperCase();\n }\n return (fourChars() + fourChars() + \"-\" + fourChars() + \"-\" + fourChars() + \"-\" + fourChars() + \"-\" + fourChars() + fourChars() + fourChars());\n };\n})();\n\n// usage example:\nvar tempId = PseudoGuid.GetNew();\nsomeDomElement.id = tempId;\n</code></pre>\n\n<p>That works for me, I just tested it in a Greasemonkey script myself.</p>\n\n<hr>\n\n<p><strong>UPDATE:</strong> Closures are the way to go - personally, as a hard-core JavaScript developer, I don't know how you <em>didn't</em> think of those immediately. :) </p>\n\n<pre><code>myDomElement; // some DOM element we want later reference to\n\nsomeOtherDomElement.addEventListener(\"click\", function(e) {\n // because of the closure, here we have a reference to myDomElement\n doSomething(myDomElement);\n}, false);\n</code></pre>\n\n<p>Now, <code>myDomElement</code> is one of the elements you apparently, from your description, already have around (since you were thinking of adding an ID to it, or whatever).</p>\n\n<p>Maybe if you post an example of what you are trying to do, it would be easier to help you, assuming this doesn't.</p>\n" }, { "answer_id": 226912, "author": "Borgar", "author_id": 27388, "author_profile": "https://Stackoverflow.com/users/27388", "pm_score": 2, "selected": false, "text": "<p>If you <em>can</em> write to the DOM (I'm sure you can). I would solve this like this:</p>\n\n<p>Have a function return or generate an ID:</p>\n\n<pre><code>//(function () {\n\n var idCounter = new Date().getTime();\n function getId( node ) {\n return (node.id) ? node.id : (node.id = 'tempIdPrefix_' + idCounter++ );\n }\n\n//})();\n</code></pre>\n\n<p>Use this to get ID's as needed:</p>\n\n<pre><code>var n = document.getElementById('someid');\ngetId(n); // returns \"someid\"\n\nvar n = document.getElementsByTagName('div')[1];\ngetId(n); // returns \"tempIdPrefix_1224697942198\"\n</code></pre>\n\n<p>This way you don't need to worry about what the HTML looks like when the server hands it to you.</p>\n" }, { "answer_id": 227199, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": false, "text": "<p>Closure is the way to go. This way you'll have exact reference to the element that even will survive some shuffling of DOM.</p>\n\n<p>Example for those who don't know closures:</p>\n\n<pre><code>var saved_element = findThatDOMNode();\n\ndocument.body.onclick = function() \n{\n alert(saved_element); // it's still there!\n}\n</code></pre>\n\n<p><em>If</em> you had to store it in a cookie, then I recommend computing XPath for it (e.g. walk up the DOM counting previous siblings until you find element with an ID and you'll end up with something like <code>[@id=foo]/div[4]/p[2]/a</code>). </p>\n\n<p><a href=\"http://www.w3.org/TR/WD-xptr\" rel=\"noreferrer\">XPointer</a> is W3C's solution to that problem.</p>\n" }, { "answer_id": 230114, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 4, "selected": true, "text": "<p><strong>UPDATE:</strong> Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work:</p>\n\n<pre><code>for (var i = 0; i &lt; elements.length; i++) {\n var element = elements[i];\n var button = document.createElement(\"button\");\n button.addEventListener(\"click\", function(ev) {\n // do something with element here\n }, false)\n}\n</code></pre>\n\n<p>But this does:</p>\n\n<pre><code>var buildListener = function(element) {\n return function(ev) {\n // do something with event here\n };\n};\n\nfor (var i = 0; i &lt; elements.length; i++) {\n var element = elements[i];\n var button = document.createElement(\"button\");\n button.addEventListener(\"click\", buildListener(element), false)\n}\n</code></pre>\n\n<p>Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!</p>\n" }, { "answer_id": 232323, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 0, "selected": false, "text": "<p>You can also use pguid (page-unique identifier) for unique identifier generation:</p>\n\n<pre><code> pguid = b9j.pguid.next() // A unique id (suitable for a DOM element)\n // is generated\n // Something like \"b9j-pguid-20a9ff-0\"\n ...\n pguid = b9j.pguid.next() // Another unique one... \"b9j-pguid-20a9ff-1\"\n\n // Build a custom generator\n var sequence = new b9j.pguid.Sequence({ namespace: \"frobozz\" })\n pguid = sequence.next() \"frobozz-c861e1-0\"\n</code></pre>\n\n<p><a href=\"http://appengine.bravo9.com/b9j/documentation/pguid.html\" rel=\"nofollow noreferrer\">http://appengine.bravo9.com/b9j/documentation/pguid.html</a></p>\n" }, { "answer_id": 2525659, "author": "Paul Tierney", "author_id": 302767, "author_profile": "https://Stackoverflow.com/users/302767", "pm_score": 1, "selected": false, "text": "<p>Use mouse and/or positional properties of the element to generate a unique ID.</p>\n" }, { "answer_id": 2546796, "author": "Tom Carnell", "author_id": 258574, "author_profile": "https://Stackoverflow.com/users/258574", "pm_score": 0, "selected": false, "text": "<p>I 'think' I've just solved a problem similar to this. However, I'm using jQuery in a browser DOM environment.</p>\n\n<p>var objA = $(\"selector to some dom element\");\nvar objB = $(\"selector to some other dom element\");</p>\n\n<p>if( objA[0] === objB[0]) {\n //GREAT! the two objects point to exactly the same dom node\n}</p>\n" }, { "answer_id": 24387829, "author": "kisp", "author_id": 419371, "author_profile": "https://Stackoverflow.com/users/419371", "pm_score": 0, "selected": false, "text": "<p>OK, there is no ID associated to DOM element automatically.\nDOM has a hierarchycal structure of elements which is the main information.\nFrom this perspective, you can <strong>associate data to DOM elements</strong> with jQuery or jQLite. It can solve some issues when you have to bind custom data to elements.</p>\n" }, { "answer_id": 44069221, "author": "wybe", "author_id": 2204864, "author_profile": "https://Stackoverflow.com/users/2204864", "pm_score": 2, "selected": false, "text": "<p>You can generate a stable, unique identifier for any given node in a DOM with the following function:</p>\n\n<pre><code>function getUniqueKeyForNode (targetNode) {\n const pieces = ['doc'];\n let node = targetNode;\n\n while (node &amp;&amp; node.parentNode) {\n pieces.push(Array.prototype.indexOf.call(node.parentNode.childNodes, node));\n node = node.parentNode\n }\n\n return pieces.reverse().join('/');\n}\n</code></pre>\n\n<p>This will create identifiers such as <code>doc/0</code>, <code>doc/0/0</code>, <code>doc/0/1</code>, <code>doc/0/1/0</code>, <code>doc/0/1/1</code> for a structure like this one:</p>\n\n<pre><code>&lt;div&gt;\n &lt;div /&gt;\n &lt;div&gt;\n &lt;div /&gt;\n &lt;div /&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>There are also a few optimisations and changes you can make, for example:</p>\n\n<ul>\n<li><p>In the <code>while</code> loop, <code>break</code> when that <code>node</code> has an attribute you know to be unique, for example <code>@id</code></p></li>\n<li><p>Not <code>reverse()</code> the <code>pieces</code>, currently it is just there to look more like the DOM structure the ID's are generated from</p></li>\n<li><p>Not include the first <code>piece</code> <code>doc</code> if you don't need an identifier for the document node</p></li>\n<li><p>Save the identifier on the node in some way, and reuse that value for child nodes to avoid having to traverse all the way up the tree again.</p></li>\n<li><p>If you're writing these identifiers back to XML, use another concatenation character if the attribute you're writing is restricted.</p></li>\n</ul>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
I'm writing a GreaseMonkey script where I'm iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The element itself doesn't have an `id` attribute, and I can't modify the original document to give it one (although I can make DOM changes in my script). I can't store the references in my script because when I need them, the GreaseMonkey script itself will have gone out of scope. Is there some way to get at an "internal" ID that the browser uses, for example? A Firefox-only solution is fine; a cross-browser solution that could be applied in other scenarios would be awesome. Edit: * **If the GreaseMonkey script is out of scope, how are you referencing the elements later?** They GreaseMonkey script is adding events to DOM objects. I can't store the references in an array or some other similar mechanism because when the event fires, the array will be gone because the GreaseMonkey script will have gone out of scope. So the event needs some way to know about the element reference that the script had when the event was attached. And the element in question is not the one to which it is attached. * **Can't you just use a custom property on the element?** Yes, but the problem is on the lookup. I'd have to resort to iterating through all the elements looking for the one that has that custom property set to the desired id. That would work, sure, but in large documents it could be very time consuming. I'm looking for something where the browser can do the lookup grunt work. * **Wait, can you or can you not modify the document?** I can't modify the source document, but I can make DOM changes in the script. I'll clarify in the question. * **Can you not use closures?** Closuses did turn out to work, although I initially thought they wouldn't. See my later post. It sounds like the answer to the question: "Is there some internal browser ID I could use?" is "No."
**UPDATE:** Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work: ``` for (var i = 0; i < elements.length; i++) { var element = elements[i]; var button = document.createElement("button"); button.addEventListener("click", function(ev) { // do something with element here }, false) } ``` But this does: ``` var buildListener = function(element) { return function(ev) { // do something with event here }; }; for (var i = 0; i < elements.length; i++) { var element = elements[i]; var button = document.createElement("button"); button.addEventListener("click", buildListener(element), false) } ``` Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!
226,701
<p>QA tester was reading HTML/JS code to write a functional test of a web form, and saw:</p> <pre><code>if (form_field == empty) { ...do stuff for empty field } else if (form_field != empty) { ...do stuff for non-empty field } else { ...do stuff that will never be done } </code></pre> <p>After a couple embarrassing attempts, tester realized that they couldn't trigger the alert strings hidden in the third block.</p> <p>Things I'm wondering are if this Is this problem more or less language specific (can non-JS people learn lessons here?) and are there legitimate reasons code ended up this way?</p> <p>How can I find/address the problem?</p>
[ { "answer_id": 226729, "author": "UnhipGlint", "author_id": 13010, "author_profile": "https://Stackoverflow.com/users/13010", "pm_score": 1, "selected": false, "text": "<p>I don't believe that this problem is at all language specific. You could construct similar (flawed) conditional statements in a wide variety of other languages.</p>\n\n<p>Also, I don't think that there is a legitimate reason for the conditional statement to be structured this way. As you state in the comment, the statements in the third block will just never be done.</p>\n\n<p>You could probably find mistakes like this most effectively with code review. However, since that requires quite a bit of time from at least one developer, you may be better served by developing quality unit tests and inspecting code coverage. In this case, you probably would have noticed that the third portion of the conditional statement was never used.</p>\n" }, { "answer_id": 226730, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>I've seen cases where the else if used to have something else (AND/OR) there and the person who fixed it just 'fixed it' and didn't probe very deep.</p>\n" }, { "answer_id": 226732, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>In the general form</p>\n\n<pre><code>if (a)\n //1\nelse if (!a)\n //2\nelse\n //3\n</code></pre>\n\n<p>can always be reduced to </p>\n\n<pre><code>if (a)\n //1\nelse\n //2\n</code></pre>\n\n<p>with no side-effects.</p>\n" }, { "answer_id": 226736, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>I know I remember writing a few like that way back in my first year or two of college, before I knew any better. But I can't see a reason to do it now.</p>\n\n<p>The only way it's even close to legitimate is if either \"empty\" or \"form_field\" were a volatile value, similar to VB's Now() function. But in that case, I wouldn't write it this way. Instead, you trap the value once above the if block and test on the trapped value.</p>\n" }, { "answer_id": 226737, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>static analysis would have told you that the third case is \"dead code\"</p>\n\n<p>code like this comes from a misunderstanding of Boolean logic, or multiple edits over time by different people - or both ;-)</p>\n\n<p>this is not specific to Javascript, this kind of mistake can be made in any language that has the if-else structure (or a reasonable facsimile thereof)</p>\n" }, { "answer_id": 226740, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 3, "selected": false, "text": "<p>Although the third block can't trigger in Javascript, that is not true in all languages. In T-SQL:</p>\n\n<pre><code>declare @test as int\n\nset @test = null\n\nif @test = 1 \n print 1\nelse if not @test = 1\n print 2\nelse \n print 3\n</code></pre>\n\n<p>This will print 3, because NULL is neither equal to, nor not equal to any other value.</p>\n" }, { "answer_id": 226746, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Is this problem more or less language specific (can non-JS people learn lessons here?) </li>\n</ul>\n\n<p>No. You could run into this kind of code in any language with branches and comparisons. </p>\n\n<ul>\n<li>Are there legitimate reasons code ended up this way?</li>\n<li>What approaches should be used to find/address the problem (code coverage, code review, blackbox testing, etc.) </li>\n</ul>\n\n<p>No, not really. I'd guess that code started out with something other than a Boolean comparison; maybe it was empty, numeric, or non-numeric, or empty, 1-5 chars, or more than 5 chars, something like that. When the logic was changed to empty or non-empty, the third block should have been removed - this would normally be caught in a peer review or something like that.</p>\n\n<p>Depending on the language, some compilers may even catch this. A review would catch it; black-box testing would not, because you wouldn't be checking the code, but white-box testing would (although you should also notice it as soon as you see the code, before any testing is actually done).</p>\n" }, { "answer_id": 226751, "author": "64BitBob", "author_id": 16339, "author_profile": "https://Stackoverflow.com/users/16339", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>Is this problem more or less language\n specific (can non-JS people learn\n lessons here?)</p>\n</blockquote>\n\n<p>This is a language-agnostic problem. It's quite easy to write the following in Java, for example:</p>\n\n<pre><code>if(x)\n{\n //do something\n}\nelse if(!x)\n{\n //do something else\n}\nelse\n{\n //never, ever, do anything\n}\n</code></pre>\n\n<p>The key thing to remember is that the \"if(!x)\" is not required. Making that a simple \"else\" would create simpler code.</p>\n\n<pre><code>Are there legitimate reasons code ended up this way?\n</code></pre>\n\n<p>Sort of. It's standard practice for an else condition to always exist when a fall-through is needed. The problem was the programmer wasn't thinking very clearly single his \"(form_field != empty)\" was exactly the same as a simple \"else\". Point it out to him and he should kick himself. If he doesn't, question his role on the team.</p>\n\n<blockquote>\n <p>What approaches should be used to\n find/address the problem (code\n coverage, code review, blackbox\n testing, etc.)</p>\n</blockquote>\n\n<p>Static code analysis tools can catch this sort of issue. However, I'm not aware of any for Javascript. <a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a> can catch a lot of bad stuff, but not logic flow issues.</p>\n" }, { "answer_id": 226763, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 0, "selected": false, "text": "<p>This class of problem is easy to spot if you are testing a single condition A, because you know that you can have A and not-A. </p>\n\n<p>It's also not too hard to do if you had conditions A and B. You look for A, not-A and B, not-A and not-B (for example) - and you can fairly easily tell that you've covered all cases. </p>\n\n<p>Sometimes, for whatever reason, the conditions might get refactored out, and then (taking the above contrived example) while leaving the three blocks behind, and the resulting WTF.</p>\n\n<p>But what if you had conditions A, B, C, and D? Stacked if-else's is really a gnarly way of doing it, but sometimes that's just the way it gets done.</p>\n\n<p>Spotting \"holes\" in the logic coverage is easy to do by creating a complete truth table. A nice way to do this is with Karnaugh maps. The wikipedia entry on <a href=\"http://en.wikipedia.org/wiki/Karnaugh_map\" rel=\"nofollow noreferrer\">Karnaugh maps</a> is a great starting point (with pictures, even!). For software coding, you want full coverage of the map without an overlap (well, at least, usually). </p>\n" }, { "answer_id": 226774, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 2, "selected": false, "text": "<p>This can happen if you use poorly designed booleans (common in early C when there wasn't a true boolean type). You can still find this stuff in Windows.</p>\n\n<pre><code>BOOL result = SomeWindowsAPI();\nif (result == TRUE)\n{\n // success\n}\nelse if (result == FALSE)\n{\n // failure\n}\nelse\n{\n // wtf?\n}\n</code></pre>\n\n<p>The key here is the explicit testing for \"TRUE\" which assumes that there is one and only one way the boolean can have a true value. When using integers as booleans, this isn't true.</p>\n\n<p>In some languages on some computers (Fortran on VMS), there can be many different integer values that resolve to true and many different values resolve to false. On Windows, the HRESULT when being interpreted as SUCCESS or FAILURE is the same way.</p>\n" }, { "answer_id": 226797, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 1, "selected": false, "text": "<p>Perhaps not in JavaScript, but any laguage that supports multithreaded programming, <em>and</em> declares form_field in such a way that it is shared between more than one thread could actually see that happen.</p>\n\n<p>For example, <a href=\"http://en.wikipedia.org/wiki/Peterson%27s_algorithm\" rel=\"nofollow noreferrer\">Peterson's algorithm</a> contains a similarly useless-looking double check:</p>\n\n<pre><code> turn = 1;\n while( flag[1] &amp;&amp; turn == 1 );\n</code></pre>\n\n<p>That's protecting against a race condition though. It'd still be damn tough to generate a test to cause it.</p>\n\n<p>If there is no possible race condition then this is the kind of check we used to jokingly call a \"cosmic ray check\" back when I contracted for NASA. :-)</p>\n" }, { "answer_id": 226806, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>Different smells show up with different measurements.</p>\n\n<p>I have found <a href=\"http://www.google.com/search?q=cyclomatic+complexity+tool\" rel=\"nofollow noreferrer\">Cyclomatic Complexity</a> tools useful. Anything with a complexity over about 5 deserves a closer look.</p>\n" }, { "answer_id": 1593575, "author": "Asher", "author_id": 156470, "author_profile": "https://Stackoverflow.com/users/156470", "pm_score": 0, "selected": false, "text": "<p>This happened at our company and I thought it was the funniest thing that the \"dead code\" in the second else was being executed. \nIn our case it was an <strong>untyped pointer</strong> (don't ask why we have those) that was incorrectly set and cast to a class that had a Boolean Field.</p>\n\n<p>The \"<code>if (A = TRUE) .. else if (A == FALSE) .. else ..</code>\" was applied to the Boolean field. The resulting asm code was as follows:</p>\n\n<pre><code>cmp al,$01\njnz +$0c\n...\ntest al,al\njnz +$0c\n...\n</code></pre>\n\n<p>clear the value in <strong>al</strong> was > 1 and it fell through to the <strong>else ..</strong></p>\n\n<p>the fact the coder wrote this expecting it to happen is another matter...</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2910/" ]
QA tester was reading HTML/JS code to write a functional test of a web form, and saw: ``` if (form_field == empty) { ...do stuff for empty field } else if (form_field != empty) { ...do stuff for non-empty field } else { ...do stuff that will never be done } ``` After a couple embarrassing attempts, tester realized that they couldn't trigger the alert strings hidden in the third block. Things I'm wondering are if this Is this problem more or less language specific (can non-JS people learn lessons here?) and are there legitimate reasons code ended up this way? How can I find/address the problem?
> > Is this problem more or less language > specific (can non-JS people learn > lessons here?) > > > This is a language-agnostic problem. It's quite easy to write the following in Java, for example: ``` if(x) { //do something } else if(!x) { //do something else } else { //never, ever, do anything } ``` The key thing to remember is that the "if(!x)" is not required. Making that a simple "else" would create simpler code. ``` Are there legitimate reasons code ended up this way? ``` Sort of. It's standard practice for an else condition to always exist when a fall-through is needed. The problem was the programmer wasn't thinking very clearly single his "(form\_field != empty)" was exactly the same as a simple "else". Point it out to him and he should kick himself. If he doesn't, question his role on the team. > > What approaches should be used to > find/address the problem (code > coverage, code review, blackbox > testing, etc.) > > > Static code analysis tools can catch this sort of issue. However, I'm not aware of any for Javascript. [JSLint](http://www.jslint.com/) can catch a lot of bad stuff, but not logic flow issues.
226,703
<p>I want to pause input in a shell script, and prompt the user for choices.<br> The standard <code>Yes</code>, <code>No</code>, or <code>Cancel</code> type question.<br> How do I accomplish this in a typical bash prompt?</p>
[ { "answer_id": 226720, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 8, "selected": false, "text": "<pre><code>echo \"Please enter some input: \"\nread input_variable\necho \"You entered: $input_variable\"\n</code></pre>\n" }, { "answer_id": 226722, "author": "SumoRunner", "author_id": 18975, "author_profile": "https://Stackoverflow.com/users/18975", "pm_score": 6, "selected": false, "text": "<pre><code>inquire () {\n echo -n \"$1 [y/n]? \"\n read answer\n finish=\"-1\"\n while [ \"$finish\" = '-1' ]\n do\n finish=\"1\"\n if [ \"$answer\" = '' ];\n then\n answer=\"\"\n else\n case $answer in\n y | Y | yes | YES ) answer=\"y\";;\n n | N | no | NO ) answer=\"n\";;\n *) finish=\"-1\";\n echo -n 'Invalid response -- please reenter:';\n read answer;;\n esac\n fi\n done\n}\n\n... other stuff\n\ninquire \"Install now?\"\n\n...\n</code></pre>\n" }, { "answer_id": 226724, "author": "Myrddin Emrys", "author_id": 9084, "author_profile": "https://Stackoverflow.com/users/9084", "pm_score": 12, "selected": true, "text": "<p>The simplest and most widely available method to get user input at a shell prompt is the <a href=\"https://www.gnu.org/software/bash/manual/bashref.html#index-read\" rel=\"noreferrer\"><code>read</code></a> command. The best way to illustrate its use is a simple demonstration:</p>\n<pre><code>while true; do\n read -p &quot;Do you wish to install this program? &quot; yn\n case $yn in\n [Yy]* ) make install; break;;\n [Nn]* ) exit;;\n * ) echo &quot;Please answer yes or no.&quot;;;\n esac\ndone\n</code></pre>\n<p>Another method, <a href=\"https://stackoverflow.com/a/226946/9084\">pointed out</a> by <a href=\"https://stackoverflow.com/users/28604/steven-huwig\">Steven Huwig</a>, is Bash's <a href=\"https://www.gnu.org/software/bash/manual/bashref.html#index-select\" rel=\"noreferrer\"><code>select</code></a> command. Here is the same example using <code>select</code>:</p>\n<pre><code>echo &quot;Do you wish to install this program?&quot;\nselect yn in &quot;Yes&quot; &quot;No&quot;; do\n case $yn in\n Yes ) make install; break;;\n No ) exit;;\n esac\ndone\n</code></pre>\n<p>With <code>select</code> you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a <code>while true</code> loop to retry if they give invalid input.</p>\n<p>Also, <a href=\"https://stackoverflow.com/users/7939871/l%c3%a9a-gris\">Léa Gris</a> demonstrated a way to make the request language agnostic in <a href=\"https://stackoverflow.com/a/57739142/9084\">her answer</a>. Adapting my first example to better serve multiple languages might look like this:</p>\n<pre><code>set -- $(locale LC_MESSAGES)\nyesexpr=&quot;$1&quot;; noexpr=&quot;$2&quot;; yesword=&quot;$3&quot;; noword=&quot;$4&quot;\n\nwhile true; do\n read -p &quot;Install (${yesword} / ${noword})? &quot; yn\n if [[ &quot;$yn&quot; =~ $yesexpr ]]; then make install; exit; fi\n if [[ &quot;$yn&quot; =~ $noexpr ]]; then exit; fi\n echo &quot;Answer ${yesword} / ${noword}.&quot;\ndone\n</code></pre>\n<p>Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.</p>\n<p>Finally, please check out the <a href=\"https://stackoverflow.com/a/27875395/9084\">excellent answer</a> by <a href=\"https://stackoverflow.com/users/1765658/f-hauri\">F. Hauri</a>.</p>\n" }, { "answer_id": 226742, "author": "Osama Al-Maadeed", "author_id": 25544, "author_profile": "https://Stackoverflow.com/users/25544", "pm_score": 2, "selected": false, "text": "<p>I suggest you <a href=\"http://www.linuxjournal.com/article/2460\" rel=\"nofollow noreferrer\">use dialog</a>...</p>\n<blockquote>\n<h3><a href=\"http://www.linuxjournal.com/article/2460\" rel=\"nofollow noreferrer\">Linux Apprentice: Improve Bash Shell Scripts Using Dialog</a></h3>\n<p>The dialog command enables the use of window boxes in shell scripts to make their use more interactive.</p>\n</blockquote>\n<p>it's simple and easy to use, there's also a gnome version called gdialog that takes the exact same parameters, but shows it GUI style on X.</p>\n" }, { "answer_id": 226946, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 7, "selected": false, "text": "<p>Bash has <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs\" rel=\"noreferrer\">select</a> for this purpose.</p>\n\n<pre><code>select result in Yes No Cancel\ndo\n echo $result\ndone\n</code></pre>\n" }, { "answer_id": 4886643, "author": "serg", "author_id": 601562, "author_profile": "https://Stackoverflow.com/users/601562", "pm_score": 6, "selected": false, "text": "<pre><code>read -p \"Are you alright? (y/n) \" RESP\nif [ \"$RESP\" = \"y\" ]; then\n echo \"Glad to hear it\"\nelse\n echo \"You need more bash programming\"\nfi\n</code></pre>\n" }, { "answer_id": 5987314, "author": "yPhil", "author_id": 1729094, "author_profile": "https://Stackoverflow.com/users/1729094", "pm_score": 7, "selected": false, "text": "<p>You can use the built-in <a href=\"http://ss64.com/bash/read.html\" rel=\"noreferrer\">read</a> command ; Use the <code>-p</code> option to prompt the user with a question.</p>\n\n<p>Since BASH4, you can now use <code>-i</code> to suggest an answer :</p>\n\n<pre><code>read -e -p \"Enter the path to the file: \" -i \"/usr/local/etc/\" FILEPATH\necho $FILEPATH\n</code></pre>\n\n<p>(But remember to use the \"readline\" option <code>-e</code> to allow line editing with arrow keys)</p>\n\n<p>If you want a \"yes / no\" logic, you can do something like this:</p>\n\n<pre><code>read -e -p \"\nList the content of your home dir ? [Y/n] \" YN\n\n[[ $YN == \"y\" || $YN == \"Y\" || $YN == \"\" ]] &amp;&amp; ls -la ~/\n</code></pre>\n" }, { "answer_id": 10508165, "author": "ThatLinuxGuy", "author_id": 1383344, "author_profile": "https://Stackoverflow.com/users/1383344", "pm_score": 5, "selected": false, "text": "<p>Use the <code>read</code> command:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>echo Would you like to install? \"(Y or N)\"\n\nread x\n\n# now check if $x is \"y\"\nif [ \"$x\" = \"y\" ]; then\n # do something here!\nfi\n</code></pre>\n\n<p>and then all of the other stuff you need</p>\n" }, { "answer_id": 12202793, "author": "mpen", "author_id": 65387, "author_profile": "https://Stackoverflow.com/users/65387", "pm_score": 5, "selected": false, "text": "<p>Here's something I put together:</p>\n\n<pre><code>#!/bin/sh\n\npromptyn () {\n while true; do\n read -p \"$1 \" yn\n case $yn in\n [Yy]* ) return 0;;\n [Nn]* ) return 1;;\n * ) echo \"Please answer yes or no.\";;\n esac\n done\n}\n\nif promptyn \"is the sky blue?\"; then\n echo \"yes\"\nelse\n echo \"no\"\nfi\n</code></pre>\n\n<p>I'm a beginner, so take this with a grain of salt, but it seems to work.</p>\n" }, { "answer_id": 18968774, "author": "jlettvin", "author_id": 1363592, "author_profile": "https://Stackoverflow.com/users/1363592", "pm_score": 2, "selected": false, "text": "<pre><code>yn() {\n if [[ 'y' == `read -s -n 1 -p \"[y/n]: \" Y; echo $Y` ]];\n then eval $1;\n else eval $2;\n fi }\nyn 'echo yes' 'echo no'\nyn 'echo absent no function works too!'\n</code></pre>\n" }, { "answer_id": 19995350, "author": "Dennis", "author_id": 72321, "author_profile": "https://Stackoverflow.com/users/72321", "pm_score": 4, "selected": false, "text": "<p>This solution reads a single character and calls a function on a yes response.</p>\n\n<pre><code>read -p \"Are you sure? (y/n) \" -n 1\necho\nif [[ $REPLY =~ ^[Yy]$ ]]; then\n do_something \nfi\n</code></pre>\n" }, { "answer_id": 20817520, "author": "Ernest A", "author_id": 1278855, "author_profile": "https://Stackoverflow.com/users/1278855", "pm_score": 3, "selected": false, "text": "<p>Multiple choice version:</p>\n\n<pre><code>ask () { # $1=question $2=options\n # set REPLY\n # options: x=..|y=..\n while $(true); do\n printf '%s [%s] ' \"$1\" \"$2\"\n stty cbreak\n REPLY=$(dd if=/dev/tty bs=1 count=1 2&gt; /dev/null)\n stty -cbreak\n test \"$REPLY\" != \"$(printf '\\n')\" &amp;&amp; printf '\\n'\n (\n IFS='|'\n for o in $2; do\n if [ \"$REPLY\" = \"${o%%=*}\" ]; then\n printf '\\n'\n break\n fi\n done\n ) | grep ^ &gt; /dev/null &amp;&amp; return\n done\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ ask 'continue?' 'y=yes|n=no|m=maybe'\ncontinue? [y=yes|n=no|m=maybe] g\ncontinue? [y=yes|n=no|m=maybe] k\ncontinue? [y=yes|n=no|m=maybe] y\n$\n</code></pre>\n\n<p>It will set <code>REPLY</code> to <code>y</code> (inside the script).</p>\n" }, { "answer_id": 22893526, "author": "Thorsten Staerk", "author_id": 236872, "author_profile": "https://Stackoverflow.com/users/236872", "pm_score": 4, "selected": false, "text": "<p>To get a nice ncurses-like inputbox use the command <strong><em>dialog</em></strong> like this:</p>\n\n<pre><code>#!/bin/bash\nif (dialog --title \"Message\" --yesno \"Want to do something risky?\" 6 25)\n# message box will have the size 25x6 characters\nthen \n echo \"Let's do something risky\"\n # do something risky\nelse \n echo \"Let's stay boring\"\nfi\n</code></pre>\n\n<p>The dialog package is installed by default at least with SUSE Linux. Looks like:\n<a href=\"https://i.stack.imgur.com/UExu9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/UExu9.png\" alt=\"the &quot;dialog&quot; command in action\"></a></p>\n" }, { "answer_id": 23781791, "author": "user9869932", "author_id": 1183098, "author_profile": "https://Stackoverflow.com/users/1183098", "pm_score": 4, "selected": false, "text": "<p>In my case I needed to read from a downloaded script i.e.,</p>\n<pre><code>curl -Ss https://example.com/installer.sh | sh\n</code></pre>\n<p>The line <code>read -r yn &lt;/dev/tty</code> allowed it to read input in this case.</p>\n<pre><code>printf &quot;These files will be uploaded. Is this ok? (y/N) &quot;\nread -r yn &lt;/dev/tty\n\nif [ &quot;$yn&quot; = &quot;y&quot; ]; then\n \n # Yes\nelse\n \n # No\nfi\n</code></pre>\n" }, { "answer_id": 27831208, "author": "Miguel", "author_id": 674405, "author_profile": "https://Stackoverflow.com/users/674405", "pm_score": 3, "selected": false, "text": "<p>Inspired by the answers of @Mark and @Myrddin I created this function for a universal prompt</p>\n\n<pre><code>uniprompt(){\n while true; do\n echo -e \"$1\\c\"\n read opt\n array=($2)\n case \"${array[@]}\" in *\"$opt\"*) eval \"$3=$opt\";return 0;; esac\n echo -e \"$opt is not a correct value\\n\"\n done\n}\n</code></pre>\n\n<p>use it like this:</p>\n\n<pre><code>unipromtp \"Select an option: (a)-Do one (x)-&gt;Do two (f)-&gt;Do three : \" \"a x f\" selection\necho \"$selection\"\n</code></pre>\n" }, { "answer_id": 27875395, "author": "F. Hauri - Give Up GitHub", "author_id": 1765658, "author_profile": "https://Stackoverflow.com/users/1765658", "pm_score": 9, "selected": false, "text": "<h1>At least five answers for one generic question.</h1>\n<p>Depending on</p>\n<ul>\n<li><a href=\"/questions/tagged/posix\" class=\"post-tag\" title=\"show questions tagged &#39;posix&#39;\" aria-label=\"show questions tagged &#39;posix&#39;\" rel=\"tag\" aria-labelledby=\"posix-container\">posix</a> compliant: could work on poor systems with generic <a href=\"/questions/tagged/shell\" class=\"post-tag\" title=\"show questions tagged &#39;shell&#39;\" aria-label=\"show questions tagged &#39;shell&#39;\" rel=\"tag\" aria-labelledby=\"shell-container\">shell</a> environments</li>\n<li><a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged &#39;bash&#39;\" aria-label=\"show questions tagged &#39;bash&#39;\" rel=\"tag\" aria-labelledby=\"bash-container\">bash</a> specific: using so called <em>bashisms</em></li>\n</ul>\n<p>and if you want</p>\n<ul>\n<li>simple ``in line'' question / answer (generic solutions)</li>\n<li>pretty formatted interfaces, like <a href=\"/questions/tagged/ncurses\" class=\"post-tag\" title=\"show questions tagged &#39;ncurses&#39;\" aria-label=\"show questions tagged &#39;ncurses&#39;\" rel=\"tag\" aria-labelledby=\"ncurses-container\">ncurses</a> or more graphical using libgtk or libqt...</li>\n<li>use powerful readline history capability</li>\n</ul>\n<h2>1. POSIX generic solutions</h2>\n<p>You could use the <code>read</code> command, followed by <code>if ... then ... else</code>:</p>\n<pre><code>printf 'Is this a good question (y/n)? '\nread answer\n</code></pre>\n<s>\n<pre><code># if echo &quot;$answer&quot; | grep -iq &quot;^y&quot; ;then\n</code></pre>\n</s>\n<pre><code>if [ &quot;$answer&quot; != &quot;${answer#[Yy]}&quot; ] ;then # this grammar (the #[] operator) means that the variable $answer where any Y or y in 1st position will be dropped if they exist.\n echo Yes\nelse\n echo No\nfi\n</code></pre>\n<p>(Thanks to <a href=\"https://stackoverflow.com/posts/comments/86532780?noredirect=1\">Adam Katz's comment</a>: Replaced the test above with one that is more portable and avoids one fork:)</p>\n<h3>POSIX, but single key feature</h3>\n<p>But if you don't want the user to have to hit <kbd>Return</kbd>, you could write:</p>\n<p>(<strong>Edited:</strong> As <a href=\"https://stackoverflow.com/users/15168/jonathan-leffler\">@JonathanLeffler</a> rightly suggest, <em>saving</em> stty's configuration could be better than simply force them to <em>sane</em>.)</p>\n<pre><code>printf 'Is this a good question (y/n)? '\nold_stty_cfg=$(stty -g)\nstty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with stty\nif echo &quot;$answer&quot; | grep -iq &quot;^y&quot; ;then\n echo Yes\nelse\n echo No\nfi\n</code></pre>\n<p><strong>Note:</strong> This was tested under <a href=\"/questions/tagged/sh\" class=\"post-tag\" title=\"show questions tagged &#39;sh&#39;\" aria-label=\"show questions tagged &#39;sh&#39;\" rel=\"tag\" aria-labelledby=\"sh-container\">sh</a>, <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged &#39;bash&#39;\" aria-label=\"show questions tagged &#39;bash&#39;\" rel=\"tag\" aria-labelledby=\"bash-container\">bash</a>, <a href=\"/questions/tagged/ksh\" class=\"post-tag\" title=\"show questions tagged &#39;ksh&#39;\" aria-label=\"show questions tagged &#39;ksh&#39;\" rel=\"tag\" aria-labelledby=\"ksh-container\">ksh</a>, <a href=\"/questions/tagged/dash\" class=\"post-tag\" title=\"show questions tagged &#39;dash&#39;\" aria-label=\"show questions tagged &#39;dash&#39;\" rel=\"tag\" aria-labelledby=\"dash-container\">dash</a> and <a href=\"/questions/tagged/busybox\" class=\"post-tag\" title=\"show questions tagged &#39;busybox&#39;\" aria-label=\"show questions tagged &#39;busybox&#39;\" rel=\"tag\" aria-labelledby=\"busybox-container\">busybox</a>!</p>\n<p>Same, but waiting explicitly for <kbd>y</kbd> or <kbd>n</kbd>:</p>\n<pre><code>#/bin/sh\nprintf 'Is this a good question (y/n)? '\nold_stty_cfg=$(stty -g)\nstty raw -echo\nanswer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )\nstty $old_stty_cfg\nif echo &quot;$answer&quot; | grep -iq &quot;^y&quot; ;then\n echo Yes\nelse\n echo No\nfi\n</code></pre>\n<h3>Using dedicated tools</h3>\n<p>There are many tools which were built using <code>libncurses</code>, <code>libgtk</code>, <code>libqt</code> or other graphical libraries. For example, using <code>whiptail</code>:</p>\n<pre><code>if whiptail --yesno &quot;Is this a good question&quot; 20 60 ;then\n echo Yes\nelse\n echo No\nfi\n</code></pre>\n<p>Depending on your system, you may need to replace <code>whiptail</code> with another similiar tool:</p>\n<pre><code>dialog --yesno &quot;Is this a good question&quot; 20 60 &amp;&amp; echo Yes\n\ngdialog --yesno &quot;Is this a good question&quot; 20 60 &amp;&amp; echo Yes\n\nkdialog --yesno &quot;Is this a good question&quot; 20 60 &amp;&amp; echo Yes\n</code></pre>\n<p>where <code>20</code> is height of dialog box in number of lines and <code>60</code> is width of the dialog box. These tools all have <em>near same</em> syntax.</p>\n<pre><code>DIALOG=whiptail\nif [ -x /usr/bin/gdialog ] ;then DIALOG=gdialog ; fi\nif [ -x /usr/bin/xdialog ] ;then DIALOG=xdialog ; fi\n...\n$DIALOG --yesno ...\n</code></pre>\n<h2>2. Bash specific solutions</h2>\n<h3>Basic <em>in line</em> method</h3>\n<pre><code>read -p &quot;Is this a good question (y/n)? &quot; answer\ncase ${answer:0:1} in\n y|Y )\n echo Yes\n ;;\n * )\n echo No\n ;;\nesac\n</code></pre>\n<p>I prefer to use <code>case</code> so I could even test for <code>yes | ja | si | oui</code> if needed...</p>\n<h3><em>in line</em> with <em>single key</em> feature</h3>\n<p>Under bash, we can specify the length of intended input for for the <code>read</code> command:</p>\n<pre><code>read -n 1 -p &quot;Is this a good question (y/n)? &quot; answer\n</code></pre>\n<p>Under bash, <code>read</code> command accepts a <em>timeout</em> parameter, which could be useful.</p>\n<pre><code>read -t 3 -n 1 -p &quot;Is this a good question (y/n)? &quot; answer\n[ -z &quot;$answer&quot; ] &amp;&amp; answer=&quot;Yes&quot; # if 'yes' have to be default choice\n</code></pre>\n<h2>3. Some tricks for <em>dedicated tools</em></h2>\n<p>More sophisticated dialog boxes, beyond simple <em><code>yes - no</code></em> purposes:</p>\n<pre><code>dialog --menu &quot;Is this a good question&quot; 20 60 12 y Yes n No m Maybe\n</code></pre>\n<p>Progress bar:</p>\n<pre><code>dialog --gauge &quot;Filling the tank&quot; 20 60 0 &lt; &lt;(\n for i in {1..100};do\n printf &quot;XXX\\n%d\\n%(%a %b %T)T progress: %d\\nXXX\\n&quot; $i -1 $i\n sleep .033\n done\n) \n</code></pre>\n<p>Little demo:</p>\n<pre><code>#!/bin/sh\nwhile true ;do\n [ -x &quot;$(which ${DIALOG%% *})&quot; ] || DIALOG=dialog\n DIALOG=$($DIALOG --menu &quot;Which tool for next run?&quot; 20 60 12 2&gt;&amp;1 \\\n whiptail &quot;dialog boxes from shell scripts&quot; &gt;/dev/tty \\\n dialog &quot;dialog boxes from shell with ncurses&quot; \\\n gdialog &quot;dialog boxes from shell with Gtk&quot; \\\n kdialog &quot;dialog boxes from shell with Kde&quot; ) || exit\n clear;echo &quot;Choosed: $DIALOG.&quot;\n for i in `seq 1 100`;do\n date +&quot;`printf &quot;XXX\\n%d\\n%%a %%b %%T progress: %d\\nXXX\\n&quot; $i $i`&quot;\n sleep .0125\n done | $DIALOG --gauge &quot;Filling the tank&quot; 20 60 0\n $DIALOG --infobox &quot;This is a simple info box\\n\\nNo action required&quot; 20 60\n sleep 3\n if $DIALOG --yesno &quot;Do you like this demo?&quot; 20 60 ;then\n AnsYesNo=Yes; else AnsYesNo=No; fi\n AnsInput=$($DIALOG --inputbox &quot;A text:&quot; 20 60 &quot;Text here...&quot; 2&gt;&amp;1 &gt;/dev/tty)\n AnsPass=$($DIALOG --passwordbox &quot;A secret:&quot; 20 60 &quot;First...&quot; 2&gt;&amp;1 &gt;/dev/tty)\n $DIALOG --textbox /etc/motd 20 60\n AnsCkLst=$($DIALOG --checklist &quot;Check some...&quot; 20 60 12 \\\n Correct &quot;This demo is useful&quot; off \\\n Fun &quot;This demo is nice&quot; off \\\n Strong &quot;This demo is complex&quot; on 2&gt;&amp;1 &gt;/dev/tty)\n AnsRadio=$($DIALOG --radiolist &quot;I will:&quot; 20 60 12 \\\n &quot; -1&quot; &quot;Downgrade this answer&quot; off \\\n &quot; 0&quot; &quot;Not do anything&quot; on \\\n &quot; +1&quot; &quot;Upgrade this anser&quot; off 2&gt;&amp;1 &gt;/dev/tty)\n out=&quot;Your answers:\\nLike: $AnsYesNo\\nInput: $AnsInput\\nSecret: $AnsPass&quot;\n $DIALOG --msgbox &quot;$out\\nAttribs: $AnsCkLst\\nNote: $AnsRadio&quot; 20 60\n done\n</code></pre>\n<p>More samples? Have a look at <a href=\"https://stackoverflow.com/questions/50560500/linux-shell-get-device-id-from-user-input/50577400#50577400\">Using whiptail for choosing USB device</a> and <a href=\"https://unix.stackexchange.com/questions/119759/removable-usb-stick-listed-as-non-removable-in-sys-block/119816#119816\">USB removable storage selector: USBKeyChooser</a></p>\n<h2>5. Using readline's history</h2>\n<p>Example:</p>\n<pre><code>#!/bin/bash\n\nset -i\nHISTFILE=~/.myscript.history\nhistory -c\nhistory -r\n\nmyread() {\n read -e -p '&gt; ' $1\n history -s ${!1}\n}\ntrap 'history -a;exit' 0 1 2 3 6\n\nwhile myread line;do\n case ${line%% *} in\n exit ) break ;;\n * ) echo &quot;Doing something with '$line'&quot; ;;\n esac\n done\n</code></pre>\n<p>This will create a file <code>.myscript.history</code> in your <code>$HOME</code> directory, than you could use readline's history commands, like <kbd>Up</kbd>, <kbd>Down</kbd>, <kbd>Ctrl</kbd>+<kbd>r</kbd> and others.</p>\n" }, { "answer_id": 29523713, "author": "Joshua Goldberg", "author_id": 411282, "author_profile": "https://Stackoverflow.com/users/411282", "pm_score": 2, "selected": false, "text": "<p>One simple way to do this is with <code>xargs -p</code> or gnu <code>parallel --interactive</code>.</p>\n\n<p>I like the behavior of xargs a little better for this because it executes each command immediately after the prompt like other interactive unix commands, rather than collecting the yesses to run at the end. (You can Ctrl-C after you get through the ones you wanted.)</p>\n\n<p>e.g., </p>\n\n<pre><code>echo *.xml | xargs -p -n 1 -J {} mv {} backup/\n</code></pre>\n" }, { "answer_id": 29724498, "author": "Jahid", "author_id": 3744681, "author_profile": "https://Stackoverflow.com/users/3744681", "pm_score": 4, "selected": false, "text": "<pre><code>read -e -p \"Enter your choice: \" choice\n</code></pre>\n\n<p>The <code>-e</code> option enables the user to edit the input using arrow keys.</p>\n\n<p>If you want to use a suggestion as input:</p>\n\n<pre><code>read -e -i \"yes\" -p \"Enter your choice: \" choice\n</code></pre>\n\n<p><code>-i</code> option prints a suggestive input.</p>\n" }, { "answer_id": 30652018, "author": "ccDict", "author_id": 1158046, "author_profile": "https://Stackoverflow.com/users/1158046", "pm_score": 2, "selected": false, "text": "<p>As a friend of a one line command I used the following:</p>\n\n<pre><code>while [ -z $prompt ]; do read -p \"Continue (y/n)?\" choice;case \"$choice\" in y|Y ) prompt=true; break;; n|N ) exit 0;; esac; done; prompt=;\n</code></pre>\n\n<p>Written longform, it works like this:</p>\n\n<pre><code>while [ -z $prompt ];\n do read -p \"Continue (y/n)?\" choice;\n case \"$choice\" in\n y|Y ) prompt=true; break;;\n n|N ) exit 0;;\n esac;\ndone;\nprompt=;\n</code></pre>\n" }, { "answer_id": 31699418, "author": "Alexander Löfqvist", "author_id": 4888007, "author_profile": "https://Stackoverflow.com/users/4888007", "pm_score": 2, "selected": false, "text": "<p>more generic would be:</p>\n\n<pre><code>function menu(){\n title=\"Question time\"\n prompt=\"Select:\"\n options=(\"Yes\" \"No\" \"Maybe\")\n echo \"$title\"\n PS3=\"$prompt\"\n select opt in \"${options[@]}\" \"Quit/Cancel\"; do\n case \"$REPLY\" in\n 1 ) echo \"You picked $opt which is option $REPLY\";;\n 2 ) echo \"You picked $opt which is option $REPLY\";;\n 3 ) echo \"You picked $opt which is option $REPLY\";;\n $(( ${#options[@]}+1 )) ) clear; echo \"Goodbye!\"; exit;;\n *) echo \"Invalid option. Try another one.\";continue;;\n esac\n done\n return\n}\n</code></pre>\n" }, { "answer_id": 34354784, "author": "oHo", "author_id": 938111, "author_profile": "https://Stackoverflow.com/users/938111", "pm_score": 5, "selected": false, "text": "<h2>You want:</h2>\n\n<ul>\n<li>Bash builtin commands (i.e. portable)</li>\n<li>Check TTY</li>\n<li>Default answer</li>\n<li>Timeout</li>\n<li>Colored question</li>\n</ul>\n\n<h2>Snippet</h2>\n\n<pre><code>do_xxxx=y # In batch mode =&gt; Default is Yes\n[[ -t 0 ]] &amp;&amp; # If TTY =&gt; Prompt the question\nread -n 1 -p $'\\e[1;32m\nDo xxxx? (Y/n)\\e[0m ' do_xxxx # Store the answer in $do_xxxx\nif [[ $do_xxxx =~ ^(y|Y|)$ ]] # Do if 'y' or 'Y' or empty\nthen\n xxxx\nfi\n</code></pre>\n\n<h2>Explanations</h2>\n\n<ul>\n<li><code>[[ -t 0 ]] &amp;&amp; read ...</code> => Call command <code>read</code> if TTY</li>\n<li><code>read -n 1</code> => Wait for one character</li>\n<li><code>$'\\e[1;32m ... \\e[0m '</code> => Print in green<br>\n(green is fine because readable on both white/black backgrounds)</li>\n<li><code>[[ $do_xxxx =~ ^(y|Y|)$ ]]</code> => bash regex</li>\n</ul>\n\n<h2>Timeout => Default answer is No</h2>\n\n<pre><code>do_xxxx=y\n[[ -t 0 ]] &amp;&amp; { # Timeout 5 seconds (read -t 5)\nread -t 5 -n 1 -p $'\\e[1;32m\nDo xxxx? (Y/n)\\e[0m ' do_xxxx || # read 'fails' on timeout\ndo_xxxx=n ; } # Timeout =&gt; answer No\nif [[ $do_xxxx =~ ^(y|Y|)$ ]]\nthen\n xxxx\nfi\n</code></pre>\n" }, { "answer_id": 35783292, "author": "Apurv Nerlekar", "author_id": 1266952, "author_profile": "https://Stackoverflow.com/users/1266952", "pm_score": 5, "selected": false, "text": "<p>The easiest way to achieve this with the least number of lines is as follows:</p>\n\n<pre><code>read -p \"&lt;Your Friendly Message here&gt; : y/n/cancel\" CONDITION;\n\nif [ \"$CONDITION\" == \"y\" ]; then\n # do something here!\nfi\n</code></pre>\n\n<p>The <code>if</code> is just an example: it is up to you how to handle this variable.</p>\n" }, { "answer_id": 40483453, "author": "oOpSgEo", "author_id": 2875443, "author_profile": "https://Stackoverflow.com/users/2875443", "pm_score": 2, "selected": false, "text": "<p>I've used the <code>case</code> statement a couple of times in such a scenario, using the case statment is a good way to go about it. A <code>while</code> loop, that ecapsulates the <code>case</code> block, that utilizes a boolean condition can be implemented in order to hold even more control of the program, and fulfill many other requirements. After the all the conditions have been met, a <code>break</code> can be used which will pass control back to the main part of the program. Also, to meet other conditions, of course conditional statements can be added to accompany the control structures: <code>case</code> statement and possible <code>while</code> loop.</p>\n\n<p>Example of using a <code>case</code> statement to fulfill your request</p>\n\n<pre><code>#! /bin/sh \n\n# For potential users of BSD, or other systems who do not\n# have a bash binary located in /bin the script will be directed to\n# a bourne-shell, e.g. /bin/sh\n\n# NOTE: It would seem best for handling user entry errors or\n# exceptions, to put the decision required by the input \n# of the prompt in a case statement (case control structure), \n\necho Would you like us to perform the option: \"(Y|N)\"\n\nread inPut\n\ncase $inPut in\n # echoing a command encapsulated by \n # backticks (``) executes the command\n \"Y\") echo `Do something crazy`\n ;;\n # depending on the scenario, execute the other option\n # or leave as default\n \"N\") echo `execute another option`\n ;;\nesac\n\nexit\n</code></pre>\n" }, { "answer_id": 41034251, "author": "Yokai", "author_id": 5443139, "author_profile": "https://Stackoverflow.com/users/5443139", "pm_score": 3, "selected": false, "text": "<p>I noticed that no one posted an answer showing multi-line echo menu for such simple user input so here is my go at it:</p>\n\n<pre><code>#!/bin/bash\n\nfunction ask_user() { \n\necho -e \"\n#~~~~~~~~~~~~#\n| 1.) Yes |\n| 2.) No |\n| 3.) Quit |\n#~~~~~~~~~~~~#\\n\"\n\nread -e -p \"Select 1: \" choice\n\nif [ \"$choice\" == \"1\" ]; then\n\n do_something\n\nelif [ \"$choice\" == \"2\" ]; then\n\n do_something_else\n\nelif [ \"$choice\" == \"3\" ]; then\n\n clear &amp;&amp; exit 0\n\nelse\n\n echo \"Please select 1, 2, or 3.\" &amp;&amp; sleep 3\n clear &amp;&amp; ask_user\n\nfi\n}\n\nask_user\n</code></pre>\n\n<p>This method was posted in the hopes that someone may find it useful and time-saving.</p>\n" }, { "answer_id": 45110946, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 2, "selected": false, "text": "<h1>Yes / No / Cancel</h1>\n\n<h3>Function</h3>\n\n<pre><code>#!/usr/bin/env bash\n@confirm() {\n local message=\"$*\"\n local result=''\n\n echo -n \"&gt; $message (Yes/No/Cancel) \" &gt;&amp;2\n\n while [ -z \"$result\" ] ; do\n read -s -n 1 choice\n case \"$choice\" in\n y|Y ) result='Y' ;;\n n|N ) result='N' ;;\n c|C ) result='C' ;;\n esac\n done\n\n echo $result\n}\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>case $(@confirm 'Confirm?') in\n Y ) echo \"Yes\" ;;\n N ) echo \"No\" ;;\n C ) echo \"Cancel\" ;;\nesac\n</code></pre>\n\n<h1>Confirm with clean user input</h1>\n\n<h3>Function</h3>\n\n<pre><code>#!/usr/bin/env bash\n@confirm() {\n local message=\"$*\"\n local result=3\n\n echo -n \"&gt; $message (y/n) \" &gt;&amp;2\n\n while [[ $result -gt 1 ]] ; do\n read -s -n 1 choice\n case \"$choice\" in\n y|Y ) result=0 ;;\n n|N ) result=1 ;;\n esac\n done\n\n return $result\n}\n</code></pre>\n\n<h3>Usage</h3>\n\n<pre><code>if @confirm 'Confirm?' ; then\n echo \"Yes\"\nelse\n echo \"No\"\nfi\n</code></pre>\n" }, { "answer_id": 50431319, "author": "Mike Q", "author_id": 1618630, "author_profile": "https://Stackoverflow.com/users/1618630", "pm_score": 2, "selected": false, "text": "<p>In response to others: </p>\n\n<p>You don't need to specify case in BASH4 just use the ',,' to make a var lowercase. Also I strongly dislike putting code inside of the read block, get the result and deal with it outside of the read block IMO. Also include a 'q' for quit IMO. Lastly why type 'yes' just use -n1 and have the press y. </p>\n\n<p>Example: user can press y/n and also q to just quit.</p>\n\n<pre><code>ans=''\nwhile true; do\n read -p \"So is MikeQ the greatest or what (y/n/q) ?\" -n1 ans\n case ${ans,,} in\n y|n|q) break;;\n *) echo \"Answer y for yes / n for no or q for quit.\";;\n esac\ndone\n\necho -e \"\\nAnswer = $ans\"\n\nif [[ \"${ans,,}\" == \"q\" ]] ; then\n echo \"OK Quitting, we will assume that he is\"\n exit 0\nfi\n\nif [[ \"${ans,,}\" == \"y\" ]] ; then\n echo \"MikeQ is the greatest!!\"\nelse\n echo \"No? MikeQ is not the greatest?\"\nfi\n</code></pre>\n" }, { "answer_id": 51078339, "author": "Tom Hale", "author_id": 5353461, "author_profile": "https://Stackoverflow.com/users/5353461", "pm_score": 4, "selected": false, "text": "<h2>Single keypress only</h2>\n\n<p>Here's a longer, but reusable and modular approach:</p>\n\n<ul>\n<li>Returns <code>0</code>=yes and <code>1</code>=no</li>\n<li>No pressing enter required - just a single character</li>\n<li>Can press <kbd>enter</kbd> to accept the default choice</li>\n<li>Can disable default choice to force a selection</li>\n<li>Works for both <code>zsh</code> and <code>bash</code>.</li>\n</ul>\n\n<h3>Defaulting to \"no\" when pressing enter</h3>\n\n<p>Note that the <code>N</code> is capitalsed. Here enter is pressed, accepting the default: </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ confirm \"Show dangerous command\" &amp;&amp; echo \"rm *\"\nShow dangerous command [y/N]?\n</code></pre>\n\n<p>Also note, that <code>[y/N]?</code> was automatically appended.\nThe default \"no\" is accepted, so nothing is echoed.</p>\n\n<p><strong>Re-prompt until a valid response is given:</strong></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ confirm \"Show dangerous command\" &amp;&amp; echo \"rm *\"\nShow dangerous command [y/N]? X\nShow dangerous command [y/N]? y\nrm *\n</code></pre>\n\n<h3>Defaulting to \"yes\" when pressing enter</h3>\n\n<p>Note that the <code>Y</code> is capitalised:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ confirm_yes \"Show dangerous command\" &amp;&amp; echo \"rm *\"\nShow dangerous command [Y/n]?\nrm *\n</code></pre>\n\n<p>Above, I just pressed enter, so the command ran.</p>\n\n<h3>No default on <kbd>enter</kbd> - require <code>y</code> or <code>n</code></h3>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ get_yes_keypress \"Here you cannot press enter. Do you like this [y/n]? \"\nHere you cannot press enter. Do you like this [y/n]? k\nHere you cannot press enter. Do you like this [y/n]?\nHere you cannot press enter. Do you like this [y/n]? n\n$ echo $?\n1\n</code></pre>\n\n<p>Here, <code>1</code> or false was returned. Note that with this lower-level function you'll need to provide your own <code>[y/n]?</code> prompt.</p>\n\n<h3>Code</h3>\n\n<pre class=\"lang-sh prettyprint-override\"><code># Read a single char from /dev/tty, prompting with \"$*\"\n# Note: pressing enter will return a null string. Perhaps a version terminated with X and then remove it in caller?\n# See https://unix.stackexchange.com/a/367880/143394 for dealing with multi-byte, etc.\nfunction get_keypress {\n local REPLY IFS=\n &gt;/dev/tty printf '%s' \"$*\"\n [[ $ZSH_VERSION ]] &amp;&amp; read -rk1 # Use -u0 to read from STDIN\n # See https://unix.stackexchange.com/q/383197/143394 regarding '\\n' -&gt; ''\n [[ $BASH_VERSION ]] &amp;&amp; &lt;/dev/tty read -rn1\n printf '%s' \"$REPLY\"\n}\n\n# Get a y/n from the user, return yes=0, no=1 enter=$2\n# Prompt using $1.\n# If set, return $2 on pressing enter, useful for cancel or defualting\nfunction get_yes_keypress {\n local prompt=\"${1:-Are you sure [y/n]? }\"\n local enter_return=$2\n local REPLY\n # [[ ! $prompt ]] &amp;&amp; prompt=\"[y/n]? \"\n while REPLY=$(get_keypress \"$prompt\"); do\n [[ $REPLY ]] &amp;&amp; printf '\\n' # $REPLY blank if user presses enter\n case \"$REPLY\" in\n Y|y) return 0;;\n N|n) return 1;;\n '') [[ $enter_return ]] &amp;&amp; return \"$enter_return\"\n esac\n done\n}\n\n# Credit: http://unix.stackexchange.com/a/14444/143394\n# Prompt to confirm, defaulting to NO on &lt;enter&gt;\n# Usage: confirm \"Dangerous. Are you sure?\" &amp;&amp; rm *\nfunction confirm {\n local prompt=\"${*:-Are you sure} [y/N]? \"\n get_yes_keypress \"$prompt\" 1\n} \n\n# Prompt to confirm, defaulting to YES on &lt;enter&gt;\nfunction confirm_yes {\n local prompt=\"${*:-Are you sure} [Y/n]? \"\n get_yes_keypress \"$prompt\" 0\n}\n</code></pre>\n" }, { "answer_id": 53746668, "author": "Walter A", "author_id": 3220113, "author_profile": "https://Stackoverflow.com/users/3220113", "pm_score": 4, "selected": false, "text": "<p>You can use the default <code>REPLY</code> on a <code>read</code>, convert to lowercase and compare to a set of variables with an expression.<br>\nThe script also supports <code>ja</code>/<code>si</code>/<code>oui</code></p>\n\n<pre><code>read -rp \"Do you want a demo? [y/n/c] \"\n\n[[ ${REPLY,,} =~ ^(c|cancel)$ ]] &amp;&amp; { echo \"Selected Cancel\"; exit 1; }\n\nif [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then\n echo \"Positive\"\nfi\n</code></pre>\n" }, { "answer_id": 57739142, "author": "Léa Gris", "author_id": 7939871, "author_profile": "https://Stackoverflow.com/users/7939871", "pm_score": 4, "selected": false, "text": "<p>It is possible to handle a locale-aware \"Yes / No choice\" in a POSIX shell; by using the entries of the <code>LC_MESSAGES</code> locale category, witch provides ready-made RegEx patterns to match an input, and strings for localized Yes No.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env sh\n\n# Getting LC_MESSAGES values into variables\n# shellcheck disable=SC2046 # Intended IFS splitting\nIFS='\n' set -- $(locale LC_MESSAGES)\n\nyesexpr=\"$1\"\nnoexpr=\"$2\"\nyesstr=\"$3\"\nnostr=\"$4\"\nmessages_codeset=\"$5\" # unused here, but kept as documentation\n\n# Display Yes / No ? prompt into locale\necho \"$yesstr / $nostr ?\"\n\n# Read answer\nread -r yn\n\n# Test answer\ncase \"$yn\" in\n# match only work with the character class from the expression\n ${yesexpr##^}) echo \"answer $yesstr\" ;;\n ${noexpr##^}) echo \"answer $nostr\" ;;\nesac\n</code></pre>\n\n<p>EDIT:\nAs <a href=\"/users/1046421/urhixidur\">@Urhixidur</a> mentioned in <a href=\"/questions/226703/how-do-i-prompt-for-yes-no-cancel-input-in-a-linux-shell-script/57739142?noredirect=1#comment105493248_57739142\">his comment</a>:</p>\n\n<blockquote>\n <p>Unfortunately, POSIX only specifies the first two (yesexpr and noexpr). On Ubuntu 16, yesstr and nostr are empty.</p>\n</blockquote>\n\n<p>See: <a href=\"https://www.ee.ryerson.ca/~courses/ele709/susv4/xrat/V4_xbd_chap07.html#tag_21_07_03_06\" rel=\"noreferrer\">https://www.ee.ryerson.ca/~courses/ele709/susv4/xrat/V4_xbd_chap07.html#tag_21_07_03_06</a></p>\n\n<blockquote>\n <h3>LC_MESSAGES</h3>\n \n <p>The <strong><code>yesstr</code></strong> and <strong><code>nostr</code></strong> locale keywords and the <code>YESSTR</code> and <code>NOSTR</code> langinfo items were formerly used to match user affirmative and negative responses. In POSIX.1-2008, the <strong><code>yesexpr</code></strong>, <strong><code>noexpr</code></strong>, <code>YESEXPR</code>, and <code>NOEXPR</code> extended regular expressions have replaced them. Applications should use the general locale-based messaging facilities to issue prompting messages which include sample desired responses.</p>\n</blockquote>\n\n<p>Alternatively using locales the Bash way:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env bash\n\nIFS=$'\\n' read -r -d '' yesexpr noexpr _ &lt; &lt;(locale LC_MESSAGES)\n\nprintf -v yes_or_no_regex \"(%s)|(%s)\" \"$yesexpr\" \"$noexpr\"\n\nprintf -v prompt $\"Please answer Yes (%s) or No (%s): \" \"$yesexpr\" \"$noexpr\"\n\ndeclare -- answer=;\n\nuntil [[ \"$answer\" =~ $yes_or_no_regex ]]; do\n read -rp \"$prompt\" answer\ndone\n\nif [[ -n \"${BASH_REMATCH[1]}\" ]]; then\n echo $\"You answered: Yes\"\nelse\n echo $\"No, was your answer.\"\nfi\n</code></pre>\n\n<p>The answer is matched using locale environment's provided regexps.</p>\n\n<p>To translate the remaining messages, use <code>bash --dump-po-strings scriptname</code> to output the po strings for localization:</p>\n\n<pre><code>#: scriptname:8\nmsgid \"Please answer Yes (%s) or No (%s): \"\nmsgstr \"\"\n#: scriptname:17\nmsgid \"You answered: Yes\"\nmsgstr \"\"\n#: scriptname:19\nmsgid \"No, was your answer.\"\nmsgstr \"\"\n</code></pre>\n" }, { "answer_id": 61070975, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": 2, "selected": false, "text": "<p>This is what I usually need in a script/function:</p>\n\n<ul>\n<li>default answer is Yes, if you hit ENTER</li>\n<li>accept also z (in case you mix up you are on QWERTZ Layout)</li>\n<li>accept other lanyuages (\"ja\", \"Oui\", ...)</li>\n<li>handle the right exit in case you are inside a function</li>\n</ul>\n\n<pre><code>while true; do\n read -p \"Continue [Y/n]? \" -n 1 -r -e yn\n case \"${yn:-Y}\" in\n [YyZzOoJj]* ) echo; break ;;\n [Nn]* ) [[ \"$0\" = \"$BASH_SOURCE\" ]] &amp;&amp; exit 1 || return 1 ;; # handle exits from shell or function but don't exit interactive shell\n * ) echo \"Please answer yes or no.\";;\n esac\ndone\necho \"and off we go!\"\n</code></pre>\n" }, { "answer_id": 65118202, "author": "Roland", "author_id": 1845672, "author_profile": "https://Stackoverflow.com/users/1845672", "pm_score": 2, "selected": false, "text": "<p>The absolute most simple solution is this one-liner without clever tricks:</p>\n<pre><code>read -p &quot;press enter ...&quot; y\n</code></pre>\n<p>It reminds of the classic DOS <code>Hit any key to continue</code>, except that it waits for the Enter key, not just any key.</p>\n<p>True, this does not offer you three options for Yes No Cancel, but it is useful where you accept control-C as No resp. Cancel in simple scripts like, e.g.:</p>\n<pre><code>#!/bin/sh\necho Backup this project\nread -p &quot;press enter ...&quot; y\nrsync -tavz . /media/hard_to_remember_path/backup/projects/yourproject/\n</code></pre>\n<p>because you don't like to need to remember ugly commands and paths, but neither scripts that run too fast, without giving you a chance to stop before you decide it is not the script you intended to run.</p>\n" }, { "answer_id": 66420668, "author": "Samir Kape", "author_id": 8312897, "author_profile": "https://Stackoverflow.com/users/8312897", "pm_score": 3, "selected": false, "text": "<p>Check this</p>\n<pre><code>read -p &quot;Continue? (y/n): &quot; confirm &amp;&amp; [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1\n</code></pre>\n" }, { "answer_id": 69495671, "author": "ish-west", "author_id": 5272636, "author_profile": "https://Stackoverflow.com/users/5272636", "pm_score": 1, "selected": false, "text": "<p>I've made this small script for yes/no questions: <a href=\"https://github.com/optimistiCli/getans\" rel=\"nofollow noreferrer\">https://github.com/optimistiCli/getans</a></p>\n<p>Example:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\nif ! getans.sh 'Shall we proceed?' y ; then\n echo &quot;User said “NO”&quot;\n exit 1\nfi\n\necho &quot;User said “YES”&quot;\n# do something usefull\nexit 0\n</code></pre>\n<p>Direct link:\n<a href=\"https://github.com/optimistiCli/getans/raw/main/getans.sh\" rel=\"nofollow noreferrer\">https://github.com/optimistiCli/getans/raw/main/getans.sh</a></p>\n" }, { "answer_id": 69672795, "author": "Ctrl-C", "author_id": 731634, "author_profile": "https://Stackoverflow.com/users/731634", "pm_score": 3, "selected": false, "text": "<p>One-liner:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>read -p &quot;Continue? [Enter] → Yes, [Ctrl]+[C] → No.&quot;\n</code></pre>\n<p>This assumes that &quot;No&quot; and &quot;Cancel&quot; have the same outcome, so no reason to treat them differently.</p>\n" }, { "answer_id": 71503750, "author": "Diego Torres Milano", "author_id": 236465, "author_profile": "https://Stackoverflow.com/users/236465", "pm_score": 1, "selected": false, "text": "<p>A one-liner <code>python</code> alternative using <a href=\"https://github.com/CITGuru/PyInquirer\" rel=\"nofollow noreferrer\">PyInquirer</a></p>\n<pre><code>python3 -c 'import PyInquirer; print(PyInquirer.prompt([{&quot;type&quot;:&quot;confirm&quot;, &quot;message&quot;:&quot;Do you want to continue?&quot;, &quot;name&quot;:&quot;r&quot;}]).get(&quot;r&quot;))'\n</code></pre>\n<p>which supports yes/no/cancel (intr, CTRL+C).</p>\n<p><a href=\"https://i.stack.imgur.com/eDGP1.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eDGP1.gif\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 72237677, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 1, "selected": false, "text": "<p>You can write a function to test:</p>\n<pre><code>confirm() {\n local ans IFS=;\n while read -rp &quot;$1&quot; -n1 ans;\n do printf '\\n';\n case $ans in [Yy]) return 0;;\n [Nn]) return 1;;\n esac;\n done;\n}; ## Usage: if confirm &quot;Are you sure? &quot;; then ...\n\nif confirm &quot;Does everything look ok...reboot now? [Y/n]&quot;; then\n echo &quot;rebooting...&quot;\n sleep 5\n reboot\nfi\n</code></pre>\n" }, { "answer_id": 72692403, "author": "Erik Pukinskis", "author_id": 778946, "author_profile": "https://Stackoverflow.com/users/778946", "pm_score": 3, "selected": false, "text": "<p>Lots of good answers to this question, but from what I can see none of them are my ideal, which would:</p>\n<ol>\n<li>Be simple, just a couple lines of shell</li>\n<li>Work with a single y/n keypress (no need to press enter)</li>\n<li>Default to yes if you just hit enter</li>\n<li>Work with an uppercase Y/N as well</li>\n</ol>\n<p>Here's my version which does has those properties:</p>\n<pre><code>read -n1 -p &quot;Continue? (Y/n) &quot; confirm\n\nif ! echo $confirm | grep '^[Yy]\\?$'; then\n exit 1\nfi\n</code></pre>\n<p>You can modify that conditional to only run on &quot;yes&quot; (just remove the <code>!</code> in the <code>if</code> statement) or add an <code>else</code> if you want to run code on both branches.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084/" ]
I want to pause input in a shell script, and prompt the user for choices. The standard `Yes`, `No`, or `Cancel` type question. How do I accomplish this in a typical bash prompt?
The simplest and most widely available method to get user input at a shell prompt is the [`read`](https://www.gnu.org/software/bash/manual/bashref.html#index-read) command. The best way to illustrate its use is a simple demonstration: ``` while true; do read -p "Do you wish to install this program? " yn case $yn in [Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo "Please answer yes or no.";; esac done ``` Another method, [pointed out](https://stackoverflow.com/a/226946/9084) by [Steven Huwig](https://stackoverflow.com/users/28604/steven-huwig), is Bash's [`select`](https://www.gnu.org/software/bash/manual/bashref.html#index-select) command. Here is the same example using `select`: ``` echo "Do you wish to install this program?" select yn in "Yes" "No"; do case $yn in Yes ) make install; break;; No ) exit;; esac done ``` With `select` you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a `while true` loop to retry if they give invalid input. Also, [Léa Gris](https://stackoverflow.com/users/7939871/l%c3%a9a-gris) demonstrated a way to make the request language agnostic in [her answer](https://stackoverflow.com/a/57739142/9084). Adapting my first example to better serve multiple languages might look like this: ``` set -- $(locale LC_MESSAGES) yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4" while true; do read -p "Install (${yesword} / ${noword})? " yn if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi if [[ "$yn" =~ $noexpr ]]; then exit; fi echo "Answer ${yesword} / ${noword}." done ``` Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases. Finally, please check out the [excellent answer](https://stackoverflow.com/a/27875395/9084) by [F. Hauri](https://stackoverflow.com/users/1765658/f-hauri).
226,717
<p>When you are monitoring the TFS build from Visual Studio (2008 or 2005), you can see where it is up to.</p> <p>The issue is that I have some Post-Build custom steps I would like the developer to be able to see directly throught the UI. Those steps take some times and we can also get a "timing" of the build step.</p> <p>Any idea how to have it displayed?</p>
[ { "answer_id": 227063, "author": "Martin Woodward", "author_id": 6438, "author_profile": "https://Stackoverflow.com/users/6438", "pm_score": 4, "selected": true, "text": "<p>This is the pattern that I normally use for adding steps to the build report in TFS 2008. (See <a href=\"http://code.msdn.microsoft.com/buildwallboard/\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/buildwallboard/</a> for the full example that I usually use in my Team Build talks)</p>\n\n<p>Basically, the magic is that there is a custom task provided for you in TFS2008 called \"BuildStep\". Here is the section where I generate and MSI installer and build the appropriate build steps in the report:</p>\n\n<pre><code> &lt;Target Name=\"PackageBinaries\"&gt;\n\n &lt;!-- create the build step --&gt;\n &lt;BuildStep TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Message=\"Creating Installer\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \" &gt;\n &lt;Output TaskParameter=\"Id\"\n PropertyName=\"InstallerStepId\" /&gt;\n &lt;/BuildStep&gt;\n\n &lt;!-- Create the MSI file using WiX --&gt;\n &lt;MSBuild Projects=\"$(SolutionRoot)\\SetupProject\\wallboard.wixproj\"\n Properties=\"BinariesSource=$(OutDir);PublishDir=$(BinariesRoot);Configuration=%(ConfigurationToBuild.FlavourToBuild)\" &gt;\n &lt;/MSBuild&gt;\n\n &lt;!-- If we sucessfully built the installer, tell TFS --&gt;\n &lt;BuildStep TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(InstallerStepId)\"\n Status=\"Succeeded\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \" /&gt;\n\n &lt;!-- Note that the condition above means that we do not talk to TFS when doing a Desktop Build --&gt;\n\n &lt;!-- If we error during this step, then tell TFS we failed--&gt;\n &lt;OnError ExecuteTargets=\"MarkInstallerFailed\" /&gt;\n &lt;/Target&gt;\n\n &lt;Target Name=\"MarkInstallerFailed\"&gt;\n &lt;!-- Called by the PackageBinaries method if creating the installer fails --&gt;\n &lt;BuildStep TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n Id=\"$(InstallerStepId)\"\n Status=\"Failed\"\n Condition=\" '$(IsDesktopBuild)' != 'true' \" /&gt;\n &lt;/Target&gt;\n</code></pre>\n\n<p>So initially, I create the build step and save the Id of the step in a propery called InstallerStepId. After I have performed my task, I set the status of that step to Succeeded. If any errors occur during the step then I set the status of that step to Failed.</p>\n\n<p>Good luck,</p>\n\n<p>Martin.</p>\n" }, { "answer_id": 8435110, "author": "Polyfun", "author_id": 181315, "author_profile": "https://Stackoverflow.com/users/181315", "pm_score": 0, "selected": false, "text": "<p>Note that in @Martin Woodward's great example, PackageBinaries is one of the existing <a href=\"http://msdn.microsoft.com/en-us/library/aa337604%28v=VS.90%29.aspx\" rel=\"nofollow\">TFS build targets</a>. If you want to use your own targets, you can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms229474%28v=VS.90%29.aspx\" rel=\"nofollow\">CallTarget</a> task to call them from one of the known targets, e.g.,</p>\n\n<pre><code>&lt;Target Name=\"AfterDropBuild\"&gt;\n &lt;CallTarget Targets=\"CreateDelivery\"/&gt;\n &lt;CallTarget Targets=\"CreateInventory\"/&gt;\n&lt;/Target&gt;\n</code></pre>\n\n<p>Then in your targets (e.g., CreateDelivery) use the BuildStep task as per Martin's example.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
When you are monitoring the TFS build from Visual Studio (2008 or 2005), you can see where it is up to. The issue is that I have some Post-Build custom steps I would like the developer to be able to see directly throught the UI. Those steps take some times and we can also get a "timing" of the build step. Any idea how to have it displayed?
This is the pattern that I normally use for adding steps to the build report in TFS 2008. (See <http://code.msdn.microsoft.com/buildwallboard/> for the full example that I usually use in my Team Build talks) Basically, the magic is that there is a custom task provided for you in TFS2008 called "BuildStep". Here is the section where I generate and MSI installer and build the appropriate build steps in the report: ``` <Target Name="PackageBinaries"> <!-- create the build step --> <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Message="Creating Installer" Condition=" '$(IsDesktopBuild)' != 'true' " > <Output TaskParameter="Id" PropertyName="InstallerStepId" /> </BuildStep> <!-- Create the MSI file using WiX --> <MSBuild Projects="$(SolutionRoot)\SetupProject\wallboard.wixproj" Properties="BinariesSource=$(OutDir);PublishDir=$(BinariesRoot);Configuration=%(ConfigurationToBuild.FlavourToBuild)" > </MSBuild> <!-- If we sucessfully built the installer, tell TFS --> <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(InstallerStepId)" Status="Succeeded" Condition=" '$(IsDesktopBuild)' != 'true' " /> <!-- Note that the condition above means that we do not talk to TFS when doing a Desktop Build --> <!-- If we error during this step, then tell TFS we failed--> <OnError ExecuteTargets="MarkInstallerFailed" /> </Target> <Target Name="MarkInstallerFailed"> <!-- Called by the PackageBinaries method if creating the installer fails --> <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(InstallerStepId)" Status="Failed" Condition=" '$(IsDesktopBuild)' != 'true' " /> </Target> ``` So initially, I create the build step and save the Id of the step in a propery called InstallerStepId. After I have performed my task, I set the status of that step to Succeeded. If any errors occur during the step then I set the status of that step to Failed. Good luck, Martin.
226,721
<p>I have a struts2 application with a single page that may show one of a number of values stored in a database. The application is for a school with many departments and each department has many programs. The department page is accessed using a url like this</p> <pre><code>department.action?id=2 </code></pre> <p>and the DepartmentAction will load the Department with id = 2 for display. All this is fine if the user is just browsing around the site but it gets uncomfortable if I want to provide a link to say the Engineering department in the newspapers. The link will have to be www.myschooldomain.com/department.action?id=2. I see a number of problems with this.</p> <p>First, it is not user friendly. Second, it is prone to be broken because the departments are dynamically maintained and the id for a department could change without warning making the link unstable.</p> <p>I would prefer to print a url like this: www.myschooldomain.com/department/engineering and have that somehow go to department.action?id=2.</p> <p>My thoughts so far: create an action that will parse the url for the department name at the end then look it up by name. Maybe I could add a friendlyurl field to the database for each department.</p> <p>But the question is: Is there a better way to do this in struts2?</p> <p>Thanks.</p> <p><strong>Update (May 2009):</strong> I just happened to stumble back over this question and thought that I would say what I did to solve it. </p> <p>I created a new package in the struts.xml called departments. In this package there is only one action mapped to *. So it catches all requests to mydomain.com/departments/anything.html.</p> <p>In the action class I simply parse the url and look for the part between departments/ and .html and that is the name of the department so I can do a lookup in the database for it. This has been working fine for almost 5 months now and I have implemented it for other areas of the site.</p>
[ { "answer_id": 226827, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": true, "text": "<p>This is normally done by mapping a servlet to, in your case '/department', and then using the <a href=\"http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getPathInfo()\" rel=\"nofollow noreferrer\">path</a> information (e.g., '/engineering') within the servlet to determine the ID. </p>\n\n<p>Since the Struts2 dispatcher doesn't implement this behavior, it might be simplest to write your own servlet. This servlet would be configured with a map of valid \"friendly\" names to the unfriendly numeric identifiers. This could be an actual <code>Map</code> or it could be done with a database finder method. </p>\n\n<p>The result of <code>getPathInfo()</code> would be used to look up the ID, and the request would be <a href=\"http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)\" rel=\"nofollow noreferrer\">forwarded</a> to the department.action. Handle the <code>null</code> case too, which means the user is trying to browse the <code>/departments/</code> directory.</p>\n" }, { "answer_id": 729846, "author": "Pool", "author_id": 2352432, "author_profile": "https://Stackoverflow.com/users/2352432", "pm_score": 2, "selected": false, "text": "<p>You could use the <a href=\"http://tuckey.org/urlrewrite/\" rel=\"nofollow noreferrer\">URL Rewrite filter</a></p>\n\n<p>This avoids the need for any additional servlet or Java code but requires XML descriptors.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27439/" ]
I have a struts2 application with a single page that may show one of a number of values stored in a database. The application is for a school with many departments and each department has many programs. The department page is accessed using a url like this ``` department.action?id=2 ``` and the DepartmentAction will load the Department with id = 2 for display. All this is fine if the user is just browsing around the site but it gets uncomfortable if I want to provide a link to say the Engineering department in the newspapers. The link will have to be www.myschooldomain.com/department.action?id=2. I see a number of problems with this. First, it is not user friendly. Second, it is prone to be broken because the departments are dynamically maintained and the id for a department could change without warning making the link unstable. I would prefer to print a url like this: www.myschooldomain.com/department/engineering and have that somehow go to department.action?id=2. My thoughts so far: create an action that will parse the url for the department name at the end then look it up by name. Maybe I could add a friendlyurl field to the database for each department. But the question is: Is there a better way to do this in struts2? Thanks. **Update (May 2009):** I just happened to stumble back over this question and thought that I would say what I did to solve it. I created a new package in the struts.xml called departments. In this package there is only one action mapped to \*. So it catches all requests to mydomain.com/departments/anything.html. In the action class I simply parse the url and look for the part between departments/ and .html and that is the name of the department so I can do a lookup in the database for it. This has been working fine for almost 5 months now and I have implemented it for other areas of the site.
This is normally done by mapping a servlet to, in your case '/department', and then using the [path](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getPathInfo()) information (e.g., '/engineering') within the servlet to determine the ID. Since the Struts2 dispatcher doesn't implement this behavior, it might be simplest to write your own servlet. This servlet would be configured with a map of valid "friendly" names to the unfriendly numeric identifiers. This could be an actual `Map` or it could be done with a database finder method. The result of `getPathInfo()` would be used to look up the ID, and the request would be [forwarded](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)) to the department.action. Handle the `null` case too, which means the user is trying to browse the `/departments/` directory.
226,743
<p>I am using the webbrowser control in visual studio. I think it is a wrapper around internet explorer. Anyway all is going well I am using it in edit mode however I can't get he document's keydown event to fire (in order to catch ctrl+v) anyone had similar problems with it?</p> <p>Anyone have a solution?</p>
[ { "answer_id": 226789, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "<p>You should override a \"WndProc()\" method in derived class from WebBrowser control or in form, which contains a webbrowser. Or you can catch the keys with custom message filter ( Application.AddMessageFilter ). With this way you can also filter a mouse actions.</p>\n\n<p>I had same problems years ago, but I don't remember which way i used.</p>\n" }, { "answer_id": 226794, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 3, "selected": true, "text": "<p>Indeed the webbrowser control is just a wrapper of the IE browser control.\nIs your problem that the controls PreviewKeyDown not working? Seems to be working for me as long as the control has focus.</p>\n\n<pre><code> webBrowser1.PreviewKeyDown += new PreviewKeyDownEventHandler(webBrowser1_PreviewKeyDown); \n\n....\n\n private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {\n Console.WriteLine(e.KeyCode.ToString() + \" \" + e.Modifiers.ToString());\n if (e.Modifiers == Keys.Control &amp;&amp; e.KeyCode == Keys.V) {\n MessageBox.Show(\"ctrl-v pressed\");\n }\n }\n</code></pre>\n\n<p>but perhaps I am not completely understanding?</p>\n" }, { "answer_id": 226885, "author": "Matt V", "author_id": 30456, "author_profile": "https://Stackoverflow.com/users/30456", "pm_score": 1, "selected": false, "text": "<p>You mentioned the KeyDown event of the 'document'. If you are referring to the WebBrowser control's Document property (type HtmlDocument) it only has events for MouseUp, MouseDown, etc but not keyboard events. You want to register your event handler with the WebBrowser control's PreviewKeyDown delegate. You may also want to set the value of the WebBrowser control's WebBrowserShortcutsEnabled property to false if you don't want standard Internet Explorer shortcuts to have their usual effect. You should also make sure that the WebBrowser control is in focus by manually calling its Focus() method and setting the TabStop property of other controls on the form to false. If this is not possible because you have other controls on the form that need to accept focus, you also might want to add an event handler for the KeyDown event of the Form itself.</p>\n" }, { "answer_id": 227868, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://support.microsoft.com/kb/320584\" rel=\"nofollow noreferrer\">How to trap keystrokes in controls by using Visual C#</a></p>\n\n<p>e.g.</p>\n\n<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData) \n{ \n const int WM_KEYDOWN = 0x100; \n const int WM_SYSKEYDOWN = 0x104; \n\n if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN)) \n { \n switch(keyData) \n { \n case Keys.Down: \n this.Parent.Text=\"Down Arrow Captured\"; \n break; \n\n...\n\n } \n } \n\n return base.ProcessCmdKey(ref msg,keyData); \n} \n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
I am using the webbrowser control in visual studio. I think it is a wrapper around internet explorer. Anyway all is going well I am using it in edit mode however I can't get he document's keydown event to fire (in order to catch ctrl+v) anyone had similar problems with it? Anyone have a solution?
Indeed the webbrowser control is just a wrapper of the IE browser control. Is your problem that the controls PreviewKeyDown not working? Seems to be working for me as long as the control has focus. ``` webBrowser1.PreviewKeyDown += new PreviewKeyDownEventHandler(webBrowser1_PreviewKeyDown); .... private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { Console.WriteLine(e.KeyCode.ToString() + " " + e.Modifiers.ToString()); if (e.Modifiers == Keys.Control && e.KeyCode == Keys.V) { MessageBox.Show("ctrl-v pressed"); } } ``` but perhaps I am not completely understanding?
226,785
<p>We have a netbeans project that has an xsd that we use to create a wsdl and we use the wsdl to create a webservice. Since we are using types in our xsd jaxb is used and one of our webservice methods looks like this: </p> <pre><code>public void someMethod( org.netbeans.xml.schema.line.Line x )... </code></pre> <p>So that leaves us a problem with subversion since the Line objects are generated by netbeans. So we want to do is either tell netbeans to place the files inside of the project? Or tell netbeans that we will generate the jaxb code and that they should use our classes when the webservice calls are processed? How can we accomplish one of these, what are some other alternatives?</p>
[ { "answer_id": 226795, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "<p>You can build one with the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx\" rel=\"noreferrer\"><code>HttpListener</code></a> class to listen for incoming requests and the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx\" rel=\"noreferrer\"><code>HttpWebRequest</code></a> class to relay the requests.</p>\n" }, { "answer_id": 259132, "author": "Stephen Caldwell", "author_id": 33437, "author_profile": "https://Stackoverflow.com/users/33437", "pm_score": 2, "selected": false, "text": "<p>The browser is connected to the proxy so the data that the proxy gets from the web server is just sent via the same connection that the browser initiated to the proxy.</p>\n" }, { "answer_id": 806378, "author": "Vadym Stetsiak", "author_id": 6952, "author_profile": "https://Stackoverflow.com/users/6952", "pm_score": 4, "selected": false, "text": "<p>Proxy can work in the following way.</p>\n\n<p>Step1, configure client to use proxyHost:proxyPort.</p>\n\n<p>Proxy is a TCP server that is listening on proxyHost:proxyPort.\nBrowser opens connection with Proxy and sends Http request. \nProxy parses this request and tries to detect \"Host\" header. This header will tell Proxy where to open connection. </p>\n\n<p>Step 2: Proxy opens connection to the address specified in the \"Host\" header. Then it sends HTTP request to that remote server. Reads response.</p>\n\n<p>Step 3: After response is read from remote HTTP server, Proxy sends the response through an earlier opened TCP connection with browser.</p>\n\n<p>Schematically it will look like this:</p>\n\n<pre><code>Browser Proxy HTTP server\n Open TCP connection \n Send HTTP request -----------&gt; \n Read HTTP header\n detect Host header\n Send request to HTTP -----------&gt;\n Server\n &lt;-----------\n Read response and send\n &lt;----------- it back to the browser\nRender content\n</code></pre>\n" }, { "answer_id": 806406, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 7, "selected": false, "text": "<p>I wouldn't use HttpListener or something like that, in that way you'll come across so many issues. </p>\n\n<p>Most importantly it'll be a huge pain to support:</p>\n\n<ul>\n<li>Proxy Keep-Alives</li>\n<li>SSL won't work (in a correct way, you'll get popups)</li>\n<li>.NET libraries strictly follows RFCs which causes some requests to fail (even though IE, FF and any other browser in the world will work.)</li>\n</ul>\n\n<p>What you need to do is:</p>\n\n<ul>\n<li>Listen a TCP port </li>\n<li>Parse the browser request </li>\n<li>Extract Host connect to that host in TCP level</li>\n<li>Forward everything back and forth unless you want to add custom headers etc.</li>\n</ul>\n\n<p>I wrote 2 different HTTP proxies in .NET with different requirements and I can tell you that this is the best way to do it.</p>\n\n<p>Mentalis doing this, but their code is \"delegate spaghetti\", worse than GoTo :)</p>\n" }, { "answer_id": 3670396, "author": "Alireza Rinan", "author_id": 442656, "author_profile": "https://Stackoverflow.com/users/442656", "pm_score": 3, "selected": false, "text": "<p>Agree to dr evil\nif you use HTTPListener you will have many problems, you have to parse requests and will be engaged to headers and ...</p>\n\n<ol>\n<li>Use tcp listener to listen to browser requests<br /></li>\n<li>parse only the first line of the request and get the host domain and port to connect</li>\n<li>send the exact raw request to the found host on the first line of browser request</li>\n<li>receive the data from the target site(I have problem in this section)</li>\n<li>send the exact data received from the host to the browser</li>\n</ol>\n\n<p>you see you dont need to even know what is in the browser request and parse it, only get the target site address from the first line\nfirst line usually likes this\nGET <a href=\"http://google.com\" rel=\"nofollow noreferrer\">http://google.com</a> HTTP1.1\nor\nCONNECT facebook.com:443 (this is for ssl requests)</p>\n" }, { "answer_id": 11053588, "author": "C.M.", "author_id": 1429439, "author_profile": "https://Stackoverflow.com/users/1429439", "pm_score": 3, "selected": false, "text": "<p>Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.</p>\n\n<p>If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.</p>\n\n<p>If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.</p>\n" }, { "answer_id": 11123208, "author": "Dean North", "author_id": 361464, "author_profile": "https://Stackoverflow.com/users/361464", "pm_score": 4, "selected": false, "text": "<p>If you are just looking to intercept the traffic, you could use the fiddler core to create a proxy...</p>\n\n<p><a href=\"http://fiddler.wikidot.com/fiddlercore\" rel=\"noreferrer\">http://fiddler.wikidot.com/fiddlercore</a></p>\n\n<p>run fiddler first with the UI to see what it does, it is a proxy that allows you to debug the http/https traffic. It is written in c# and has a core which you can build into your own applications.</p>\n\n<p>Keep in mind FiddlerCore is not free for commercial applications.</p>\n" }, { "answer_id": 27791072, "author": "Jehonathan Thomas", "author_id": 1215371, "author_profile": "https://Stackoverflow.com/users/1215371", "pm_score": 5, "selected": false, "text": "<p>I have recently written a light weight proxy in c# .net using <a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener%28v=vs.110%29.aspx\" rel=\"noreferrer\">TcpListener</a> and <a href=\"https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx\" rel=\"noreferrer\">TcpClient</a>.</p>\n\n<p><a href=\"https://github.com/titanium007/Titanium-Web-Proxy\" rel=\"noreferrer\">https://github.com/titanium007/Titanium-Web-Proxy</a></p>\n\n<p>It supports secure HTTP the correct way, client machine needs to trust root certificate used by the proxy. Also supports WebSockets relay. All features of HTTP 1.1 are supported except pipelining. Pipelining is not used by most modern browsers anyway. Also supports windows authentication (plain, digest).</p>\n\n<p>You can hook up your application by referencing the project and then see and modify all traffic. (Request and response).</p>\n\n<p>As far as performance, I have tested it on my machine and works without any noticeable delay.</p>\n" }, { "answer_id": 28024774, "author": "Jochen van Wylick", "author_id": 896697, "author_profile": "https://Stackoverflow.com/users/896697", "pm_score": 3, "selected": false, "text": "<p>Things have become really easy with OWIN and WebAPI. In my search for a C# Proxy server, I also came across this post <a href=\"http://blog.kloud.com.au/2013/11/24/do-it-yourself-web-api-proxy/\">http://blog.kloud.com.au/2013/11/24/do-it-yourself-web-api-proxy/</a> . This will be the road I'm taking.</p>\n" }, { "answer_id": 58039128, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 2, "selected": false, "text": "<p>For what it's worth, here is a C# sample async implementation based on <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netframework-4.8\" rel=\"nofollow noreferrer\">HttpListener</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8\" rel=\"nofollow noreferrer\">HttpClient</a> (I use it to be able to connect Chrome in Android devices to IIS Express, that's the only way I found...).</p>\n\n<p>And If you need HTTPS support, it shouldn't require more code, just certificate configuration: <a href=\"https://stackoverflow.com/questions/11403333/httplistener-with-https-support\">Httplistener with HTTPS support</a></p>\n\n<pre><code>// define http://localhost:5000 and http://127.0.0.1:5000/ to be proxies for http://localhost:53068\nusing (var server = new ProxyServer(\"http://localhost:53068\", \"http://localhost:5000/\", \"http://127.0.0.1:5000/\"))\n{\n server.Start();\n Console.WriteLine(\"Press ESC to stop server.\");\n while (true)\n {\n var key = Console.ReadKey(true);\n if (key.Key == ConsoleKey.Escape)\n break;\n }\n server.Stop();\n}\n\n....\n\npublic class ProxyServer : IDisposable\n{\n private readonly HttpListener _listener;\n private readonly int _targetPort;\n private readonly string _targetHost;\n private static readonly HttpClient _client = new HttpClient();\n\n public ProxyServer(string targetUrl, params string[] prefixes)\n : this(new Uri(targetUrl), prefixes)\n {\n }\n\n public ProxyServer(Uri targetUrl, params string[] prefixes)\n {\n if (targetUrl == null)\n throw new ArgumentNullException(nameof(targetUrl));\n\n if (prefixes == null)\n throw new ArgumentNullException(nameof(prefixes));\n\n if (prefixes.Length == 0)\n throw new ArgumentException(null, nameof(prefixes));\n\n RewriteTargetInText = true;\n RewriteHost = true;\n RewriteReferer = true;\n TargetUrl = targetUrl;\n _targetHost = targetUrl.Host;\n _targetPort = targetUrl.Port;\n Prefixes = prefixes;\n\n _listener = new HttpListener();\n foreach (var prefix in prefixes)\n {\n _listener.Prefixes.Add(prefix);\n }\n }\n\n public Uri TargetUrl { get; }\n public string[] Prefixes { get; }\n public bool RewriteTargetInText { get; set; }\n public bool RewriteHost { get; set; }\n public bool RewriteReferer { get; set; } // this can have performance impact...\n\n public void Start()\n {\n _listener.Start();\n _listener.BeginGetContext(ProcessRequest, null);\n }\n\n private async void ProcessRequest(IAsyncResult result)\n {\n if (!_listener.IsListening)\n return;\n\n var ctx = _listener.EndGetContext(result);\n _listener.BeginGetContext(ProcessRequest, null);\n await ProcessRequest(ctx).ConfigureAwait(false);\n }\n\n protected virtual async Task ProcessRequest(HttpListenerContext context)\n {\n if (context == null)\n throw new ArgumentNullException(nameof(context));\n\n var url = TargetUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);\n using (var msg = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), url + context.Request.RawUrl))\n {\n msg.Version = context.Request.ProtocolVersion;\n\n if (context.Request.HasEntityBody)\n {\n msg.Content = new StreamContent(context.Request.InputStream); // disposed with msg\n }\n\n string host = null;\n foreach (string headerName in context.Request.Headers)\n {\n var headerValue = context.Request.Headers[headerName];\n if (headerName == \"Content-Length\" &amp;&amp; headerValue == \"0\") // useless plus don't send if we have no entity body\n continue;\n\n bool contentHeader = false;\n switch (headerName)\n {\n // some headers go to content...\n case \"Allow\":\n case \"Content-Disposition\":\n case \"Content-Encoding\":\n case \"Content-Language\":\n case \"Content-Length\":\n case \"Content-Location\":\n case \"Content-MD5\":\n case \"Content-Range\":\n case \"Content-Type\":\n case \"Expires\":\n case \"Last-Modified\":\n contentHeader = true;\n break;\n\n case \"Referer\":\n if (RewriteReferer &amp;&amp; Uri.TryCreate(headerValue, UriKind.Absolute, out var referer)) // if relative, don't handle\n {\n var builder = new UriBuilder(referer);\n builder.Host = TargetUrl.Host;\n builder.Port = TargetUrl.Port;\n headerValue = builder.ToString();\n }\n break;\n\n case \"Host\":\n host = headerValue;\n if (RewriteHost)\n {\n headerValue = TargetUrl.Host + \":\" + TargetUrl.Port;\n }\n break;\n }\n\n if (contentHeader)\n {\n msg.Content.Headers.Add(headerName, headerValue);\n }\n else\n {\n msg.Headers.Add(headerName, headerValue);\n }\n }\n\n using (var response = await _client.SendAsync(msg).ConfigureAwait(false))\n {\n using (var os = context.Response.OutputStream)\n {\n context.Response.ProtocolVersion = response.Version;\n context.Response.StatusCode = (int)response.StatusCode;\n context.Response.StatusDescription = response.ReasonPhrase;\n\n foreach (var header in response.Headers)\n {\n context.Response.Headers.Add(header.Key, string.Join(\", \", header.Value));\n }\n\n foreach (var header in response.Content.Headers)\n {\n if (header.Key == \"Content-Length\") // this will be set automatically at dispose time\n continue;\n\n context.Response.Headers.Add(header.Key, string.Join(\", \", header.Value));\n }\n\n var ct = context.Response.ContentType;\n if (RewriteTargetInText &amp;&amp; host != null &amp;&amp; ct != null &amp;&amp;\n (ct.IndexOf(\"text/html\", StringComparison.OrdinalIgnoreCase) &gt;= 0 ||\n ct.IndexOf(\"application/json\", StringComparison.OrdinalIgnoreCase) &gt;= 0))\n {\n using (var ms = new MemoryStream())\n {\n using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))\n {\n await stream.CopyToAsync(ms).ConfigureAwait(false);\n var enc = context.Response.ContentEncoding ?? Encoding.UTF8;\n var html = enc.GetString(ms.ToArray());\n if (TryReplace(html, \"//\" + _targetHost + \":\" + _targetPort + \"/\", \"//\" + host + \"/\", out var replaced))\n {\n var bytes = enc.GetBytes(replaced);\n using (var ms2 = new MemoryStream(bytes))\n {\n ms2.Position = 0;\n await ms2.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n else\n {\n ms.Position = 0;\n await ms.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n }\n }\n else\n {\n using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))\n {\n await stream.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);\n }\n }\n }\n }\n }\n }\n\n public void Stop() =&gt; _listener.Stop();\n public override string ToString() =&gt; string.Join(\", \", Prefixes) + \" =&gt; \" + TargetUrl;\n public void Dispose() =&gt; ((IDisposable)_listener)?.Dispose();\n\n // out-of-the-box replace doesn't tell if something *was* replaced or not\n private static bool TryReplace(string input, string oldValue, string newValue, out string result)\n {\n if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))\n {\n result = input;\n return false;\n }\n\n var oldLen = oldValue.Length;\n var sb = new StringBuilder(input.Length);\n bool changed = false;\n var offset = 0;\n for (int i = 0; i &lt; input.Length; i++)\n {\n var c = input[i];\n\n if (offset &gt; 0)\n {\n if (c == oldValue[offset])\n {\n offset++;\n if (oldLen == offset)\n {\n changed = true;\n sb.Append(newValue);\n offset = 0;\n }\n continue;\n }\n\n for (int j = 0; j &lt; offset; j++)\n {\n sb.Append(input[i - offset + j]);\n }\n\n sb.Append(c);\n offset = 0;\n }\n else\n {\n if (c == oldValue[0])\n {\n if (oldLen == 1)\n {\n changed = true;\n sb.Append(newValue);\n }\n else\n {\n offset = 1;\n }\n continue;\n }\n\n sb.Append(c);\n }\n }\n\n if (changed)\n {\n result = sb.ToString();\n return true;\n }\n\n result = input;\n return false;\n }\n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
We have a netbeans project that has an xsd that we use to create a wsdl and we use the wsdl to create a webservice. Since we are using types in our xsd jaxb is used and one of our webservice methods looks like this: ``` public void someMethod( org.netbeans.xml.schema.line.Line x )... ``` So that leaves us a problem with subversion since the Line objects are generated by netbeans. So we want to do is either tell netbeans to place the files inside of the project? Or tell netbeans that we will generate the jaxb code and that they should use our classes when the webservice calls are processed? How can we accomplish one of these, what are some other alternatives?
You can build one with the [`HttpListener`](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) class to listen for incoming requests and the [`HttpWebRequest`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) class to relay the requests.
226,790
<p>Forgive me for being a complete newbie with Windows DDK.</p> <p>I have create a simple file named <code>test.cpp</code>:</p> <pre><code>#include &lt;windows.h&gt; #define BAD_ADDRESS 0xBAADF00D int __cdecl main(int argc, char* args[]) { char* p =(char*)BAD_ADDRESS; *p='A'; return 0; } </code></pre> <p>In the same directory I created a <code>sources</code> file like this:</p> <pre> TARGETNAME=test TARGETTYPE=PROGRAM TARGETPATH=obj TARGETLIBS=$(SDK_LIB_PATH)\kernel32.lib SOURCES= test.cpp </pre> <p>And a <code>makefile</code> like this:</p> <pre> # # DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source # file to this component. This file merely indirects to the real make file # that is shared by all the components of Windows # !INCLUDE $(NTMAKEENV)\makefile.def </pre> <p>After launching the Windows XP Free Build Environment I browse to the directory with the three files (test.cpp, makefile and sources) and run the following command:</p> <pre>F:\temp\debug\dir1>build -cZg</pre> <p>Which outputs:</p> <pre> BUILD: Adding /Y to COPYCMD so xcopy ops won't hang. BUILD: Using 2 child processes BUILD: Object root set to: ==> objfre_wxp_x86 BUILD: Compile and Link for i386 BUILD: Examining f:\temp\debug\dir1 directory for files to compile. BUILD: Compiling (NoSync) f:\temp\debug\dir1 directory 1>Compiling - test.cpp for i386 BUILD: Compiling f:\temp\debug\dir1 directory BUILD: Linking f:\temp\debug\dir1 directory 1>Linking Executable - objfre_wxp_x86\i386\test.exe for i386 BUILD: Done 2 files compiled 1 executable built </pre> <p>The problem is that when I run the created executable <code>test.exe</code> it says:</p> <pre> F:\temp\debug\dir1\objfre_wxp_x86\i386>test The F:\temp\debug\dir1\objfre_wxp_x86\i386\test.exe application cannot be run in Win32 mode. </pre> <p><strong>What am I missing here?</strong></p>
[ { "answer_id": 226952, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>You have compiled a 'native application' rather than a win32 one. The TARGET_TYPE definition controls this.</p>\n\n<p>See '<a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897447.aspx\" rel=\"nofollow noreferrer\">Inside Native Applications</a>' for a discussion of using the DDK to generate a native application.</p>\n" }, { "answer_id": 227165, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/226790/error-when-compiling-with-windows-ddk#226952\">Rob Walker</a> explains the why but <a href=\"http://blogs.msmvps.com/kernelmustard/2005/11/04/building-win32-apps-with-build-exe-and-the-ddk/\" rel=\"nofollow noreferrer\">Kernel Mustard</a> explains the how.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
Forgive me for being a complete newbie with Windows DDK. I have create a simple file named `test.cpp`: ``` #include <windows.h> #define BAD_ADDRESS 0xBAADF00D int __cdecl main(int argc, char* args[]) { char* p =(char*)BAD_ADDRESS; *p='A'; return 0; } ``` In the same directory I created a `sources` file like this: ``` TARGETNAME=test TARGETTYPE=PROGRAM TARGETPATH=obj TARGETLIBS=$(SDK_LIB_PATH)\kernel32.lib SOURCES= test.cpp ``` And a `makefile` like this: ``` # # DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source # file to this component. This file merely indirects to the real make file # that is shared by all the components of Windows # !INCLUDE $(NTMAKEENV)\makefile.def ``` After launching the Windows XP Free Build Environment I browse to the directory with the three files (test.cpp, makefile and sources) and run the following command: ``` F:\temp\debug\dir1>build -cZg ``` Which outputs: ``` BUILD: Adding /Y to COPYCMD so xcopy ops won't hang. BUILD: Using 2 child processes BUILD: Object root set to: ==> objfre_wxp_x86 BUILD: Compile and Link for i386 BUILD: Examining f:\temp\debug\dir1 directory for files to compile. BUILD: Compiling (NoSync) f:\temp\debug\dir1 directory 1>Compiling - test.cpp for i386 BUILD: Compiling f:\temp\debug\dir1 directory BUILD: Linking f:\temp\debug\dir1 directory 1>Linking Executable - objfre_wxp_x86\i386\test.exe for i386 BUILD: Done 2 files compiled 1 executable built ``` The problem is that when I run the created executable `test.exe` it says: ``` F:\temp\debug\dir1\objfre_wxp_x86\i386>test The F:\temp\debug\dir1\objfre_wxp_x86\i386\test.exe application cannot be run in Win32 mode. ``` **What am I missing here?**
[Rob Walker](https://stackoverflow.com/questions/226790/error-when-compiling-with-windows-ddk#226952) explains the why but [Kernel Mustard](http://blogs.msmvps.com/kernelmustard/2005/11/04/building-win32-apps-with-build-exe-and-the-ddk/) explains the how.
226,828
<p>After discussing with a newly arrived developer in my team, I realized that there are still, in C++, habits of using C constructs because they are supposed to be better (i.e. faster, leaner, prettier, pick your reason).</p> <p><strong>What are the examples worth sharing, showing a C constructs, compared to the similar C++ construct?</strong></p> <p>For each example, I need to read the reasons the C++ construct is as good as or even better the original C construct. The aim is to offer alternatives to some C constructs that are considered somewhat dangerous/unsafe in C++ code (C++0x valid only answers are accepted as long as clearly marked as C++0x only).</p> <p>I'll post below an answer (struct inline initialization) as an example.</p> <p><em>Note 1: Please, one answer per case. If you have multiple cases, please post multiple answers</em></p> <p><em>Note 2: <s>This is not a C question. Do not add the "C" tag to this question.</s></em> <em>This is not supposed to become a fight between C++ and C. Only the study of some constructs of the C subset of C++, and their alternative in other C++ "toolkits"</em></p> <p><em>Note 3: This is not a C-bashing question. I want reasons. Boasting, bashing, and unproven comparisons will be downmodded. Mentioning C++ features without a C equivalent could be considered out of topic: I want the put side by side a C feature against a C++ feature.</em></p>
[ { "answer_id": 226833, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "<h2>struct inline initialization vs. inline constructors</h2>\n<p>Sometimes, we need in C++ a simple aggregation of data. The data being somewhat independant, protecting it through encapsulation would not be worth the effort.</p>\n<pre><code>// C-like code in C++\nstruct CRect\n{\n int x ;\n int y ;\n} ;\n\nvoid doSomething()\n{\n CRect r0 ; // uninitialized\n CRect r1 = { 25, 40 } ; // vulnerable to some silent struct reordering,\n // or adding a parameter\n}\n</code></pre>\n<p>;\nI see three problems with the code above:</p>\n<ul>\n<li>if the object is not specifically initialized, it won't be at initialized all</li>\n<li>if we echange x or y (for whatever reason), the default C initialization in doSomething() will now be wrong</li>\n<li>if we add a z member, and liked it to be &quot;zero&quot; by default, we would still need to change every inline initializing</li>\n</ul>\n<p>The code below will have the constructors inlined (if really useful), and thus, will have a zero cost (as the C code above):</p>\n<pre><code>// C++\nstruct CRect\n{\n CRect() : x(0), y(0) {} ;\n CRect(int X, int Y) : x(X), y(Y) {} ;\n int x ;\n int y ;\n} ;\n\nvoid doSomething()\n{\n CRect r0 ;\n CRect r1(25, 40) ;\n}\n</code></pre>\n<p>(The bonus is that we could add a operator== methods, but this bonus is out of topic, and so worth mentioning but not worth as an answer.)</p>\n<h2>Edit: C99 has named initialized</h2>\n<p>Adam Rosenfield made an interesting comment I find very interesting:</p>\n<p><em>C99 allows named initializers:</em>\nCRect r = { .x = 25, .y = 40 }</p>\n<p>This won't compile in C++. I guess this should be added to C++, if only for C-compatibiliy. Anyway, in C, it alleviates the problem mentioned in this answer.</p>\n" }, { "answer_id": 226890, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": -1, "selected": false, "text": "<p>Nearly any use of <code>void*</code>.</p>\n" }, { "answer_id": 227021, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 5, "selected": false, "text": "<h2>Macros vs. inline templates</h2>\n\n<p>C style:</p>\n\n<pre><code>#define max(x,y) (x) &gt; (y) ? (x) : (y)\n</code></pre>\n\n<p>C++ style</p>\n\n<pre><code>inline template&lt;typename T&gt;\nconst T&amp; max(const T&amp; x, const T&amp; y)\n{\n return x &gt; y ? x : y;\n}\n</code></pre>\n\n<p>Reason to prefer C++ approach:</p>\n\n<ul>\n<li>Type safety -- Enforces that arguments must be of same type</li>\n<li>Syntax errors in definition of max will point to the correct place, rather than where you call the macro</li>\n<li>Can debug into the function</li>\n</ul>\n" }, { "answer_id": 227095, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 4, "selected": false, "text": "<h2>Default parameters:</h2>\n\n<h3>C:</h3>\n\n<pre><code>void AddUser(LPCSTR lpcstrName, int iAge, const char *lpcstrAddress);\nvoid AddUserByNameOnly(LPCSTR lpcstrName)\n {\n AddUser(lpcstrName, -1,NULL);\n }\n</code></pre>\n\n<h3>C++ replacement/equivalent:</h3>\n\n<pre><code>void User::Add(LPCSTR lpcstrName, int iAge=-1, const char *lpcstrAddress=NULL);\n</code></pre>\n\n<h3>Why it's an improvement:</h3>\n\n<p>Allows programmer to write express the function of the program in fewer lines of source code and in a more compact form. Also permits default values for unused parameters to be expressed closest to where they are actually used. For the caller, simplifies the interface to the class/struct. </p>\n" }, { "answer_id": 227142, "author": "Andrew Top", "author_id": 30036, "author_profile": "https://Stackoverflow.com/users/30036", "pm_score": 5, "selected": false, "text": "<h2>RAII and all the ensuing glory vs. manual resource acquisition/release</h2>\n\n<p>In C:</p>\n\n<pre><code>Resource r;\nr = Acquire(...);\n\n... Code that uses r ...\n\nRelease(r);\n</code></pre>\n\n<p>where as examples, <code>Resource</code> could be a pointer to memory and Acquire/Release will allocate/free that memory, or it could be an open file descriptor where Acquire/Release will open/close that file.</p>\n\n<p>This presents a number of problems:</p>\n\n<ol>\n<li>You might forget to call <code>Release</code></li>\n<li>No information about the data flow for <code>r</code> is conveyed by the code. If <code>r</code> is acquired and released within the same scope, the code does not self-document this.</li>\n<li>During the time between <code>Resource r</code> and <code>r.Acquire(...)</code>, <code>r</code> is actually accessible, despite being uninitialized. This is a source of bugs.</li>\n</ol>\n\n<p>Applying the RAII (Resource Acquisition Is Initialization) methodology, in C++ we obtain</p>\n\n<pre><code>class ResourceRAII\n{\n Resource rawResource;\n\n public:\n ResourceRAII(...) {rawResource = Acquire(...);}\n ~ResourceRAII() {Release(rawResource);}\n\n // Functions for manipulating the resource\n};\n\n...\n\n{\n ResourceRAII r(...);\n\n ... Code that uses r ...\n}\n</code></pre>\n\n<p>The C++ version will ensure you do not forget to release the resource (if you do, you have a memory leak, which is more easily detected by debugging tools). It forces the programmer to be explicit about how the resource's data flow (ie: if it only exists during a function's scope, this would be made clear by a construction of ResourceRAII on the stack). There is no point during between the creation of the resource object and its destruction where the resource is invalid. </p>\n\n<p>Its also exception safe!</p>\n" }, { "answer_id": 227188, "author": "Jeff Linahan", "author_id": 2222, "author_profile": "https://Stackoverflow.com/users/2222", "pm_score": 3, "selected": false, "text": "<h2>iostream vs stdio.h</h2>\n\n<p>In C:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n int num = 42;\n\n printf(\"%s%d%c\", \"Hello World\\n\", num, '\\n');\n\n return 0;\n}\n</code></pre>\n\n<p>The format string is parsed at runtime which means it is not type safe.</p>\n\n<p>in C++:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n int num = 42;\n\n std::cout &lt;&lt; \"Hello World\\n\" &lt;&lt; num &lt;&lt; '\\n';\n}\n</code></pre>\n\n<p>The data types are known at compile time, and there's also less to type because there is not need for a format string.</p>\n" }, { "answer_id": 227202, "author": "Cat Plus Plus", "author_id": 16102, "author_profile": "https://Stackoverflow.com/users/16102", "pm_score": 4, "selected": false, "text": "<h2>Dynamic arrays vs. STL containers</h2>\n\n<p>C-style:</p>\n\n<pre><code>int **foo = new int*[n];\nfor (int x = 0; x &lt; n; ++x) foo[x] = new int[m];\n// (...)\nfor (int x = 0; x &lt; n; ++x) delete[] foo[x];\ndelete[] foo;\n</code></pre>\n\n<p>C++-style:</p>\n\n<pre><code>std::vector&lt; std::vector&lt;int&gt; &gt; foo(n, std::vector&lt;int&gt;(m));\n// (...)\n</code></pre>\n\n<p>Why STL containers are better:</p>\n\n<ul>\n<li>They're resizeable, arrays have fixed size</li>\n<li>They're exception safe - if unhandled exception occurs in (...) part, then array memory may leak - container is created on stack, so it will be destroyed properly during unwind</li>\n<li>They implement bound checking, e.g. <a href=\"http://en.cppreference.com/w/cpp/container/vector/at\" rel=\"nofollow noreferrer\">vector::at()</a> (getting out of bounds on array will most likely generate an Access Violation and terminate the program)</li>\n<li>They're easier to use, e.g. <a href=\"http://en.cppreference.com/w/cpp/container/vector/clear\" rel=\"nofollow noreferrer\">vector::clear()</a> vs. manually clearing the array</li>\n<li>They hide memory management details, making code more readable</li>\n</ul>\n" }, { "answer_id": 227220, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 4, "selected": false, "text": "<p>#define vs. const</p>\n\n<p>I keep seeing code like this from developers who have coded C for a long time:</p>\n\n<pre><code>#define MYBUFSIZE 256\n\n. . . \n\nchar somestring[MYBUFSIZE];\n</code></pre>\n\n<p>etc. etc.</p>\n\n<p>In C++ this would be better as:</p>\n\n<pre><code>const int MYBUFSIZE = 256;\n\nchar somestring[MYBUFSIZE];\n</code></pre>\n\n<p><em>Of course, better yet would be for a developer to use std::string instead of a char array but that's a separate issue.</em> </p>\n\n<p>The problems with C macros are legion--no type checking being the major issue in this case. </p>\n\n<p>From what I've seen, this seems to be an extremely hard habit for C programmers converting to C++ to break.</p>\n" }, { "answer_id": 227349, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p><strong>C's <code>qsort</code> function versus C++' <code>sort</code> function template.</strong> The latter offers type safety through templates which have obvious and less obvious consequences:</p>\n\n<ul>\n<li>Type safety makes the code less error-prone.</li>\n<li>The interface of <code>sort</code> is slightly easier (no need to specify the size of the elements).</li>\n<li>The compiler knows the type of the comparer function. If, instead of a function pointer, the user passes a function <em>object</em>, <code>sort</code> will perform <em>faster</em> than <code>qsort</code> because inlining the comparison becomes trivial. This isn't the case with function pointers that are necessary in the C version.</li>\n</ul>\n\n<p>The following example demonstrates the usage of <code>qsort</code> versus <code>sort</code> on a C-style array of <code>int</code>.</p>\n\n<pre><code>int pint_less_than(void const* pa, void const* pb) {\n return *static_cast&lt;int const*&gt;(pa) - *static_cast&lt;int const*&gt;(pb);\n}\n\nstruct greater_than {\n bool operator ()(int a, int b) {\n return a &gt; b;\n }\n};\n\ntemplate &lt;std::size_t Size&gt;\nvoid print(int (&amp;arr)[Size]) {\n std::copy(arr, arr + Size, std::ostream_iterator&lt;int&gt;(std::cout, \" \"));\n std::cout &lt;&lt; std::endl;\n}\n\nint main() {\n std::size_t const size = 5;\n int values[] = { 4, 3, 6, 8, 2 };\n\n { // qsort\n int arr[size];\n std::copy(values, values + size, arr);\n std::qsort(arr, size, sizeof(int), &amp;pint_less_than);\n print(arr);\n }\n\n { // sort\n int arr[size];\n std::copy(values, values + size, arr);\n std::sort(arr, arr + size);\n print(arr);\n }\n\n { // sort with custom comparer\n int arr[size];\n std::copy(values, values + size, arr);\n std::sort(arr, arr + size, greater_than());\n print(arr);\n }\n}\n</code></pre>\n" }, { "answer_id": 227408, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "<p>Following fizzer's post at <a href=\"https://stackoverflow.com/questions/226828/c-constructs-replacing-c-constructs#227310\">C++ constructs replacing C constructs</a>, I'll write here my answer:</p>\n\n<p><strong>Warning: The C++ solution proposed below is not standard C++, but is an extension to g++ and Visual C++, and is proposed as a standard for C++0x</strong> (Thanks to <strong>Fizzer</strong>'s comments about this)</p>\n\n<p><b>Note that <a href=\"https://stackoverflow.com/questions/226828/c-constructs-replacing-c-constructs/411610#411610\">Johannes Schaub - litb's answer</a> offers another, C++03 compliant way to do it anyway.</b></p>\n\n<h2>Question</h2>\n\n<p>How to extract the size of a C array?</p>\n\n<h2>Proposed C solution</h2>\n\n<p>Source: <a href=\"https://stackoverflow.com/questions/96196/when-are-c-macros-beneficial#97292\">When are C++ macros beneficial?</a></p>\n\n<hr>\n\n<pre><code>#define ARRAY_SIZE(arr) (sizeof arr / sizeof arr[0])\n</code></pre>\n\n<p>Unlike the 'preferred' template solution discussed in a current thread, you can use it as a constant expression:</p>\n\n<pre><code>char src[23];\nint dest[ARRAY_SIZE(src)];\n</code></pre>\n\n<hr>\n\n<p>I disagree with Fizzer as there is a templated solution able to generate a constant expression (In fact, a very interesting part of templates is their capacity to generate constant expressions at compilation)</p>\n\n<p>Anyway, ARRAY_SIZE is a macro able to extract the size of a C array. I won't elaborate about the macros in C++: The aim is to find an equal or better C++ solution.</p>\n\n<h2>A better C++ solution?</h2>\n\n<p>The following C++ version has none of the macro problems, and can do anything the same way:</p>\n\n<pre><code>template &lt;typename T, size_t size&gt;\ninline size_t array_size(T (&amp;p)[size])\n{\n // return sizeof(p)/sizeof(p[0]) ;\n return size ; // corrected after Konrad Rudolph's comment.\n}\n</code></pre>\n\n<h2>demonstration</h2>\n\n<p>As demonstrated by the following code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n// C-like macro\n#define ARRAY_SIZE(arr) (sizeof arr / sizeof arr[0])\n\n// C++ replacement\ntemplate &lt;typename T, size_t size&gt;\ninline size_t array_size(T (&amp;p)[size])\n{\n // return sizeof(p)/sizeof(p[0]) ;\n return size ; // corrected after Konrad Rudolph's comment.\n}\n\nint main(int argc, char **argv)\n{\n char src[23];\n char * src2 = new char[23] ;\n int dest[ARRAY_SIZE(src)];\n int dest2[array_size(src)];\n\n std::cout &lt;&lt; \"ARRAY_SIZE(src) : \" &lt;&lt; ARRAY_SIZE(src) &lt;&lt; std::endl ;\n std::cout &lt;&lt; \"array_size(src) : \" &lt;&lt; array_size(src) &lt;&lt; std::endl ;\n std::cout &lt;&lt; \"ARRAY_SIZE(src2) : \" &lt;&lt; ARRAY_SIZE(src2) &lt;&lt; std::endl ;\n // The next line won't compile\n //std::cout &lt;&lt; \"array_size(src2) : \" &lt;&lt; array_size(src2) &lt;&lt; std::endl ;\n\n return 0;\n}\n</code></pre>\n\n<p>This will output:</p>\n\n<pre><code>ARRAY_SIZE(src) : 23\narray_size(src) : 23\nARRAY_SIZE(src2) : 4\n</code></pre>\n\n<p>In the code above, the macro mistook a pointer for an array, and thus, returned a wrong value (4, instead of 23). The template, instead, refused to compile:</p>\n\n<pre><code>/main.cpp|539|error: no matching function for call to ‘array_size(char*&amp;)’|\n</code></pre>\n\n<p>Thus demonstrating that the template solution is:\n* able to generate constant expression at compile time\n* able to stop the compilation if used in the wrong way</p>\n\n<h2>Conclusion</h2>\n\n<p>Thus, all in all, the arguments for the template is:</p>\n\n<ul>\n<li>no macro-like pollution of code</li>\n<li>can be hidden inside a namespace</li>\n<li>can protect from wrong type evaluation (a pointer to memory is not an array)</li>\n</ul>\n\n<p>Note: Thanks for Microsoft implementation of strcpy_s for C++... I knew this would serve me one day... ^_^</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/td1esda9.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/td1esda9.aspx</a></p>\n\n<h2>Edit: The solution is an extension standardized for C++0x</h2>\n\n<p>Fizzer did rightly comment this was not valid in the current C++ standard, and was quite true (as I could verify on g++ with -pedantic option checked).</p>\n\n<p>Still, not only this is usable today on two major compilers (i.e. Visual C++ and g++), but this was considered for C++0x, as proposed in the following drafts:</p>\n\n<ul>\n<li><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1521.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1521.pdf</a> (see sections \"2.1 Constant-expression functions\")</li>\n<li><a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2691.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2691.pdf</a> (see sections \"5.19 Constant expressions\" and \"7.1.5 The constexpr specifier\")</li>\n</ul>\n\n<p>The only change for C++0x being probably something like:</p>\n\n<pre><code>inline template &lt;typename T, size_t size&gt;\nconstexpr size_t array_size(T (&amp;p)[size])\n{\n //return sizeof(p)/sizeof(p[0]) ;\n return size ; // corrected after Konrad Rudolph's comment.\n}\n</code></pre>\n\n<p>(note the <strong>constexpr</strong> keyword)</p>\n\n<h2>Edit 2</h2>\n\n<p><a href=\"https://stackoverflow.com/questions/226828/c-constructs-replacing-c-constructs/411610#411610\">Johannes Schaub - litb's answer</a> offers another, C++03 compliant way to do it. I'll copy paste the source here for reference, but do visit his answer for a complete example (<b>and upmod it!</b>):</p>\n\n<pre><code>template&lt;typename T, size_t N&gt; char (&amp; array_size(T(&amp;)[N]) )[N];\n</code></pre>\n\n<p>Which is used as:</p>\n\n<pre><code>int p[] = { 1, 2, 3, 4, 5, 6 };\nint u[sizeof array_size(p)]; // we get the size (6) at compile time.\n</code></pre>\n\n<p>Many neurons in my brain fried to make me understand the nature of <code>array_size</code> (hint: it's a function returning a reference to an array of N chars).</p>\n\n<p>:-)</p>\n" }, { "answer_id": 227409, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 2, "selected": false, "text": "<p>casting the C way <code>(type)</code> versus <code>static_cast&lt;type&gt;()</code>. see <a href=\"https://stackoverflow.com/questions/103512/in-c-why-use-staticcastintx-instead-of-intx#103868\">there</a> and <a href=\"https://stackoverflow.com/questions/28002/regular-cast-vs-staticcast-vs-dynamiccast#28037\">there</a> on stackoverflow for the topic</p>\n" }, { "answer_id": 229637, "author": "Alex Che", "author_id": 23715, "author_profile": "https://Stackoverflow.com/users/23715", "pm_score": 2, "selected": false, "text": "<p><strong>Local (automatic) variables declaration</strong></p>\n\n<p>(Not true since C99, as correctly pointed by Jonathan Leffler)</p>\n\n<p>In C, you must declare all local variables at the start of the block in which they are defined.</p>\n\n<p>In C++ it is possible (and preferable) to postpone variable definition before it must be used.\nLater is preferable for two main reasons:</p>\n\n<ol>\n<li>It increases program clarity (as you see the type of variable where it is used for the first time).</li>\n<li>It makes refactoring easier (as you have small cohesive chunks of code).</li>\n<li>It improves program efficiency (as variables are constructed just when they actually needed).</li>\n</ol>\n" }, { "answer_id": 234192, "author": "Steve", "author_id": 1965047, "author_profile": "https://Stackoverflow.com/users/1965047", "pm_score": 0, "selected": false, "text": "<h2>Overloaded functions:</h2>\n\n<h3>C:</h3>\n\n<pre><code>AddUserName(int userid, NameInfo nameinfo);\nAddUserAge(int userid, int iAge);\nAddUserAddress(int userid, AddressInfo addressinfo);\n</code></pre>\n\n<h3>C++ equivalent/replacement:</h3>\n\n<pre><code>User::AddInfo(NameInfo nameinfo);\nUser::AddInfo(int iAge);\nUser::AddInfo(AddressInfo addressInfo);\n</code></pre>\n\n<h3>Why it's an improvement:</h3>\n\n<p>Allows the programmer to express the interface such that the concept of the function is expressed in the name, and the parameter type is only expressed in the parameter itself. Allows the caller to interact with the class in a manner closer to an expression of the concepts. Also generally results in more concise, compact and readable source code. </p>\n" }, { "answer_id": 235288, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "<p><strong>iostreams</strong></p>\n\n<p>Formatted I/O may be faster using the C runtime. But I don't believe that low-level I/O (read,write,etc.) is any slower with streams. The ability to read or write to a stream without caring if the other end is a file, string, socket or some user-defined object is incredibly useful.</p>\n" }, { "answer_id": 245394, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 2, "selected": false, "text": "<p>In response to <a href=\"https://stackoverflow.com/questions/226828/c-constructs-replacing-c-constructs#229637\">Alex Che</a>, and in fairness to C:</p>\n\n<p>In C99, the current ISO standard spec for C, variables may be declared anywhere in a block, the same as in C++. The following code is valid C99:</p>\n\n<pre><code>int main(void)\n{\n for(int i = 0; i &lt; 10; i++)\n ...\n\n int r = 0;\n return r;\n}\n</code></pre>\n" }, { "answer_id": 402185, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 2, "selected": false, "text": "<p>I'll offer something that is perhaps abundantly obvious, Namespaces.</p>\n<h2>c's crowded global scope:</h2>\n<pre><code>void PrintToScreen(const char *pBuffer);\nvoid PrintToFile(const char *pBuffer);\nvoid PrintToSocket(const char *pBuffer);\nvoid PrintPrettyToScreen(const char *pBuffer);\n</code></pre>\n<p>vs.</p>\n<h2>c++'s definable subdivisions of global scope, namespaces:</h2>\n<pre><code>namespace Screen\n{\n void Print(const char *pBuffer);\n}\n\nnamespace File\n{\n void Print(const char *pBuffer);\n}\n\nnamespace Socket\n{\n void Print(const char *pBuffer);\n}\n\nnamespace PrettyScreen\n{\n void Print(const char *pBuffer);\n}\n</code></pre>\n<p>This is a bit of a contrived example, but the ability to classify tokens you define into scopes that make sense prevents confusing purpose of the function with the context in which it is called.</p>\n" }, { "answer_id": 402222, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 0, "selected": false, "text": "<p>In c, much of your dynamic functionality is achieved by passing about function pointers. C++ allows you to have Function Objects, providing greater flexibility and safety. I'll present an example adapted from Stephen Dewhurst's excellent <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321321928\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\" title=\" Amazon: C++ Common Knowledge by Stephen Dewhurst\">C++ Common Knowledge</a></p>\n\n<h2>C Function Pointers:</h2>\n\n<pre><code>int fibonacci() {\n static int a0 = 0, a1 =1; // problematic....\n int temp = a0;\n a0 = a1;\n a1 = temp + a0;\n return temp;\n}\n\nvoid Graph( (int)(*func)(void) );\nvoid Graph2( (int)(*func1)(void), (int)(*func2)(void) ); \n\nGraph(fibonacci);\nGraph2(fibonacci,fibonacci);\n</code></pre>\n\n<p>You can see that, given the static variables in the function <code>fibonacci()</code>, the order of execution of <code>Graph</code> and <code>Graph2()</code> will change the behavior, not withstanding the fact that call to <code>Graph2()</code> may have unexpected results as each call to <code>func1</code> and <code>func2</code> will yield the next value in the series, not the next value in an individual instance of the series with respect to the function being called. (Obviously you could externalize the state of the function, but that would be missing the point, not to mention confusing to the user and complicating to the client functions)</p>\n\n<h2>C++ Function Objects:</h2>\n\n<pre><code>class Fib {\n public:\n Fib() : a0_(1), a1_(1) {}\n int operator();\n private:\n int a0_, a1_;\n};\nint Fib::operator() {\n int temp = a0_;\n a0_ = a1_;\n a1_ = temp + a0_;\n return temp;\n}\n\n\ntemplate &lt;class FuncT&gt;\nvoid Graph( FuncT &amp;func );\n\ntemplate &lt;class FuncT&gt;\nvoid Graph2( FuncT &amp;func1, FuncT &amp;func2); \n\nFib a,b,c;\nGraph(a);\nGraph2(b,c);\n</code></pre>\n\n<p>Here, the order of execution of the <code>Graph()</code> and <code>Graph2()</code> functions does not change the result of the call. Also, in the call to <code>Graph2()</code> <code>b</code> and <code>c</code> maintain separate state as they are used; each will generate the complete Fibonacci sequence individually. </p>\n" }, { "answer_id": 411610, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<p>Following <a href=\"https://stackoverflow.com/questions/226828/c-constructs-replacing-c-constructs#227408\">paercebal</a>'s construct using variable length arrays to get around the limitation that functions can't return constant expressions yet, here is a way to do just that, in a certain other way:</p>\n\n<pre><code>template&lt;typename T, size_t N&gt; char (&amp; array_size(T(&amp;)[N]) )[N];\n</code></pre>\n\n<p>I've written it in some of my other answers, but it doesn't fit anywhere better than into this thread. Now, well, here is how one could use it:</p>\n\n<pre><code>void pass(int *q) {\n int n1 = sizeof(q); // oops, size of the pointer!\n int n2 = sizeof array_size(q); // error! q is not an array!\n}\n\nint main() {\n int p[] = { 1, 2, 3, 4, 5, 6 };\n int u[sizeof array_size(p)]; // we get the size at compile time.\n\n pass(p);\n}\n</code></pre>\n\n<h3>Advantage over sizeof</h3>\n\n<ol>\n<li>Fails for non-arrays. Will <em>not</em> silently work for pointers</li>\n<li>Will tell in the code that the array-size is taken. </li>\n</ol>\n" }, { "answer_id": 411644, "author": "kal", "author_id": 43756, "author_profile": "https://Stackoverflow.com/users/43756", "pm_score": 0, "selected": false, "text": "<p>new in C++ vs malloc in C. (for memory management)</p>\n\n<p>new operator allows class constructors to be called whereas malloc does not.</p>\n" }, { "answer_id": 10464325, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 1, "selected": false, "text": "<h2><code>std::copy</code> vs. <code>memcpy</code></h2>\n<p>First there are usability concerns:</p>\n<ul>\n<li><code>memcpy</code> takes void pointers. This throws out type safety.</li>\n<li><code>std::copy</code> allows overlapping ranges in certain cases (with <code>std::copy_backward</code> existing for other overlapping cases), while <code>memcpy</code> does not ever allow it.</li>\n<li><code>memcpy</code> only works on pointers, while <code>std::copy</code> works on iterators (of which pointers are a special case, so <code>std::copy</code> works on pointers, too). This means that you can, for example, <code>std::copy</code> elements in a <code>std::list</code>.</li>\n</ul>\n<p>Surely all of this extra safety and generality comes at a price, right?</p>\n<p>When I measured, I found that <a href=\"https://stackoverflow.com/questions/4707012/c-memcpy-vs-stdcopy/9980859#9980859\"><code>std::copy</code> had a slight performance advantage over <code>memcpy</code></a>.</p>\n<p><strong>In other words, it seems as if there is no reason to use <code>memcpy</code> in real C++ code.</strong></p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
After discussing with a newly arrived developer in my team, I realized that there are still, in C++, habits of using C constructs because they are supposed to be better (i.e. faster, leaner, prettier, pick your reason). **What are the examples worth sharing, showing a C constructs, compared to the similar C++ construct?** For each example, I need to read the reasons the C++ construct is as good as or even better the original C construct. The aim is to offer alternatives to some C constructs that are considered somewhat dangerous/unsafe in C++ code (C++0x valid only answers are accepted as long as clearly marked as C++0x only). I'll post below an answer (struct inline initialization) as an example. *Note 1: Please, one answer per case. If you have multiple cases, please post multiple answers* *Note 2: ~~This is not a C question. Do not add the "C" tag to this question.~~* *This is not supposed to become a fight between C++ and C. Only the study of some constructs of the C subset of C++, and their alternative in other C++ "toolkits"* *Note 3: This is not a C-bashing question. I want reasons. Boasting, bashing, and unproven comparisons will be downmodded. Mentioning C++ features without a C equivalent could be considered out of topic: I want the put side by side a C feature against a C++ feature.*
Macros vs. inline templates --------------------------- C style: ``` #define max(x,y) (x) > (y) ? (x) : (y) ``` C++ style ``` inline template<typename T> const T& max(const T& x, const T& y) { return x > y ? x : y; } ``` Reason to prefer C++ approach: * Type safety -- Enforces that arguments must be of same type * Syntax errors in definition of max will point to the correct place, rather than where you call the macro * Can debug into the function
226,831
<p>I'd like to make anchors to every post in my asp.net forum. Every forum's post is rendered using repeater control. How can I render <code>&lt;a name="anchor_name"&gt;&lt;/a&gt;</code> in asp.net?</p>
[ { "answer_id": 226838, "author": "Travis Collins", "author_id": 30460, "author_profile": "https://Stackoverflow.com/users/30460", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;a name='&lt;%# Eval(\"PostId\") %&gt;' /&gt;\n</code></pre>\n\n<p>where PostId is the name of the property you want to appear in your anchor.</p>\n" }, { "answer_id": 226841, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": -1, "selected": false, "text": "<p>Adding <code>&lt;a name=\"anchor_name\"&gt;&lt;/a&gt;</code> in the ItemTempate of the repeater at the appropriate spot should do the trick. A little more information might help.</p>\n" }, { "answer_id": 226854, "author": "Chris Porter", "author_id": 13495, "author_profile": "https://Stackoverflow.com/users/13495", "pm_score": 1, "selected": false, "text": "<p>This won't be exact code as I'm not in VS to ensure the syntax but something like this should get you were you want to go.</p>\n\n<pre><code>&lt;a name=\"&lt;%# Bind('PostId') %&gt;\" runat=\"server\" /&gt;\n</code></pre>\n" }, { "answer_id": 226943, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 0, "selected": false, "text": "<p>Extend the System.Web.UI.WebControls.HyperLink class, and override UniqueID property to return the actual ID:</p>\n\n<pre><code>override string UniqueID { get { return ID; } }\n</code></pre>\n\n<p>Use this new user control in the item template of the repeater.</p>\n\n<pre><code>&lt;MyPrefix:MyHyperLink ID=\"IDOfYourHyperLink\" ... /&gt;\n</code></pre>\n\n<p>On ItemDataBound do:</p>\n\n<pre><code>(e.Item.FindControl(\"IDOfYourHyperLink\") as MyHyperlink).ID = NowIKnowWhatToUseHere;\n</code></pre>\n" }, { "answer_id": 227061, "author": "rafek", "author_id": 3182, "author_profile": "https://Stackoverflow.com/users/3182", "pm_score": 0, "selected": false, "text": "<p>Ok. I've resolved it this way:</p>\n\n<pre><code>&lt;a name='&lt;%# DataBinder.Eval(Container.DataItem, \"Id\") %&gt;' /&gt;\n</code></pre>\n\n<p>where Id is the property of binded entity.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3182/" ]
I'd like to make anchors to every post in my asp.net forum. Every forum's post is rendered using repeater control. How can I render `<a name="anchor_name"></a>` in asp.net?
``` <a name='<%# Eval("PostId") %>' /> ``` where PostId is the name of the property you want to appear in your anchor.
226,834
<p>I'm working on a C++ prettyprinter and would like to show the results of the prettyprinter by comparing code before and after running it. Does anyone know where I can find some ugly C++ code to run through the prettypretty? Ideally the code would come from some open source software.</p>
[ { "answer_id": 226852, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 3, "selected": false, "text": "<p>Try doing a search for 'C++ obfuscation' and you should be able to find C++ code that is hard to read.</p>\n" }, { "answer_id": 226878, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>Another good test is to take normal C++ code and see how well it can reformat it to a different code formatting standard.</p>\n" }, { "answer_id": 226897, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 2, "selected": false, "text": "<p>Not C++ but have you checked out The International Obfuscated C Code Contest?</p>\n\n<p>Check out some of the winners <a href=\"http://www.ioccc.org/years.html\" rel=\"nofollow noreferrer\">code</a></p>\n" }, { "answer_id": 226909, "author": "AdamC", "author_id": 16476, "author_profile": "https://Stackoverflow.com/users/16476", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://bugs.eclipse.org/bugs/buglist.cgi?query_format=advanced&amp;short_desc_type=anywordssubstr&amp;short_desc=formatter&amp;product=CDT&amp;long_desc_type=allwordssubstr&amp;long_desc=&amp;bug_file_loc_type=allwordssubstr&amp;bug_file_loc=&amp;status_whiteboard_type=allwordssubstr&amp;status_whiteboard=&amp;keywords_type=allwords&amp;keywords=&amp;emailtype1=substring&amp;email1=&amp;emailtype2=substring&amp;email2=&amp;bugidtype=include&amp;bug_id=&amp;votes=&amp;chfieldfrom=&amp;chfieldto=Now&amp;chfieldvalue=&amp;cmdtype=doit&amp;order=Reuse+same+sort+as+last+time&amp;field0-0-0=noop&amp;type0-0-0=noop&amp;value0-0-0=\" rel=\"nofollow noreferrer\">Here is a list of bugs</a> filed against the eclipse C/C++ tools project. Many of the bugs are about code that wasn't formatted correctly, so you can see how they did things and even look at the fixes if they are resolved.</p>\n" }, { "answer_id": 227122, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 3, "selected": false, "text": "<p>If you can't find a good corpus of ugly code, you could always write a \"code uglifier\" and then run it on some average code.</p>\n\n<p>For example:</p>\n\n<ul>\n<li>Remove all insignificant spaces</li>\n<li>Remove/Insert random spaces</li>\n<li>Replaces tabs with different number of spaces.</li>\n</ul>\n" }, { "answer_id": 227163, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 4, "selected": false, "text": "<p>Anything coded to the <a href=\"http://www.gnu.org/prep/standards/html_node/Formatting.html#Formatting\" rel=\"noreferrer\">GNU coding standards</a> will give you a shitty indentation style to practise on. Verbatim example:</p>\n\n<pre><code> if (x &lt; foo (y, z))\n haha = bar[4] + 5;\n else\n {\n while (z)\n {\n haha += foo (z, z);\n z--;\n }\n return ++x + bar ();\n }\n</code></pre>\n" }, { "answer_id": 227398, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>Your prettyprinter is presumably configurable? Then it will be able to generate ugly code for suitable inputs.</p>\n" }, { "answer_id": 7623580, "author": "Mechanical snail", "author_id": 319931, "author_profile": "https://Stackoverflow.com/users/319931", "pm_score": 0, "selected": false, "text": "<p>Look at \"golfed\" <a href=\"https://codegolf.stackexchange.com/questions/tagged/c%2b%2b\">C++ programs on the Code Golf Stack Exchange site</a>. They are uglified in order to save space.</p>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm working on a C++ prettyprinter and would like to show the results of the prettyprinter by comparing code before and after running it. Does anyone know where I can find some ugly C++ code to run through the prettypretty? Ideally the code would come from some open source software.
Anything coded to the [GNU coding standards](http://www.gnu.org/prep/standards/html_node/Formatting.html#Formatting) will give you a shitty indentation style to practise on. Verbatim example: ``` if (x < foo (y, z)) haha = bar[4] + 5; else { while (z) { haha += foo (z, z); z--; } return ++x + bar (); } ```
226,847
<p>I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 =&lt; only. Here is the code I have:</p> <pre><code>var oImg = document.createElement("img"); oImg.setAttribute('src', 'http://www.testtrackinglink.com'); oImg.setAttribute('alt', 'na'); oImg.setAttribute('height', '1px'); oImg.setAttribute('width', '1px'); document.body.appendChild(oImg); </code></pre> <p>Is this the simplest but most robust (error free) way to do it?</p> <p>I cannot use a framework like jQuery. It needs to be in plain JavaScript.</p>
[ { "answer_id": 226856, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Are you allowed to use a framework? <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a> and <a href=\"http://prototypejs.org\" rel=\"noreferrer\">Prototype</a> make this sort of thing pretty easy. Here's a sample in Prototype:</p>\n\n<pre><code>var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });\n$(document).insert(elem);\n</code></pre>\n" }, { "answer_id": 226875, "author": "Tad", "author_id": 30095, "author_profile": "https://Stackoverflow.com/users/30095", "pm_score": 6, "selected": false, "text": "<pre><code>var img = new Image(1,1); // width, height values are optional params \nimg.src = 'http://www.testtrackinglink.com';\n</code></pre>\n" }, { "answer_id": 226922, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 5, "selected": false, "text": "<pre><code>var img = document.createElement('img');\nimg.src = 'my_image.jpg';\ndocument.getElementById('container').appendChild(img);\n</code></pre>\n" }, { "answer_id": 226941, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": false, "text": "<p>jQuery:</p>\n\n<pre><code>$('#container').append('&lt;img src=\"/path/to/image.jpg\"\n width=\"16\" height=\"16\" alt=\"Test Image\" title=\"Test Image\" /&gt;');\n</code></pre>\n\n<p>I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):</p>\n\n<pre><code>$('#container').append($('&lt;img&gt;', { \n src : \"/path/to/image.jpg\", \n width : 16, \n height : 16, \n alt : \"Test Image\", \n title : \"Test Image\"\n}));\n</code></pre>\n" }, { "answer_id": 227093, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 8, "selected": true, "text": "<pre><code>oImg.setAttribute('width', '1px');\n</code></pre>\n\n<p><code>px</code> is for CSS only. Use either:</p>\n\n<pre><code>oImg.width = '1';\n</code></pre>\n\n<p>to set a width through HTML, or:</p>\n\n<pre><code>oImg.style.width = '1px';\n</code></pre>\n\n<p>to set it through CSS.</p>\n\n<p>Note that old versions of IE don't create a proper image with <code>document.createElement()</code>, and old versions of KHTML don't create a proper DOM Node with <code>new Image()</code>, so if you want to be fully backwards compatible use something like:</p>\n\n<pre><code>// IEWIN boolean previously sniffed through eg. conditional comments\n\nfunction img_create(src, alt, title) {\n var img = IEWIN ? new Image() : document.createElement('img');\n img.src = src;\n if ( alt != null ) img.alt = alt;\n if ( title != null ) img.title = title;\n return img;\n}\n</code></pre>\n\n<p>Also be slightly wary of <code>document.body.appendChild</code> if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <code>&lt;body&gt;</code> element has started), you could try inserting it at the start of the body using <code>body.insertBefore(body.firstChild)</code>.</p>\n\n<p>To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <code>&lt;div&gt;</code> as the body's first child and put any tracking/preload images you don't want to be visible in there.</p>\n" }, { "answer_id": 229329, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 3, "selected": false, "text": "<p>Shortest way: </p>\n\n<pre><code>(new Image()).src = \"http:/track.me/image.gif\";\n</code></pre>\n" }, { "answer_id": 229350, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 0, "selected": false, "text": "<p>As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).</p>\n" }, { "answer_id": 230096, "author": "Binny V A", "author_id": 15595, "author_profile": "https://Stackoverflow.com/users/15595", "pm_score": 3, "selected": false, "text": "<p>Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...</p>\n\n<pre><code>document.getElementById(\"image-holder\").innerHTML = \"&lt;img src='image.png' alt='The Image' /&gt;\";\n</code></pre>\n\n<p>By the way, <a href=\"http://www.quirksmode.org/blog/archives/2006/01/the_ajax_respon_1.html#link5\" rel=\"noreferrer\">innerHTML is not that bad</a></p>\n" }, { "answer_id": 7776653, "author": "Nitin Bansal", "author_id": 967062, "author_profile": "https://Stackoverflow.com/users/967062", "pm_score": 2, "selected": false, "text": "<p>you could simply do:</p>\n\n<pre><code>var newImage = new Image();\nnewImage.src = \"someImg.jpg\";\n\nif(document.images)\n{\n document.images.yourImageElementName.src = newImage.src;\n}\n</code></pre>\n\n<p>Simple :)</p>\n" }, { "answer_id": 40192076, "author": "Vaibs", "author_id": 1253088, "author_profile": "https://Stackoverflow.com/users/1253088", "pm_score": 2, "selected": false, "text": "<p>Just to add full html JS example</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;meta charset=\"UTF-8\"&gt;\n &lt;title&gt;create image demo&lt;/title&gt;\n &lt;script&gt;\n\n\n function createImage() {\n var x = document.createElement(\"IMG\");\n x.setAttribute(\"src\", \"http://www.iseebug.com/wp-content/uploads/2016/09/c2.png\");\n x.setAttribute(\"height\", \"200\");\n x.setAttribute(\"width\", \"400\");\n x.setAttribute(\"alt\", \"suppp\");\n document.getElementById(\"res\").appendChild(x);\n }\n\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;button onclick=\"createImage()\"&gt;ok&lt;/button&gt;\n&lt;div id=\"res\"&gt;&lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 50042804, "author": "Gvs Akhil", "author_id": 7737777, "author_profile": "https://Stackoverflow.com/users/7737777", "pm_score": 1, "selected": false, "text": "<p>This is the method I follow to create a loop of img tags or a single tag as ur wish</p>\n\n<pre><code>method1 :\n let pics=document.getElementById(\"pics-thumbs\");\n let divholder=document.createDocumentFragment();\n for(let i=1;i&lt;73;i++)\n {\n let img=document.createElement(\"img\");\n img.class=\"img-responsive\";\n img.src=`images/fun${i}.jpg`;\n divholder.appendChild(img);\n }\n pics.appendChild(divholder);\n</code></pre>\n\n<p>or </p>\n\n<pre><code>method2: \nlet pics = document.getElementById(\"pics-thumbs\"),\n imgArr = [];\nfor (let i = 1; i &lt; 73; i++) {\n\n imgArr.push(`&lt;img class=\"img-responsive\" src=\"images/fun${i}.jpg\"&gt;`);\n}\npics.innerHTML = imgArr.join('&lt;br&gt;')\n&lt;div id=\"pics-thumbs\"&gt;&lt;/div&gt;\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3004/" ]
I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 =< only. Here is the code I have: ``` var oImg = document.createElement("img"); oImg.setAttribute('src', 'http://www.testtrackinglink.com'); oImg.setAttribute('alt', 'na'); oImg.setAttribute('height', '1px'); oImg.setAttribute('width', '1px'); document.body.appendChild(oImg); ``` Is this the simplest but most robust (error free) way to do it? I cannot use a framework like jQuery. It needs to be in plain JavaScript.
``` oImg.setAttribute('width', '1px'); ``` `px` is for CSS only. Use either: ``` oImg.width = '1'; ``` to set a width through HTML, or: ``` oImg.style.width = '1px'; ``` to set it through CSS. Note that old versions of IE don't create a proper image with `document.createElement()`, and old versions of KHTML don't create a proper DOM Node with `new Image()`, so if you want to be fully backwards compatible use something like: ``` // IEWIN boolean previously sniffed through eg. conditional comments function img_create(src, alt, title) { var img = IEWIN ? new Image() : document.createElement('img'); img.src = src; if ( alt != null ) img.alt = alt; if ( title != null ) img.title = title; return img; } ``` Also be slightly wary of `document.body.appendChild` if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the `<body>` element has started), you could try inserting it at the start of the body using `body.insertBefore(body.firstChild)`. To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page `<div>` as the body's first child and put any tracking/preload images you don't want to be visible in there.
226,894
<p>When you use the PHP <a href="http://us2.php.net/manual/en/function.copy.php" rel="noreferrer">copy</a> function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?</p>
[ { "answer_id": 226901, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>I think you answered your own question - check to make sure the destination file exists before performing the copy. If the file exists, skip the copy.</p>\n\n<p>Update: I see you really did answer your own question. You mention race conditions, but if you do find that the file already exists, how do you know that:</p>\n\n<ul>\n<li>the file that is already there is really the one you want to copy</li>\n<li>the other process copying the file has completed its job (the file data is all there)</li>\n<li>the other process copying the file isn't going to fail (and leave an incomplete file, or delete the new file)</li>\n</ul>\n\n<p>I think you should consider these questions when designing a solution to your problem.</p>\n" }, { "answer_id": 226906, "author": "Douglas Mayle", "author_id": 8458, "author_profile": "https://Stackoverflow.com/users/8458", "pm_score": 4, "selected": true, "text": "<p>The obvious solution would be to call <a href=\"http://us2.php.net/manual/en/function.file-exists.php\" rel=\"nofollow noreferrer\">file_exists</a> to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call <a href=\"http://us2.php.net/manual/en/function.file-exists.php\" rel=\"nofollow noreferrer\">file_exists</a> and when you call <a href=\"http://us2.php.net/manual/en/function.copy.php\" rel=\"nofollow noreferrer\">copy</a>. The only safe way to check if the file exists is to use <a href=\"http://us2.php.net/manual/en/function.fopen.php\" rel=\"nofollow noreferrer\">fopen</a>.</p>\n\n<p>When you call <a href=\"http://us2.php.net/manual/en/function.fopen.php\" rel=\"nofollow noreferrer\">fopen</a>, set the mode to 'x'. This tells <a href=\"http://us2.php.net/manual/en/function.fopen.php\" rel=\"nofollow noreferrer\">fopen</a> to create the file, but only if it doesn't exist. If it exists, <a href=\"http://us2.php.net/manual/en/function.fopen.php\" rel=\"nofollow noreferrer\">fopen</a> will fail, and you'll know that you couldn't create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below:</p>\n\n<pre><code>// The PHP copy function blindly copies over existing files. We don't wish\n// this to happen, so we have to perform the copy a bit differently. The\n// only safe way to ensure we don't overwrite an existing file is to call\n// fopen in create-only mode (mode 'x'). If it succeeds, the file did not\n// exist before, and we've successfully created it, meaning we own the\n// file. After that, we can safely copy over our own file.\n\n$filename = 'sourcefile.txt'\n$copyname = 'sourcefile_copy.txt'\nif ($file = @fopen($copyname, 'x')) {\n // We've successfully created a file, so it's ours. We'll close\n // our handle.\n if (!@fclose($file)) {\n // There was some problem with our file handle.\n return false;\n }\n\n // Now we copy over the file we created.\n if (!@copy($filename, $copyname)) {\n // The copy failed, even though we own the file, so we'll clean\n // up by itrying to remove the file and report failure.\n unlink($copyname);\n return false;\n }\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 547711, "author": "Ben Blank", "author_id": 46387, "author_profile": "https://Stackoverflow.com/users/46387", "pm_score": 0, "selected": false, "text": "<p>Try using the <a href=\"http://us.php.net/manual/en/function.link.php\" rel=\"nofollow noreferrer\"><code>link()</code></a> function instead of <code>copy()</code>.</p>\n\n<pre><code>function safe_copy($src, $dest) {\n if (link($src, $dest)) {\n // Link succeeded, remove old name\n unlink($filename);\n return true;\n } else {\n // Link failed; filesystem has not been altered\n return false;\n }\n}\n</code></pre>\n\n<p>Unfortunately, this will <strong>not</strong> work on Windows.</p>\n" }, { "answer_id": 22653312, "author": "Jens A. Koch", "author_id": 1163786, "author_profile": "https://Stackoverflow.com/users/1163786", "pm_score": 1, "selected": false, "text": "<p>A honey badger function, which just doesn't care about race-conditions, but works cross-platform.</p>\n\n<pre><code>function safeCopy($src, $dest) {\n if (is_file($dest) === true) {\n // if the destination file already exists, it will NOT be overwritten. \n return false;\n }\n\n if (copy($src, $dest) === false) {\n echo \"Failed to copy $src... Permissions correct?\\n\";\n return false;\n }\n\n return true; \n}\n</code></pre>\n" } ]
2008/10/22
[ "https://Stackoverflow.com/questions/226894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8458/" ]
When you use the PHP [copy](http://us2.php.net/manual/en/function.copy.php) function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?
The obvious solution would be to call [file\_exists](http://us2.php.net/manual/en/function.file-exists.php) to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call [file\_exists](http://us2.php.net/manual/en/function.file-exists.php) and when you call [copy](http://us2.php.net/manual/en/function.copy.php). The only safe way to check if the file exists is to use [fopen](http://us2.php.net/manual/en/function.fopen.php). When you call [fopen](http://us2.php.net/manual/en/function.fopen.php), set the mode to 'x'. This tells [fopen](http://us2.php.net/manual/en/function.fopen.php) to create the file, but only if it doesn't exist. If it exists, [fopen](http://us2.php.net/manual/en/function.fopen.php) will fail, and you'll know that you couldn't create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below: ``` // The PHP copy function blindly copies over existing files. We don't wish // this to happen, so we have to perform the copy a bit differently. The // only safe way to ensure we don't overwrite an existing file is to call // fopen in create-only mode (mode 'x'). If it succeeds, the file did not // exist before, and we've successfully created it, meaning we own the // file. After that, we can safely copy over our own file. $filename = 'sourcefile.txt' $copyname = 'sourcefile_copy.txt' if ($file = @fopen($copyname, 'x')) { // We've successfully created a file, so it's ours. We'll close // our handle. if (!@fclose($file)) { // There was some problem with our file handle. return false; } // Now we copy over the file we created. if (!@copy($filename, $copyname)) { // The copy failed, even though we own the file, so we'll clean // up by itrying to remove the file and report failure. unlink($copyname); return false; } return true; } ```