Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how? I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.
I'm not a python guru, but I found this question interesting so I googled around. [This](https://mail.python.org/pipermail/python-list/2007-September/427041.html) was the first hit on "python embedding API" - does it help? > If the attributes belong to the global > scope of a module, then you can use > "PyImport\_AddModule" to get a handle > to the module object. For example, if > you wanted to get the value of an > integer in the **main** module named > "foobar", you would do the following: > > ``` > PyObject *m = PyImport_AddModule("__main__"); > PyObject *v = PyObject_GetAttrString(m,"foobar"); > > int foobar = PyInt_AsLong(v); > > Py_DECREF(v); > ```
For anyone coming here from Google, here's the direct method: ``` PyObject* PyEval_GetGlobals() ``` <https://docs.python.org/2/c-api/reflection.html> <https://docs.python.org/3/c-api/reflection.html> The return value is accessed as a dictionary.
How to access a Python global variable from C?
[ "", "python", "c", "" ]
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.
It can be done... The way we do it here is to use the /DEF option of the linker to pass a ["module definition file"](https://learn.microsoft.com/en-us/cpp/build/reference/module-definition-dot-def-files?view=vs-2017) 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 [dumpbin](http://msdn.microsoft.com/en-us/library/c1h23y6c.aspx) /LINKERMEMBER command, and manipulating the output via a simple script to the format of a module definition file. It is a lot of work to setup, but it allows us to compile code created without dllexport declarations for Unix on Windows.
Export all symbols when creating a DLL
[ "", "c++", "windows", "visual-studio", "visual-studio-2005", "" ]
I have 50+ kiosk style computers that I want to be able to get a status update, from a single computer, on demand as opposed to an interval. These computers are on a LAN in respect to the computer requesting the status. I researched WCF however it looks like I'll need IIS installed and I would rather not install IIS on 50+ Windows XP boxes -- so I think that eliminates using a webservice unless it's possible to have a WinForm host a webservice? I also researched using System.Net.Sockets and even got a barely functional prototype going however I feel I'm not skilled enough to make it a solid and reliable system. Given this path, I would need to learn more about socket programming and threading. These boxes are running .NET 3.5 SP1, so I have complete flexibility in the .NET version however I'd like to stick to C#. What is the best way to implement this? Should I just bite the bullet and learn Sockets more or does .NET have a better way of handling this? edit: I was going to go with a two way communication until I realized that all I needed was a one way communication. edit 2: I was avoiding the traditional server/client and going with an inverse because I wanted to avoid consuming too much bandwidth and wasn't sure what kind of overhead I was talking about. I was also hoping to have more control of the individual kiosks. After looking at it, I think I can still have that with WCF and connect by IP (which I wasn't aware I could connect by IP, I was thinking I would have to add 50 webservices or something).
Unless you have plans to scale this to several thousand clients I don't think WCF performance will even be a fringe issue. You can easily host WCF services from windows services or Winforms applications, and you'll find getting something working with WCF will be fairly simple once you get the key concepts. I've deployed something similar with around 100-150 clients with great success. There's plenty of resources out on the web to get you started - here's one to get you going: <http://msdn.microsoft.com/en-us/library/aa480190.aspx>
WCF does not have to be hosted within IIS, it can be hosted within your Winform, as a console application or as windows service. You can have each computer host its service within the winform, and write a program in your own computer to call each computer's service to get the status information. Another way of doing it is to host one service in your own computer, and make the 50+ computers to call the service once their status were updated, you can use a database for the service to persist the status data of each node within the network. This option is easier to maintain and scalable. P.S. WCF aims to replace .net remoting, the alternatives can be net.tcp binding or net.pipe
Communication between server and client for WinForms
[ "", "c#", ".net", "networking", "" ]
Why does Resharper want you to change most variables to var type instead of the actual type in the code?
It's just an option. You can disable it: ReSharper -> Options -> Code Inspection -> Inspection Severity -> Code Redundencies -> Use 'var' keyword where possible: change this to "Do not show" There's also the context (lightbulb) option which will take you in each direction - this is under ReSharper -> Options -> Languages -> C# -> Context Actions -> "Replaces explicit type declaration with 'var'"
I saw a video from Hadi Hariri, where he was presenting Resharper 6.x. His reasoning was, if you are forcing a user to use "var", you are actually forcing him to name the variable in a more meaningful way, that way all the names are readable and make more sense.
Resharper: vars
[ "", "c#", ".net", "resharper", "" ]
Is there ever a good reason to *not* declare a virtual destructor for a class? When should you specifically avoid writing one?
There is no need to use a virtual destructor when any of the below is true: * No intention to derive classes from it * No instantiation on the heap * No intention to store with access via a pointer to a superclass No specific reason to avoid it unless you are really so pressed for memory.
To answer the question explicitly, i.e. when should you *not* declare a virtual destructor. **C++ '98/'03** Adding a virtual destructor might change your class from being [POD (plain old data)](https://en.wikipedia.org/wiki/Passive_data_structure)\* or aggregate to non-POD. This can stop your project from compiling if your class type is aggregate initialized somewhere. ``` struct A { // virtual ~A (); int i; int j; }; void foo () { A a = { 0, 1 }; // Will fail if virtual dtor declared } ``` In an extreme case, such a change can also cause undefined behaviour where the class is being used in a way that requires a POD, e.g. passing it via an ellipsis parameter, or using it with memcpy. ``` void bar (...); void foo (A & a) { bar (a); // Undefined behavior if virtual dtor declared } ``` [\* A POD type is a type that has specific guarantees about its memory layout. The standard really only says that if you were to copy from an object with POD type into an array of chars (or unsigned chars) and back again, then the result will be the same as the original object.] **Modern C++** In recent versions of C++, the concept of POD was split between the class layout and its construction, copying and destruction. For the ellipsis case, it is no longer undefined behavior it is now conditionally-supported with implementation-defined semantics (N3937 - ~C++ '14 - 5.2.2/7): > ...Passing a potentially-evaluated argument of class type (Clause 9) having a non-trivial copy constructor, a non-trivial move constructor, or a on-trivial destructor, with no corresponding parameter, is conditionally-supported with implementation-defined semantics. Declaring a destructor other than `=default` will mean it's not trivial (12.4/5) > ... A destructor is trivial if it is not user-provided ... Other changes to Modern C++ reduce the impact of the aggregate initialization problem as a constructor can be added: ``` struct A { A(int i, int j); virtual ~A (); int i; int j; }; void foo () { A a = { 0, 1 }; // OK } ```
When should you not use virtual destructors?
[ "", "c++", "virtual-functions", "virtual-destructor", "" ]
Is there an easy way to generate an array containing the letters of the alphabet in C#? It's not too hard to do it by hand, but I was wondering if there was a built in way to do this.
I don't think there is a built in way, but I think the easiest would be ``` char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); ```
C# 3.0 : ``` char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray(); foreach (var c in az) { Console.WriteLine(c); } ``` yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-)
Generating an array of letters in the alphabet
[ "", "c#", "alphabet", "" ]
I have some old C code that I would like to combine with some C++ code. The C code used to have has the following includes: ``` #include <windows.h> #include <stdio.h> #include <string.h> #include "mysql.h" ``` Now I'm trying to make it use C++ with iostream like this: ``` #include <windows.h> #include <stdio.h> #include <string> #include <iostream> #include "mysql.h" ``` But I keep getting the following linker errors when I compile: > [Linker error] undefined reference to `std::string::size() const' > > [Linker error] undefined reference to `std::string::operator[](unsigned int) const' > > [Linker error] undefined reference to `std::string::operator[](unsigned int) const' > > [Linker error] undefined reference to `std::string::operator[](unsigned int) const' > > [Linker error] undefined reference to `std::ios\_base::Init::Init()' > > [Linker error] undefined reference to `std::ios\_base::Init::~Init()' > > ld returned 1 exit status How do I resolve this? Edit: My compiler is Dev-C++ 4.9.9.2
The C `string.h` header and the C++ `string` header are not interchangeable. Overall, though, your problem is that the file is getting properly compiled, but the wrong runtime library is getting linked in. Dev-C++ uses GCC. GCC can correctly determine the language in a file based on file extension, but won't link the right runtime library in unless you specifically ask it to (`-lstdc++` at the command line). Calling GCC as "`g++`" (or, in your case, "`mingwin32-g++`") will also get the right language and will link the needed library.
You need to link against your C++ runtime. It depends on your platform and compiler, but adding `-lc` to your linker command might do it. So might linking using your C++ compiler rather than `ld`. In any case, you probably have to link using the C++ compiler rather than `ld` if you want your C++ code to work correctly -- it's often required for exceptions and static initializers to work correctly...
iostream linker error
[ "", "c++", "c", "linker", "iostream", "" ]
I was wondering if there is a way to implement an action listener for a Jbutton without a name. For example, I have the following for loop that creates a button for each letter of the alphabet. ``` for (int i = 65; i < 91; i++){ alphabetPanel.add(new JButton("<html><center>" + (char)i)); } ``` Is there a way that I can add an action listener for each of those buttons without getting rid of my for loop and hard coding each JButton and then creating an action listener for each? Thanks in advance, Tomek
Your question is a little vague. it would be trivial to modify the loop to add a listener inside the loop: ``` ActionListener listener = something; for (int i = 65; i < 91; i++){ JButton button = new JButton("<html><center>" + (char)i); button.addActionListener( listener ); alphabetPanel.add(button); } ``` if you can't modify the loop you could iterate over all of the panel's children, and add listeners to any of the children that are jbuttons. also why are you using html to center the text? isn't that overkill? doesn't jbutton already center text? you could use setHorizontalAlignement(SwingConstants.CENTER) to do it too.
What is the problem of doing this? ``` for (int i = 65; i < 91; i++){ JButton button = new JButton("<html><center>" + (char)i)); button.addActionListener( new ButtonListener()); alphabetPanel.add(button); } ``` ... ``` class ButtonListener implements ActionListener { ButtonListener() { } public void actionPerformed(ActionEvent e) { //TODO: } } ``` Also, if the button's text doesn't identify the button you could set the button's name with the letter of the alphabet. ``` button.setName((char)i)); // or button.setName(i); ```
Java actionListener for a nameless JButton?
[ "", "java", "swing", "jbutton", "actionlistener", "" ]
I'm using a PropertyGrid in a tool app to show a window to monitor an object in a remote app. Every second or so I get an update from the app with the state of any members that have changed, and I update the grid. I call Refresh() to make the changes take. This all works pretty well except one thing. Say the object is too tall to fit in the grid so there's a scrollbar. The user has selected a grid item but has also scrolled up above it so that the selected item is below the bottom of the control. The problem is that on Refresh() the control automatically scrolls the grid item into view (strangely it doesn't do this when the item is above the top of the control). I'm looking for a way to either prevent this, or to save state, do the Refresh(), and then set it back. I tried getting the underlying VScrollBar in the PropertyGridView inside the PropertyGrid, and messing with "Value", but it doesn't stay permanently set. Always pops back so the item is in view. Deselecting the item during scrolling is my fallback (the auto scroll-into-view doesn't happen with no selected grid item) but it hurts the usability a little so I'm looking for another way. Anyone run into something similar?
This is not possible in the MS PropertyGrid. This component has too many unaccessible internals to give you the flexibility you are requesting and as you realized yourself it is not consistent (you have the issue for a property below the grid but not when it is above). That's why I created [Smart PropertyGrid.Net](http://www.visualhint.com). If a commercial product is an option for you, this grid has the option to store property states and restore them after you made an action on the grid (like Refresh()) without any flicker.
I`ve found an interesting hack: you can manually select the grid items you changed and they will refresh :) ``` var panProp = categ.GridItems[3]; var tiltProp = categ.GridItems[4]; panProp.Select(); tiltProp.Select(); ``` So I select items I need and than move the selection back
How to prevent scroll on Refresh in a PropertyGrid?
[ "", "c#", "propertygrid", "" ]
How can I get the name of a file in in PHP? What I want to do is have a function take a string of a filename and then do some stuff if it's actually on the page. ``` function onThisPageFunction(fileNameFromFunction) { if(onThisPage == fileNameFromFunction) { do stuff } } ```
There are two variables that will give you file names. eg: you call /test/test1.php as the url and test1.php includes test2.php. [`__FILE__`](http://pl.php.net/manual/en/language.constants.predefined.php) will give you the current file of the executing code, in this case it will return "test2.php" [`$_SERVER['PHP_SELF']`](https://www.php.net/manual/en/reserved.variables.server.php) will give you the full url of the original call, in this case "/test/test1.php" Note that you can use the [basename()](http://ca.php.net/basename) function to get just the filename from a path.
If I understand correctly you want `__FILE__`. Ref: <http://php.net/manual/en/language.constants.predefined.php>
Getting the name of file in PHP
[ "", "php", "" ]
I've used MS Word automation to save a .doc to a .htm. If there are bullet characters in the .doc file, they are saved fine to the .htm, but when I try to read the .htm file into a string (so I can subsequently send to a database for ultimate storage as a string, not a blob), the bullets are converted to question marks or other characters depending on the encoding used to load into a string. I'm using this to read the text: ``` string html = File.ReadAllText(myFileSpec); ``` I've also tried using StreamReader, but get the same results (maybe it's used internally by File.ReadAllText). I've also tried specifying every type of Encoding in the second overload of File.ReadAllText: ``` string html = File.ReadAllText(originalFile, Encoding.ASCII); ``` I've tried all the available enums for the Encoding type. Any ideas?
On my system (using US-English) Word saves \*.htm files in the Windows-1252 codepage. If your system uses that codepage, then that is what you should read it in as. ``` string html = File.ReadAllText(originalFile, Encoding.GetEncoding(1252)); ``` It is also possible that whatever you are using the view the results may be creating the question marks for you, though, so be sure and check for that too.
Did you try opening the file in binary mode. If you open in test mode I think it will chop up the unicode characters.
.NET: Convert .doc to .htm results in funky characters
[ "", "c#", "encoding", "" ]
If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll). How can I do this in C#? I tried the Merge statement on the datatable, but this returns void. Does Merge preserve the data? For example, if I do: ``` dtOne.Merge(dtTwo); ``` Does dtOne change or does dtTwo change and if either one changes, do the changes preserve? I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll: ``` //Will Not work, How do I do this dtAll = dtOne.Merge(dtTwo); ```
The `Merge` method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both. If you want to preserve both of the original tables, you could copy the original first, then merge: ``` dtAll = dtOne.Copy(); dtAll.Merge(dtTwo); ```
Instead of `dtAll = dtOne.Copy();` in [Jeromy Irvine's answer](https://stackoverflow.com/a/285500/979621) you can start with an empty `DataTable` and merge one-by-one iteratively: ``` dtAll = new DataTable(); ... dtAll.Merge(dtOne); dtAll.Merge(dtTwo); dtAll.Merge(dtThree); ... ``` and so on. This technique is useful in a loop where you want to iteratively merge data tables: ``` DataTable dtAllItems = new DataTable(); foreach(var item in items) { DataTable dtItem = getDataTable(item); // some function that returns a data table dtAllItems.Merge(dtItem); } ```
Merge 2 DataTables and store in a new one
[ "", "c#", "datatable", "" ]
In C++, is it safe to extend scope via a reference? In code, what I mean is: ``` MyCLass& function badIdea() { MyClass obj1; ... return obj1; } ```
It is NOT safe to extend the scope via reference. Objects in C++ are not reference counted when obj1 goes out of scope it will be deleted, refering to the result of badIdea() will only get you into trouble
The only place it's OK to extend a scope with a reference is with a `const` reference in `namespace` or function scope (not with class members). ``` const int & cir = 1+1; // OK to use cir = 2 after this line ``` This trick is used in [Andrei Alexandrescu's](http://erdani.org/) very cool [scope guard](http://www.ddj.com/cpp/184403758) in order to capture a `const` reference to a base class of the concrete scope guard.
In C++, is it safe to extend scope via a reference?
[ "", "c++", "reference", "scope", "" ]
I've got an array of `char*` in a file. The company I work for stores data in flat files.. Sometimes the data is sorted, but sometimes it's not. I'd like to sort the data in the files. Now I could write the code to do this, from scratch. Is there an easier way? Of course an in-place sort would be the best option. I'm working on large files and have little RAM. But I'll consider all options. All strings are the same length. This is some sample data: ``` the data is of fixed length the Data is of fixed length thIS data is of fixed lengt ``` This would represent three records of length 28. The app knows the length. Each record ends with CRLF (`\r\n`), though it shouldn't matter for this sort.
``` template<size_t length> int less(const char* left, const char* right) { return memcmp(left, right, length) < 0; } std::sort(array, array + array_length, less<buffer_length>); ```
Use the GNU sort program (externally) if you can't fit the data into RAM: it will sort arbitrary sized files and the larger the file, the smaller the additional cost of creating the process.
Is there an easy way to sort an array of char*'s ? C++
[ "", "c++", "sorting", "in-place", "external-sorting", "" ]
> **Possible Duplicate:** > [How do I mark a method as Obsolete/Deprecated? - C#](https://stackoverflow.com/questions/1759352/how-do-i-mark-a-method-as-obsolete-deprecated-c-sharp) How do you mark a class as deprecated? I do not want to use a class any more in my project, but do not want to delete it before a period of 2 weeks.
You need to use the `[Obsolete]` attribute. Example: ``` [Obsolete("Not used any more", true)] public class MyDeprecatedClass { //... } ``` The parameters are optional. The first parameter is for providing the reason it's obsolete, and the last one is to throw an error at compile time instead of a warning.
As per Doak's answer, but the attribute's second parameter should be set to false if you want the code to compile: ``` [Obsolete("Not used any more", false)] public class MyDeprecatedClass { //... } ``` This will just throw warnings.
How to mark a class as Deprecated?
[ "", "c#", ".net", "oop", "deprecated", "" ]
Here's the goal: to replace all standalone ampersands with &amp; but NOT replace those that are already part of an HTML entity such as &nbsp;. I think I need a regular expression for PHP (preferably for preg\_ functions) that will match only standalone ampersands. I just don't know how to do that with preg\_replace.
You could always run `html_entity_decode` before you run `htmlentities`? Works unless you only want to do ampersands (and even then you can play with the charset parameters). Much easier and faster than a regex.
PHP's `htmlentities()` has `double_encode` argument for this. If you want to do things like that in regular expressions, then negative assertions come useful: ``` preg_replace('/&(?!(?:[[:alpha:]][[:alnum:]]*|#(?:[[:digit:]]+|[Xx][[:xdigit:]]+));)/', '&amp;', $txt); ```
regex (in PHP) to match & that aren't HTML entities
[ "", "php", "regex", "pcre", "" ]
I'm looking to implement something in Java along the lines of: ``` class Foo{ private int lorem; // private int ipsum; public setAttribute(String attr, int val){ //sets attribute based on name } public static void main(String [] args){ Foo f = new Foo(); f.setAttribute("lorem",1); f.setAttribute("ipsum",2); } public Foo(){} } ``` ...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?
Here's how you might implement `setAttribute` using reflection (I've renamed the function; there are different reflection functions for different field types): ``` public void setIntField(String fieldName, int value) throws NoSuchFieldException, IllegalAccessException { Field field = getClass().getDeclaredField(fieldName); field.setInt(this, value); } ```
In general, you want to use Reflection. Here is a good introduction to the [topic with examples](http://web.archive.org/web/20081218060124/http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html) In particular, the "Changing Values of Fields" section describes how to do what you'd like to do. I note that the author says, "This feature is extremely powerful and has no equivalent in other conventional languages." Of course, in the last ten years (the article was written in 1998) we have seen great strides made in dynamic languages. The above is fairly easily done in Perl, Python, PHP, Ruby, and so on. I suspect this is the direction you might have come from based on the "eval" tag.
Setting variables by name in Java
[ "", "java", "reflection", "eval", "" ]
When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical? For example: ``` HDC dc = ::GetDC(NULL); const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX); const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY); assert(xDPI == yDPI); ::ReleaseDC(NULL, dc); ``` Are these values ever different?
It's possible for it to be different, but that generally only applies to printers. It can be safely assumed that the screen will always have identical horizontal and vertical DPIs.
I have never seen them be different, but on [this](http://msdn.microsoft.com/en-us/library/aa273854(VS.60).aspx) MSDN page I see a comment that suggests that they might be: ``` int nHorz = dc.GetDeviceCaps(LOGPIXELSX); int nVert = dc.GetDeviceCaps(LOGPIXELSY); // almost always the same in both directions, but sometimes not! ```
Windows GDI: horizontal/vertical DPI
[ "", "c++", "c", "windows", "gdi", "" ]
I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to `Date.toMonth()`, `Date.toYear()` and other deprecated `Date` methods. All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use `Calendar` methods. Has Sun/Oracle actually said when these things are going away, or does `@deprecated` just mean you lose style points?
Regarding the APIs, ... it is not specified they will be removed anytime soon. [Incompatibilities in J2SE 5.0 (since 1.4.2)](http://java.sun.com/j2se/1.5.0/compatibility.html): Source Compatibility > [...] > In general, the policy is as follows, except for any incompatibilities listed further below: > > Deprecated APIs are interfaces that are supported only for backwards compatibility. The javac compiler generates a warning message whenever one of these is used, unless the -nowarn command-line option is used. It is recommended that programs be modified to eliminate the use of deprecated APIs, **though there are no current plans to remove such APIs** – with the exception of JVMDI and JVMPI – entirely from the system. Even in its [How and When To Deprecate APIs](http://java.sun.com/javase/6/docs/technotes/guides/javadoc/deprecation/deprecation.html), nothing is being said about a policy regarding actually *removing* the deprected APIs... --- Update 10 years later, the new [JDK9+ **Enhanced Deprecation**](https://docs.oracle.com/javase/9/core/enhanced-deprecation1.htm#JSCOR-GUID-23B13A9E-2727-42DC-B03A-E374B3C4CE96) clarifies the depreciation policy. See [Jens Bannmann](https://stackoverflow.com/users/7641/jens-bannmann)'s [answer](https://stackoverflow.com/a/50445603/6309) for more details. This is also detailed in this blog post by [Vojtěch Růžička](https://twitter.com/vojtechruzicka), following [criticisms on JEP 277](https://blog.jooq.org/2015/12/22/jep-277-enhanced-deprecation-is-nice-but-heres-a-much-better-alternative/). > The convention for JDK is that once a JDK API is marked as `forRemoval=true` in a certain Java version, **it will be removed in the directly following major Java release**. > That means - when something is marked as `forRemoval=true` in Java 9, it is supposed to be completely removed in Java 10. > **Keep that in mind when using API marked for removal.** > > Note that this convention applies only to JDK itself and third-party libraries are free to choose any convention they see fit.
They're not going away. That said, they're usually deprecated because a) they're dangerous ala Thread.stop(), or b) there is a better or at least more accepted way to do it. Usually deprecated method javadoc will give you a hint as to the better way. In your case, Calendar is the recommended way to do this. While it's conceivable that they will be removed at some point in the future, I wouldn't bet on it. If anyone ever forks Java however, they'll probably be the first thing to go...
When are API methods marked "deprecated" actually going to go away?
[ "", "java", "date", "" ]
I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.
``` function loadJSInclude(scriptPath, callback) { var scriptNode = document.createElement('SCRIPT'); scriptNode.type = 'text/javascript'; scriptNode.src = scriptPath; var headNode = document.getElementsByTagName('HEAD'); if (headNode[0] != null) headNode[0].appendChild(scriptNode); if (callback != null) { scriptNode.onreadystagechange = callback; scriptNode.onload = callback; } } ``` And to use (I used swfObject as an example): ``` var callbackMethod = function () { // Code to do after loading swfObject } // Include SWFObject if its needed if (typeof(SWFObject) == 'undefined') loadJSInclude('/js/swfObject.js', callbackMethod); else callbackMethod(); ```
You might want to take a look at jsloader: <http://www.jsloader.com/>
loading javascript dependencies on demand
[ "", "javascript", "google-maps", "" ]
I heard a lot about makefiles and how they simplify the compilation process. I'm using VS2008. Can somebody please suggest some online references or books where I can find out more about how to deal with them?
A UNIX guy probably told you that. :) You can use makefiles in VS, but when you do it bypasses all the built-in functionality in MSVC's IDE. Makefiles are basically the reinterpret\_cast of the builder. IMO the simplest thing is just to use Solutions.
The Microsoft Program Maintenance Utility (NMAKE.EXE) is a tool that builds projects based on commands contained in a description file. [NMAKE Reference](http://msdn.microsoft.com/en-us/library/dd9y37ha.aspx)
How to use makefiles in Visual Studio?
[ "", "c++", "visual-studio", "makefile", "" ]
I need to test if a file is a shortcut. I'm still trying to figure out how stuff will be set up, but I might only have it's path, I might only have the actual contents of the file (as a byte[]) or I might have both. A few complications include that I it could be in a zip file (in this cases the path will be an internal path)
Shortcuts can be manipulated using the COM objects in SHELL32.DLL. In your Visual Studio project, add a reference to the COM library "Microsoft Shell Controls And Automation" and then use the following: ``` /// <summary> /// Returns whether the given path/file is a link /// </summary> /// <param name="shortcutFilename"></param> /// <returns></returns> public static bool IsLink(string shortcutFilename) { string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename); string filenameOnly = System.IO.Path.GetFileName(shortcutFilename); Shell32.Shell shell = new Shell32.ShellClass(); Shell32.Folder folder = shell.NameSpace(pathOnly); Shell32.FolderItem folderItem = folder.ParseName(filenameOnly); if (folderItem != null) { return folderItem.IsLink; } return false; // not found } ``` You can get the actual target of the link as follows: ``` /// <summary> /// If path/file is a link returns the full pathname of the target, /// Else return the original pathnameo "" if the file/path can't be found /// </summary> /// <param name="shortcutFilename"></param> /// <returns></returns> public static string GetShortcutTarget(string shortcutFilename) { string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename); string filenameOnly = System.IO.Path.GetFileName(shortcutFilename); Shell32.Shell shell = new Shell32.ShellClass(); Shell32.Folder folder = shell.NameSpace(pathOnly); Shell32.FolderItem folderItem = folder.ParseName(filenameOnly); if (folderItem != null) { if (folderItem.IsLink) { Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink; return link.Path; } return shortcutFilename; } return ""; // not found } ```
You can simply check the extension and/or contents of this file. It contains a special GUID in the header. Read [this document][1]. Link deleted, for me it goes to a porn site
How can I test programmatically if a path/file is a shortcut?
[ "", "c#", "shortcut", "" ]
The following code ``` public class GenericsTest2 { public static void main(String[] args) throws Exception { Integer i = readObject(args[0]); System.out.println(i); } public static <T> T readObject(String file) throws Exception { return readObject(new ObjectInputStream(new FileInputStream(file))); // closing the stream in finally removed to get a small example } @SuppressWarnings("unchecked") public static <T> T readObject(ObjectInputStream stream) throws Exception { return (T)stream.readObject(); } } ``` compiles in eclipse, but not with javac (type parameters of T cannot be determined; no unique maximal instance exists for type variable T with upper bounds T,java.lang.Object). When I change readObject(String file) to ``` @SuppressWarnings("unchecked") public static <T> T readObject(String file) throws Exception { return (T)readObject(new ObjectInputStream(new FileInputStream(file))); } ``` it compiles in eclipse and with javac. Who is correct, the eclipse compiler or javac?
I'd say it's the bug in the Sun compiler reported [here](https://bugs.java.com/bugdatabase/view_bug?bug_id=6302954) and [here](https://bugs.eclipse.org/bugs/show_bug.cgi?id=98379), because if you change your line to the one below it works with both, which seems to be exactly what is described in the bug reports. ``` return GenericsTest2.<T>readObject(new ObjectInputStream(new FileInputStream(file))); ```
In this case, I'd say your code is wrong (and the Sun compiler is right). There is nothing in your input arguments to `readObject` to actually infer the type `T`. In that case, you're better off to let it return Object, and let clients manually cast the result type. This should work (though I haven't tested it): ``` public static <T> T readObject(String file) throws Exception { return GenericsTest2.<T>readObject(new ObjectInputStream(new FileInputStream(file))); } ```
Bug in eclipse compiler or in javac ("type parameters of T cannot be determined")
[ "", "java", "eclipse", "generics", "" ]
It's simple enough to code up a class to store/validate something like `192.168.0.0/16`, but I was curious if a native type for this already existed in .NET? I would imagine it would work a lot like `IPAddress`: ``` CIDR subnet = CIDR.Parse("192.168.0.0/16"); ``` Basically it just needs to make sure you're working with an IPv4 or IPv6 address and then that the number of bits your specifying is valid for that type.
No there is such native type in .NET, you will need to develop one your self.
You can use the code from GitHub to do just that: <https://github.com/lduchosal/ipnetwork> ``` IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24"); Console.WriteLine("Network : {0}", ipnetwork.Network); Console.WriteLine("Netmask : {0}", ipnetwork.Netmask); Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast); Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable); Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable); Console.WriteLine("Usable : {0}", ipnetwork.Usable); Console.WriteLine("Cidr : {0}", ipnetwork.Cidr); ``` Output ``` Network : 192.168.168.0 Netmask : 255.255.255.0 Broadcast : 192.168.168.255 FirstUsable : 192.168.168.1 LastUsable : 192.168.168.254 Usable : 254 Cidr : 24 ```
Is there native .NET type for CIDR subnets?
[ "", "c#", ".net", "ip-address", "subnet", "cidr", "" ]
Can somebody please give me an example of a unidirectional @OneToOne primary-key mapping in Hibernate ? I've tried numerous combinations, and so far the best thing I've gotten is this : ``` @Entity @Table(name = "paper_cheque_stop_metadata") @org.hibernate.annotations.Entity(mutable = false) public class PaperChequeStopMetadata implements Serializable, SecurityEventAware { private static final long serialVersionUID = 1L; @Id @JoinColumn(name = "paper_cheque_id") @OneToOne(cascade = {}, fetch = FetchType.EAGER, optional = false, targetEntity = PaperCheque.class) private PaperCheque paperCheque; } ``` Whenever Hibernate tries to automatically generate the schema for the above mapping, it tries to create the primary key as a blob, instead of as a long, which is the id type of PaperCheque. Can somebody please help me ? If I can't get an exact solution, something close would do, but I'd appreciate any response.
Your intention is to have a 1-1 relationship between PaperChequeStopMetaData and PaperCheque? If that's so, you can't define the PaperCheque instance as the @Id of PaperChequeStopMetaData, you have to define a separate @Id column in PaperChequeStopMetaData.
I saved [this discussion](http://forum.hibernate.org/viewtopic.php?p=2381079) when I implemented a couple of @OneToOne mappings, I hope it can be of use to you too, but we don't let Hibernate create the database for us. Note the GenericGenerator annotation. Anyway, I have this code working: ``` @Entity @Table(name = "message") public class Message implements java.io.Serializable { @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "message_id") public MessageContent getMessageContent() { return messageContent; } } @Entity @Table(name = "message_content") @GenericGenerator(name = "MessageContent", strategy = "foreign", parameters = { @org.hibernate.annotations.Parameter ( name = "property", value = "message" ) } ) public class MessageContent implements java.io.Serializable { @Id @Column(name = "message_id", unique = true, nullable = false) // See http://forum.hibernate.org/viewtopic.php?p=2381079 @GeneratedValue(generator = "MessageContent") public Integer getMessageId() { return this.messageId; } } ```
Need an example of a primary-key @OneToOne mapping in Hibernate
[ "", "java", "hibernate", "annotations", "one-to-one", "" ]
**Executive Summary:** When assertion errors are thrown in the threads, the unit test doesn't die. This makes sense, since one thread shouldn't be allowed to crash another thread. The question is how do I either 1) make the whole test fail when the first of the helper threads crashes or 2) loop through and determine the state of each thread after they have all completed (see code below). One way of doing the latter is by having a per thread status variable, e.g., "boolean[] statuses" and have "statuses[i] == false" mean that the thread failed (this could be extended to capture more information). However, that is not what I want: I want it to fail just like any other unit test when the assertion errors are thrown. Is this even possible? Is it desirable? I got bored and I decided to spawn a bunch of threads in my unit test and then have them call a service method, just for the heck of it. The code looks approximately like: ``` Thread[] threads = new Thread[MAX_THREADS]; for( int i = 0; i < threads.length; i++ ) { threads[i] = new Thread( new Runnable() { private final int ID = threadIdSequenceNumber++; public void run() { try { resultRefs[ID] = runTest( Integer.toString( ID ) ); // returns an object } catch( Throwable t ) { // this code is EVIL - it catches even // Errors - don't copy it - more on this below final String message = "error testing thread with id => " + ID; logger.debug( message, t ); throw new IllegalStateException( message, t ); // need to wrap throwable in a // run time exception so it will compile } } } ); } ``` After this, we will loop through the array of threads and start each one. After that we will wait for them all to finish. Finally, we will perform some checks on the result references. ``` for( Thread thread : threads ) thread.start(); logger.debug( "waiting for threads to finish ..." ); boolean done = false; while( !done ) { done = true; for( Thread thread : threads ) if( thread.isAlive() ) done = false; } for( int i = 0; i < resultRefs.length; i++ ) { assertTrue( "you've got the world messed, dawg!", myCondition(resultRefs[i]) ); ``` Here's the problem. Did you notice that nasty try-catch-throwable block? I just added that as a temporary hack so I could see what was going on. In runTest( String ) a few assertions are made, e.g., assertNotNull( null ), but since it is in a different thread, it doesn't cause the unit test to fail!!!! My guess is that we will need to somehow iterate over the threads array, check the status of each, and manually cause an assertion error if the thread terminated in a nasty way. What's the name of the method that gives this information (the stack trace of the dead thread).
Concurrency is one of those things that are very difficult to unit test. If you are just trying to test that the code inside each thread is doing what it is supposed to test, may be you should just test this code isolated of the context. If in this example the threads collaborate to reach a result, may be you can test that collaboration without using threads. That would be done by executing all the collaborative parts sequentially. If you want to test for race conditions and these kind of things, unit testing is not the best way. You will get tests that sometimes fail and sometimes don´t fail. To summarize, I think that may be your problem is that you are unit testing in a level too high. Hope this helps
The Google Testing Blog had an excellent article on this subject that's well worth reading: <http://googletesting.blogspot.com/2008/08/tott-sleeping-synchronization.html> It's written in Python, but I think the principles are directly transferable to Java.
How do I perform a Unit Test using threads?
[ "", "java", "multithreading", "unit-testing", "junit", "" ]
I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module. What are your thoughts on this?
If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This only really applies to c because as others have noted, c++ has namespaces to address this issue.
For C++, a better than static is to put it in an unnamed (anonymous) namespace. This is the preferred way to prevent pollution of the Global namespace. ``` namespace { void myLocalFunction() { // stuff } } ```
Do you declare your module specific functions as static?
[ "", "c++", "c", "static", "function", "" ]
I am using freeglut for opengl rendering... I need to draw an envelop looking like a cone (2D) that has to be filled with some color and some transparency applied. Is the freeglut toolkit equipped with such an inbuilt functionality to draw filled geometries(or some trick)? or is there some other api that has an inbuilt support for filled up geometries.. **Edit1:** just to clarify the 2D cone thing... the envelop is the graphical interpretation of the coverage area of an aircraft during interception(of an enemy aircraft)...that resembles a sector of a circle..i should have mentioned sector instead.. and glutSolidCone doesnot help me as i want to draw a filled sector of a circle...which i have already done...what remains to do is to fill it with some color... how to fill geometries with color in opengl? **Edit2:** All the answers posted to this questions can work for my problem in a way.. But i would definitely would want to know a way how to fill a geometry with some color. Say if i want to draw an envelop which is a parabola...in that case there would be no default glut function to actually draw a filled parabola(or is there any?).. So to generalise this question...how to draw a custom geometry in some solid color? **Edit3:** The answer that mstrobl posted works for GL\_TRIANGLES but for such a code: ``` glBegin(GL_LINE_STRIP); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); ``` which draws a square...only a wired square is drawn...i need to fill it with blue color. anyway to do it? if i put some drawing commands for a closed curve..like a pie..and i need to fill it with a color is there a way to make it possible... i dont know how its possible for GL\_TRIANGLES... but how to do it for any closed curve?
On Edit3: The way I understand your question is that you want to have OpenGL draw borders and anything between them should be filled with colors. The idea you had was right, but a line strip is just that - a strip of lines, and it does not have any area. You can, however, have the lines connect to each other to define a polygon. That will fill out the area of the polygon on a per-vertex basis. Adapting your code: ``` glBegin(GL_POLYGON); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 0.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(200.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 200.0, 0.0); glColor3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.0, 0.0); glEnd(); ``` Please note however, that drawing a polygon this way has two limitations: * The polygon must be convex. * This is a slow operation. But I assume you just want to get the job done, and this will do it. For the future you might consider just triangulating your polygon.
On the edit on colors: OpenGL is actually a state machine. This means that the current material and/or color position is used when drawing. Since you probably won't be using materials, ignore that for now. You want colors. ``` glColor3f(float r, float g, float b) // draw with r/g/b color and alpha of 1 glColor4f(float r, float g, float b, float alpha) ``` This will affect the colors of any vertices you draw, of any geometry you render - be it glu's or your own - after the glColorXX call has been executed. If you draw a face with vertices and change the color inbetween the glVertex3f/glVertex2f calls, the colors are interpolated. Try this: ``` glBegin(GL_TRIANGLES); glColor3f(0.0, 0.0, 1.0); glVertex3f(-3.0, 0.0, 0.0); glColor3f(0.0, 1.0, 0.0); glVertex3f(0.0, 3.0, 0.0); glColor3f(1.0, 0.0, 0.0); glVertex3f(3.0, 0.0, 0.0); glEnd(); ``` But I pointed at glColor4f already, so I assume you want to set the colors on a per-vertex basis. And you want to render using display lists. Just like you can display lists of vertices, you can also make them have a list of colors: all you need to do is enable the color lists and tell opengl where the list resides. Of course, they need to have the same outfit as the vertex list (same order). If you had ``` glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, vertices_); glDisableClientState(GL_VERTEX_ARRAY); ``` you should add colors this way. They need not be float; in fact, you tell it what format it should be. For a color list with 1 byte per channel and 4 channels (R, G, B and A) use this: ``` glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(3, GL_FLOAT, 0, vertices_); glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors_); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); ``` EDIT: Forgot to add that you then have to tell OpenGL which elements to draw by calling [glDrawElements](http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawelements.html).
How to draw a filled envelop like a cone on OpenGL (using GLUT)?
[ "", "c++", "opengl", "glut", "freeglut", "" ]
I have a class which looks something like this: ``` public class Test { private static final Object someObject = new Object(); public void doSomething() { synchronized (someObject) { System.out.println(someObject.toString()); } } } ``` Can I consider the object to be synchronized, or is there a problem since it is a static member? **Edit:** note that different threads might be accessing doSomething() and the object **must** be accessed in a thread-safe manner in that case.
By using a static object as your monitor object, only one thread using ANY instance of the Test class can get into the sync block. If the monitor object was not a static object, other threads holding different instances of the Test class could get into the sync block.
Here **someObject** is acting as a lock (monitor) for **all** objects of type Test. That is, if doSomething() is invoked on two separate instances of Test, one will block before the other completes. This is different from a synchronized method which which is mostly equivalent to the code above with **someObject** replaced by **this**. Changing **someObject** to non-static will result in per--instance locking. This is essentially the "private lock object" idiom as described in item 70 of *Effective Java*.
Static members need special synchronization blocks?
[ "", "java", "static", "synchronization", "locking", "" ]
This is something that comes up so often I almost stopped thinking about it but I'm almost certain that I'm not doing this the best way. The question: Suppose you have the following table ``` CREATE TABLE TEST_TABLE ( ID INTEGER, TEST_VALUE NUMBER, UPDATED DATE, FOREIGN_KEY INTEGER ); ``` What is the best way to select the TEST\_VALUE associated with the most recently updated row where FOREIGN\_KEY = 10? **EDIT:** Let's make this more interesting as the answers below simply go with my method of sorting and then selecting the top row. Not bad but for large returns the order by would kill performance. So bonus points: how to do it in a scalable manner (ie without the unnecessary order by).
Analytic functions are your friends ``` SQL> select * from test_table; ID TEST_VALUE UPDATED FOREIGN_KEY ---------- ---------- --------- ----------- 1 10 12-NOV-08 10 2 20 11-NOV-08 10 SQL> ed Wrote file afiedt.buf 1* select * from test_table SQL> ed Wrote file afiedt.buf 1 select max( test_value ) keep (dense_rank last order by updated) 2 from test_table 3* where foreign_key = 10 SQL> / MAX(TEST_VALUE)KEEP(DENSE_RANKLASTORDERBYUPDATED) ------------------------------------------------- 10 ``` You can also extend that to get the information for the entire row ``` SQL> ed Wrote file afiedt.buf 1 select max( id ) keep (dense_rank last order by updated) id, 2 max( test_value ) keep (dense_rank last order by updated) test_value , 3 max( updated) keep (dense_rank last order by updated) updated 4 from test_table 5* where foreign_key = 10 SQL> / ID TEST_VALUE UPDATED ---------- ---------- --------- 1 10 12-NOV-08 ``` And analytic approaches are generally pretty darned efficient. I should also point out that analytic functions are relatively new, so if you are on something earlier than 9.0.1, this may not work. That's not a huge population any more, but there are always a few folks stuck on old versions.
Either use a sub-query ``` WHERE updated = (SELECT MAX(updated) ...) ``` or select the TOP 1 record with ``` ORDER BY updated DESC ``` In Oracle syntax this would be: ``` SELECT * FROM ( SELECT * FROM test_table ORDER BY updated DESC ) WHERE ROWNUM = 1 ```
Best way to select the row with the most recent timestamp that matches a criterion
[ "", "sql", "oracle", "" ]
We've got an app with some legacy printer "setup" code that we are still using `PrintDlg` for. We use a custom template to allow the user to select which printer to use for various types of printing tasks (such as reports or drawings) along with orientation and paper size/source. It works on XP and 32-bit Vista, but on Vista x64 it gets a `CDERR_MEMLOCKFAILURE` via `CommDlgExtendedError()`. I've tried running it with just the bare-bones input in the `PRINTDLG` structure, but if the parameters include `PD_PRINTSETUP` or `PD_RETURNDEFAULT`, I get that error. Since the printer selection / page setup has been split into `PageSetupDlg` and `PrintDlgEx`, there is no apparent easy transition without changing a fair amount of code and/or changing completely how we present printing and printer setup to the user. Has anyone seen this problem on 64-bit Vista, and have you found any work-arounds? **Notes:** Application runs as Administrator due to other constraints
I found a related post on the Microsoft forums: [On Vista x64, DocumentProperties fails from UAC-elevated process](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2677398&SiteID=1) I've verified with a sample program that PrintDlg running as non-admin works.
I found a post on the Quicken Community forum: [Solution to Printing Problems Vista 64 Quicken 2008](http://www.quickencommunity.com/webx/Forums/Quicken%20Personal%20Finance%20Software%20Forum%20for%20Windows/Printing%20in%20Quicken/531/26?5), and the related FAQ: [What if I'm unable to print, or receive "Error communicating with printer"?](https://quicken.custhelp.com/cgi-bin/quicken.cfg/php/enduser/std_adp.php?p_faqid=5893) and the recommendation to use an emulation printer.
Using PrintDlg on Vista x64 does not work, works fine on 32 bit and XP
[ "", "c++", "visual-studio-2008", "printing", "vista64", "" ]
I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment. Here is as a code I use: ``` #include <iostream> #include <string> #include <fstream> #include <sys/time.h> #include <sys/wait.h> using namespace std; struct timeval first, second, lapsed; struct timezone tzp; int main(int argc, char* argv[])// query, file, num. of processes. { int pCount = 5; // process count gettimeofday (&first, &tzp); //start time pid_t* pID = new pid_t[pCount]; for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++) { pID[indexOfProcess]= fork(); if (pID[indexOfProcess] == 0) // child { // code only executed by child process // magic here // The End exit(0); } else if (pID[indexOfProcess] < 0) // failed to fork { cerr << "Failed to fork" << endl; exit(1); } else // parent { // if(indexOfProcess==pCount-1) and a loop with waitpid?? gettimeofday (&second, &tzp); //stop time if (first.tv_usec > second.tv_usec) { second.tv_usec += 1000000; second.tv_sec--; } lapsed.tv_usec = second.tv_usec - first.tv_usec; lapsed.tv_sec = second.tv_sec - first.tv_sec; cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec << " usec"<< endl << endl; } }//for }//main ```
I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest: ``` for (int i = 0; i < pidCount; ++i) { int status; while (-1 == waitpid(pids[i], &status, 0)); if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { cerr << "Process " << i << " (pid " << pids[i] << ") failed" << endl; exit(1); } } gettimeofday (&second, &tzp); //stop time ``` I've assumed that if the child process fails to exit normally with a status of 0, then it didn't complete its work, and therefore the test has failed to produce valid timing data. Obviously if the child processes are *supposed* to be killed by signals, or exit non-0 return statuses, then you'll have to change the error check accordingly. An alternative using wait: ``` while (true) { int status; pid_t done = wait(&status); if (done == -1) { if (errno == ECHILD) break; // no more child processes } else { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { cerr << "pid " << done << " failed" << endl; exit(1); } } } ``` This one doesn't tell you which process in sequence failed, but if you care then you can add code to look it up in the pids array and get back the index.
The simplest method is to do ``` while(wait() > 0) { /* no-op */ ; } ``` This will not work if `wait()` fails for some reason other than the fact that there are no children left. So with some error checking, this becomes ``` int status; [...] do { status = wait(); if(status == -1 && errno != ECHILD) { perror("Error during wait()"); abort(); } } while (status > 0); ``` See also the manual page `wait(2)`.
How to wait until all child processes called by fork() complete?
[ "", "c++", "linux", "gcc", "parallel-processing", "" ]
I am using iText to generate PDF invoices for a J2EE web application and included on the page is an image read from a URL constructed from the request URL. In the development and test environments this works fine, but in production I get a java.io.IOException: is not a recognized imageformat. If I paste the url into my browser then the correct image is returned, however the request is redirected from http to https. In my code if I hard code the redirect URL then the image is displayed correctly. So it seems that when retrieving the image using com.lowagie.text.Image.getInstance(URL), the redirects on the URL are not being followed. How can I output an image from a redirected URL using iText?
Well, If you ask for an image from a URL, it must actually point to the image. If the URL points to a web page that then redirects to another URL (or the return code from the URL is a redirection), then it is going to fail. This is essentially due to the getInstance() method understanding how to use the HTTP location protocol to get a file, but not understanding the HTTP protocol enough to be a HTTP client. You could just use the 'https' address, or you could store the image with your program and locate the as CFreiner suggests. If neither of these options are feasible, then your only real solution is to implement code to query the URL, check if it is a redirection and if it is follow the redirection.
Is there a reason you have to get this using the URL?? Do you have to match the image that the url is pointing to? What if it changes or gets removed? I am not sure of your requirement, but it may be easier to save the image from the url and place it somewhere within your project. Then you can add it to your pdf with: ``` Image.getInstance("yourimage.gif"); ```
How do I retrieve an image using iText when the URL has redirects?
[ "", "java", "pdf-generation", "itext", "" ]
Okay i am working on someone elses code. They do alot of this: ``` char description[256]; description[0]=0; ``` I know this would put a \0 in the first spot of the character array. But is this even a safe way to erase a string? Also visual studio keeps reporting memory leaks, and i've pretty much tied this done to the strings that are used. Ps. Yes i know about std::string, yes i use that. This isn't my code.
To *initialize* the string to 0, you could do: ``` char description[256] = {0}; ``` that will assign 0 to every element of the array. Just setting the first element to `0` (`'\0'`) does not erase it's contents. It doesn't even guarantee the entire string is set to the null character. As stated by others, you can't "erase" statically-created objects until the function closes, when it gets abandoned. Technically, it's not erased when the function is abandoned either - the stack pointer is merely changed. If you're paranoid about the data being erased, you should iterate through the array, setting each entry to `0` (`'\0'`).
Setting the first element of the char array to \0 is enough to ensure that 'description' is a properly formatted, actual string. Elements 1 thru 255 can all be garbage, so long as element 0 is 0, description is a zero-length string. You dont have to worry about memory leaks in the code posted above, because the array is allocated on the stack. Once it falls off the stack (goes out of scope), the char array is deallocated.
Erasing a Char[]
[ "", "c++", "c", "arrays", "string", "char", "" ]
Is there an Iterator implementation that merges multiple iterators? ``` class MergedIterator<T> implements Iterator<T> { MergedIterator(Iterator<T>... iters) .... } ``` And the next method should move on to `iters[1]` when `!iters[0].hasNext()` etc
I'd call that a ConcatenatedIterator myself - a MergedIterator should merge the results of several iterators e.g. based on sorting Naming aside, I'm sure there'll be an implementation in a 3rd party library somewhere. Just off to check [Google collections](http://code.google.com/p/google-collections/)... EDIT: Bingo - [Iterators.concat](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterators.html#concat(java.util.Iterator...))
Commons Collections [IteratorChain](http://commons.apache.org/collections/apidocs/org/apache/commons/collections/iterators/IteratorChain.html)
is there a merged iterator implementation?
[ "", "java", "iterator", "" ]
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I **don't** want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do `type(X) in (list, tuple)` but there may be other sequence types I'm not aware of, and no common base class. -N. **Edit**: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.
> The problem with all of the above > mentioned ways is that str is > considered a sequence (it's iterable, > has **getitem**, etc.) yet it's > usually treated as a single item. > > For example, a function may accept an > argument that can either be a filename > or a list of filenames. What's the > most Pythonic way for the function to > detect the first from the latter? Based on the revised question, it sounds like what you want is something more like: ``` def to_sequence(arg): ''' determine whether an arg should be treated as a "unit" or a "sequence" if it's a unit, return a 1-tuple with the arg ''' def _multiple(x): return hasattr(x,"__iter__") if _multiple(arg): return arg else: return (arg,) >>> to_sequence("a string") ('a string',) >>> to_sequence( (1,2,3) ) (1, 2, 3) >>> to_sequence( xrange(5) ) xrange(5) ``` This isn't guaranteed to handle *all* types, but it handles the cases you mention quite well, and should do the right thing for most of the built-in types. When using it, make sure whatever receives the output of this can handle iterables.
As of 2.6, use [abstract base classes](http://docs.python.org/library/abc.html#module-abc). ``` >>> import collections >>> isinstance([], collections.Sequence) True >>> isinstance(0, collections.Sequence) False ``` Furthermore ABC's can be customized to account for exceptions, such as not considering strings to be sequences. Here an example: ``` import abc import collections class Atomic(object): __metaclass__ = abc.ABCMeta @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(basestring) ``` After registration the **Atomic** class can be used with **isinstance** and **issubclass**: ``` assert isinstance("hello", Atomic) == True ``` This is still much better than a hard-coded list, because you only need to register the exceptions to the rule, and external users of the code can register their own. Note that in **Python 3** the syntax for specifying metaclasses changed and the `basestring` abstract superclass was removed, which requires something like the following to be used instead: ``` class Atomic(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(str) ``` If desired, it's possible to write code which is compatible both both Python 2.6+ *and* 3.x, but doing so requires using a slightly more complicated technique which dynamically creates the needed abstract base class, thereby avoiding syntax errors due to the metaclass syntax difference. This is essentially the same as what Benjamin Peterson's [six](http://pythonhosted.org/six/) module's[`with_metaclass()`](http://pythonhosted.org/six/#six.with_metaclass)function does. ``` class _AtomicBase(object): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented class Atomic(abc.ABCMeta("NewMeta", (_AtomicBase,), {})): pass try: unicode = unicode except NameError: # 'unicode' is undefined, assume Python >= 3 Atomic.register(str) # str includes unicode in Py3, make both Atomic Atomic.register(bytes) # bytes will also be considered Atomic (optional) else: # basestring is the abstract superclass of both str and unicode types Atomic.register(basestring) # make both types of strings Atomic ``` In versions before 2.6, there are type checkers in the`operator`module. ``` >>> import operator >>> operator.isSequenceType([]) True >>> operator.isSequenceType(0) False ```
Correct way to detect sequence parameter?
[ "", "python", "types", "sequences", "" ]
Ive recently been asked to recommend a .NET framework version to use in a (GUI based) project for an XP machine. Can anyone explain the differences between all the .NET versions? OR, Does anyone have a good reference to a site that details (briefly) the differences?
Jon Skeet's book *C# In Depth* has one section describing versions of .NET in details.
The only reason to **not** go for the latest version is that it can complicate deployment. .NET 2.0 is installed automatically via Windows Update, so you can expect it to be on the target computer when your deploy your application. .NET 3.5 is not being pushed automatically yet, so you need to distribute the framework with your application. This will probably change in the near future. If you are not concerned about deployment, then go for the latest version. The fact that you target the .NET 3.5 framework, does not mean that you have to use all the new technology. For instance you can still use Windows Forms instead of WPF, but that is another question.
Differences between .NET versions (predominantly c#)
[ "", "c#", ".net", "versions", "" ]
For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands: ``` .tables .dump ``` using the Python sqlite3 API. Is there anything like that?
You can fetch the list of tables and schemata by querying the SQLITE\_MASTER table: ``` sqlite> .tab job snmptarget t1 t2 t3 sqlite> select name from sqlite_master where type = 'table'; job t1 t2 snmptarget t3 sqlite> .schema job CREATE TABLE job ( id INTEGER PRIMARY KEY, data VARCHAR ); sqlite> select sql from sqlite_master where type = 'table' and name = 'job'; CREATE TABLE job ( id INTEGER PRIMARY KEY, data VARCHAR ) ```
In Python: ``` con = sqlite3.connect('database.db') cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursor.fetchall()) ``` Watch out for my other [answer](https://stackoverflow.com/a/33100538/236830). There is a much faster way using pandas.
List of tables, db schema, dump etc using the Python sqlite3 API
[ "", "python", "sqlite", "dump", "" ]
How can I make: DELETE FROM foo WHERE id=1 AND **bar not contains id==1** To elaborate, how can I remove a row with `id = 1`, from table `foo`, only if there is not a row in table `bar` with `id = 1`.
``` DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1) ``` I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.
using a join: ``` delete f from foo f left join bar b on f.id = b.id where f.id = 1 and b.id is null ```
In SQL, how to delete a row from one table if it doesn't have a corresponding row in another table?
[ "", "sql", "" ]
In my app I've got a thread which displays for some time "please wait" dialog window, sometimes it is a very tiny amout of time and there is some glitch while drawing UI (I guess). I get the exception "Thread was being aborted" and completly have no idea how get rid of it. I mean Catch that exception in some way, or in some other way hide it from user. This exception has got nothing to do with rest of my app and that error in any way doesn't affect it. Appears randomly and it is hard to recreate on a call. I tried in various ways to catch that exception by side of code which starts and stops thread with dialog window but it seems that error apparently is by side some other thread which dispalys window in my newly created thread. Here is a code sample, part of static class with useful stuff, of course I don't say that is good way to solve this kind of "busy" situation but I want to solve this problem. Thread.Sleep(500); or other try/catch improvments doesn't help me to avoid that thread exception. ``` public static bool alreadyBusy = false; public static BusyIndicator bi = new BusyIndicator(""); public static Thread backgroundOpertionThread; public static void showBusy(bool isBusy, System.Windows.Forms.Form hostform, string message) { Common.busyMessage = message; if (isBusy) { Common.alreadyBusy = true; backgroundOpertionThread = new Thread(new ThreadStart(showBusy)); Thread.Sleep(500); if (hostform != null) { hostform.Enabled = false; hostform.SuspendLayout(); } backgroundOpertionThread.Start(); } else { backgroundOpertionThread.Abort(); Thread.Sleep(500); Common.alreadyBusy = false; if (hostform != null) { hostform.Enabled = true; hostform.ResumeLayout(); } } } public static void showBusy() { BusyIndicator bir = new BusyIndicator(Common.busyMessage); bir.ShowDialog(); } ``` Any ideas?
Do **not** use Thread.Abort. This method is reserved for when the .NET runtime needs to forcibly kill threads in order to unload your program. You can only "safely" use this if you're about to unload an AppDomain and want to get rid of threads running in it first. To get rid of a thread, write it in cooperative mode. This means that the thread should periodically check some kind of flag, and if the flag is set, exit normally out of the thread method. To "kill" the thread, simply set the flag and wait for the thread to exit. You can use an Event-object or a simple boolean variable for this flag. But **do not use Thread.Abort**.
use [SafeThread](http://www.codeproject.com/KB/threads/SafeThread.aspx) and set ShouldReportThreadAbort to false to make the problem go away... a better solution would be to run this in the debugger with Debug >> Exceptions >> Thrown checked for all exception types, and figure out what is happening to abort your thread EDIT: thanks for posting the code sample, that makes the problem much easier to see. **DO NOT CALL THREAD.ABORT**
"Thread was being aborted" exception whilst displaying dialog
[ "", "c#", ".net", "multithreading", ".net-2.0", "" ]
I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so. so i have 2 methods 1) returns a json result . In that json result there is a property called data. that property is of type object but internally it's a list of anonymous variables 2) the method calls method 1 and checks if the returned jsonresult is ok. if i run the test and i break the debugger i can hover over the result and see the items in it. i just don't find a way to do so in code.(just using a foreach isn't possible because at the point i need it i'm not in the method that created the anonymous method)
I think you mean "anonymous type" everywhere you've said "anonymous variable" - but you can still iterate over the list with `foreach`, just declaring the iteration variable as type `object`: ``` foreach (object o in myList) { // Not sure what you're actually trying to do in here... } ``` If you need to check the contents, you can use the fact that anonymous types override `ToString` in a useful way. Your test can check the result of projecting each element to a string. Indeed, you could convert your result object to a sequence of strings quite easily: ``` var strings = ((IEnumerable) result).Cast<object>.Select(x => x.ToString()); ``` Then test `strings` possibly using [`SequenceEqual`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.sequenceequal.aspx).
Create an identical set of objects to the one you expect, then serialize both it and the result.Data of the action under unit test. Finally, compare the streams to see if they are identical.
Iterate through an anonymous variable in another scope than where it was created
[ "", "c#", ".net", "asp.net-mvc", "unit-testing", "" ]
I just happened to read [jQuery Intellisense Updates from Microsoft](http://www.west-wind.com/Weblog/posts/536756.aspx) and was wondering if there was any editor or eclipse plugin available which provides intellisense complete or code assist. Are there any?
I believe eclipse, with the **[Aptana](http://www.aptana.com/)** plugin, has some [JQuery support](http://www.aptana.com/blog/lorihc/jquery1.2.6_now_available). As mentionned [here](http://www.aptana.com/docs/index.php/Getting_started_with_Aptana_and_jQuery), intellisense is supported: >  5. Start coding. > > 1. As you type, notice that Code Assist is now active for the jQuery objects and functions that you use. > 2. Press ctrl+space at any time to activate Code Assist.
Why not Visual Studio/Web Developer 2008 (or did I miss something)? The [express edition](http://www.microsoft.com/express/vwd/) is free.
Any opensource Javascript editor/javascript eclipse plugin with code assist
[ "", "javascript", "jquery", "" ]
An [answer to one of my questions](https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code#231614) included the following line of code: ``` label = std::safe_string(name); // label is a std::string ``` The intent seems to be a wrapper around a string literal (so presumably no allocation takes place). I've never heard of `safe_string` and neither, apparently, has [google](http://www.google.com/search?q=%22std%3A%3Asafe_string%22) (nor could I find it in the 98 standard). Does anyone know what this is about?
After searching [google code search](http://www.google.com/codesearch) (I should have thought of this first...) I found this: ``` //tools-cgi.cpp string safe_string (const char * s) { return (s != NULL) ? s : ""; } ``` Which converts `NULL`s to zero length strings. Although this is not standard it's probably some sort of extension in a specific STL implementation which was referred to in the answer.
There is no standard safe\_string. The safe\_string you're seeing in that answerer's response is from what looks like a private STL extensions utility library. [Google for "stlext/stringext.h"](http://www.google.com/search?q=stlext%2Fstringext.h) and you'll see the same library referenced in a post on another forum.
What is std::safe_string?
[ "", "c++", "string", "" ]
I am interested in writing a simplistic navigation application as a pet project. After searching around for free map-data I have settled on the [US Census Bureau TIGER](http://www.census.gov/geo/www/tiger/tgrshp2007/tgrshp2007.html) 2007 Line/Shapefile map data. The data is split up into zip files for individual counties and I've downloaded a single counties map-data for my area. **What would be the best way to read in this map-data into a useable format?** How should I: * Read in these files * Parse them - Regular expression or some library that can already parse these Shapefiles? * Load the data into my application - Should I load the points directly into some datastructure in memory? Use a small database? I have no need for persistence once you close the application of the map data. The user can load the Shapefile again. **What would be the best way to render the map once I have read the in the Shapefile data?** Ideally I'd like to be able to read in a counties map data shapefile and render all the poly-lines onto the screen and allow rotating and scaling. How should I: * Convert lat/lon points to screen coordinates? - As far as I know the Shapefile uses longitude and latitude for its points. So obviously I'm going to have to convert these somehow to screen coordinates to display the map features. * Render the map data (A series of polylines for roads, boundaries, etc) in a way that I can easily rotate and scale the entire map? * Render my whole map as a series of "tiles" so only the features/lines within the viewing area are rendered? Ex. of TIGER data rendered as a display map: ![alt text](https://i.stack.imgur.com/mNJ9X.png) Anyone with some experience and insight into what the best way for me to read in these files, how I should represent them (database, in memory datastructure) in my program, and how I should render (with rotating/scaling) the map-data on screen would be appreciated. EDIT: To clarify, I do not want to use any Google or Yahoo maps API. Similarly, I don't want to use OpenStreetMap. I'm looking for a more from-scratch approach than utilizing those apis/programs. This will be a **desktop** application.
First, I recommend that you use the [2008 TIGER files](http://www.census.gov/geo/www/tiger/tgrshp2008/tgrshp2008.html). Second, as others point out there are a lot of projects out there now that already read in, interpret, convert, and use the data. Building your own parser for this data is almost trivial, though, so there's no reason to go through another project's code and try to extract what you need unless you plan on using their project as a whole. ## If you want to start from the lower level **Parsing** Building your own TIGER parser (reasonably easy - just a DB of line segments), and building a simple render on top of that (lines, polygons, letters/names) is also going to be fairly easy. You'll want to look at various [map projection types](http://www.colorado.edu/geography/gcraft/notes/mapproj/mapproj_f.html) for the render phase. The most frequently used (and therefore most familiar to users) is the [Mercator projection](http://www.colorado.edu/geography/gcraft/notes/mapproj/mapproj_f.html) - it's fairly simple and fast. You might want to play with supporting other projections. This will provide a bit of 'fun' in terms of seeing how to project a map, and how to reverse that projection (say a user clicks on the map, you want to see the lat/lon they clicked - requires reversing the current projection equation). **Rendering** When I developed my renderer I decided to base my window on a fixed size (embedded device), and a fixed magnification. This meant that I could center the map at a lat/lon, and with the center pixel=center lat/lon at a given magnification, and given the mercator projection I could calculate which pixel represented each lat/lon, and vice-versa. Some programs instead allow the window to vary, and instead of using magnification and a fixed point, they use two fixed points (often the upper left and lower right corners of a rectangle defining the window). In this case it becomes trivial to determine the pixel to lat/lon transfer - it's just a few interpolation calculations. Rotating and scaling make this transfer function a little more complex, but shouldn't be considerably so - it's still a rectangular window with interpolation, but the window corners don't need to be in any particular orientation with respect to north. This adds a few corner cases (you can turn the map inside out and view it as if from inside the earth, for instance) but these aren't onerous, and can be dealt with as you work on it. Once you've got the lat/lon to pixel transfer done, rendering lines and polygons is fairly simple except for normal graphics issues (such as edges of lines or polygons overlapping inappropriately, anti-aliasing, etc). But rendering a basic ugly map such as it done by many open source renderers is fairly straightforward. You'll also be able to play with distance and great circle calculations - for instance a nice rule of thumb is that every degree of lat or lon at the equator is approximately 111.1KM - but one changes as you get closer to either pole, while the other continues to remain at 111.1kM. **Storage and Structures** How you store and refer to the data, however, depends greatly on what you plan on doing with it. A lot of difficult problems arise if you want to use the same database structure for demographics vs routing - a given data base structure and indexing will be fast for one, and slow for the other. Using zipcodes and loading only the nearby zipcodes works for small map rendering projects, but if you need a route across the country you need a different structure. Some implementations have 'overlay' databases which only contain major roads and snaps routes to the overlay (or through multiple overlays - local, metro, county, state, country). This results in fast, but sometimes inefficient routing. **Tiling** Tiling your map is actually not easy. At lower magnifications you can render a whole map and cut it up. At higher magnifications you can't render the whole thing at once (due to memory/space constraints), so you have to slice it up. Cutting lines at boundaries of tiles so you can render individual tiles results in less than perfect results - often what is done is lines are rendered beyond the tile boundary (or, at least the data of the line end is kept, though rendering stops once it finds it's fallen off the edge) - this reduces error that occurs with lines looking like they don't quite match as they travel across tiles. You'll see what I'm talking about as you work on this problem. It isn't trivial to find the data that goes into a given tile as well - a line may have both ends outside a given tile, but travel across the tile. You'll need to consult graphics books about this ([Michael Abrash's book is the seminal reference](https://www.jagregory.com/abrash-black-book/), freely available now at the preceding link). While it talks mostly about gaming, the windowing, clipping, polygon edges, collision, etc all apply here. ## However, you might want to play at a higher level. Once you have the above done (either by adapting an existing project, or doing the above yourself) you may want to play with other scenarios and algorithms. **Reverse geocoding is reasonably easy.** Input lat/lon (or click on map) and get the nearest address. This teaches you how to interpret addresses along line segments in TIGER data. **Basic geocoding is a hard problem.** Writing an address parser is a useful and interesting project, and then converting that into lat/lon using the TIGER data is non-trivial, but a lot of fun. Start out simple and small by requiring exact name and format matching, and then start to look into 'like' matching and phonetic matching. There's a lot of research in this area - look at search engine projects for some help here. **Finding the shortest path between two points is a non-trivial problem.** There are many, many algorithms for doing that, most of which are patented. I recommend that if you try this go with an easy algorithm of your own design, and then do some research and compare your design to the state of the art. It's a lot of fun if you're into graph theory. **Following a path and pre-emptively giving instructions** is not as easy as it looks on first blush. Given a set of instructions with an associated array of lat/lon pairs, 'follow' the route using external input (GPS, or simulated GPS) and develop an algorithm that gives the user instructions as they approach each real intersection. Notice that there are more lat/lon pairs than instructions due to curving roads, etc, and you'll need to detect direction of travel and so forth. Lots of corner cases you won't see until you try to implement it. **Point of interest search.** This one is interesting - you need to find the current location, and all the points of interest (not part of TIGER, make your own or get another source) within a certain distance (as the crow flies, or harder - driving distance) of the origin. This one is interesting in that you have to convert the POI database into a format that is easy to search in this circumstance. You can't take the time to go through millions of entries, do the distance calculation (sqrt(x^2 + y^2)), and return the results. You need to have some method or algorithm to cut the amount of data down first. **Traveling salesman.** Routing with multiple destinations. Just a harder version of regular routing. You can find a number of links to many projects and sources of information on this subject [here](http://delicious.com/stienman/gis). Good luck, and please publish whatever you do, no matter how rudimentary or ugly, so others can benefit! -Adam
[SharpMap](http://www.codeplex.com/SharpMap) is an open-source .NET 2.0 mapping engine for WinForms and ASP.NET. This may provide all the functionality that you need. It deals with most common GIS vector and raster data formats including ESRI shapefiles.
What is the best way to read, represent and render map data?
[ "", "java", ".net", "graphics", "rendering", "maps", "" ]
Is it less efficient to use TEXT than varchar in an SQL database? If so why? If not why would you not just always use TEXT? I'm not targetting a specific database here but oracle is probably the most relevant, although I'm testing on MySQL for the time being as part of a proof of concept.
From Microsoft [here](http://msdn.microsoft.com/en-us/library/ms187993.aspx) > ntext, text, and image data types will > be removed in a future version of > Microsoft SQL Server. Avoid using > these data types in new development > work, and plan to modify applications > that currently use them. Use > nvarchar(max), varchar(max), and > varbinary(max) instead. When you use `varchar(max)` over text you can use it in the `WHERE` clause, because they work the same as their smaller counterparts, `varchar,nvarchar and varbinary`. Below is a small list of what should be used as opposed what was to be used: * Use varchar(max) instead of text * Use nvarchar(max) instead of ntext * Use varbinary(max) instead of image
[PostgreSQL documentation says](http://www.postgresql.org/docs/current/static/datatype-character.html): > Tip: There are no performance differences between these three types, apart from increased storage size when using the blank-padded type, and a few extra cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, it has no such advantages in PostgreSQL. In most situations text or character varying should be used instead.
Databases: Are "TEXT" fields less efficient than "varchar"?
[ "", "sql", "variables", "performance", "" ]
I have the following code that sets a cookie: ``` string locale = ((DropDownList)this.LoginUser.FindControl("locale")).SelectedValue; HttpCookie cookie = new HttpCookie("localization",locale); cookie.Expires= DateTime.Now.AddYears(1); Response.Cookies.Set(cookie); ``` However, when I try to read the cookie, the Value is Null. The cookie exists. I never get past the following if check: ``` if (Request.Cookies["localization"] != null && !string.IsNullOrEmpty(Request.Cookies["localization"].Value)) ``` Help?
The check is done after a post back? If so you should read the cookie from the Request collection instead. The cookies are persisted to the browser by adding them to Response.Cookies and are read back from Request.Cookies. The cookies added to Response can be read only if the page is on the same request.
The most likely answer is seen on [this post](https://stackoverflow.com/questions/456807/asp-mvc-cookies-not-persisting/590258#590258) > When you try to check existence of a cookie using Response object rather than Reqest, ASP.net automatically creates a cookie. **Edit:** As a note, I ended up writing software that needed to check the existence of cookies that ASP.NET makes a nightmare due to their cookie API. I ended up writing a conversion process that takes cookies from the request and makes my state object. At the end of the request I then translate my state object back to cookies and stuff them in the response (if needed). This alleviated trying to figure out if cookies are in the response, to update them instead, avoiding creating of pointless cookies etc.
Cookie loses value in ASP.net
[ "", "c#", "asp.net", "cookies", "" ]
I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically added object tag for Internet Explorer seems to do nothing at all. The object tag needs the following attributes to function properly. `id ="SomeId" classid = "CLSID:{GUID}" codebase = "http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1"` Even a general working idea or method would be nice. Thanks!
I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine. ``` // something akin to this: document.getElementById(myDivId).innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc"; ``` That should work, it does just fine for me - I use it to embed Windows Media Player in a page. --- UPDATE: You would run the above code after the page loads via an event handler that either runs on the page's load event or maybe in response to a user's click. The only thing you need to do is have an empty DIV tag or some other type of tag that would allow us to inject the HTML code via that element's `innerHTML` property. --- UPDATE: Apparently you need more help than I thought you needed? Maybe this will help: Have your BODY tag look like this: `<body onload="loadAppropriatePlugin()">` Have somewhere in your page, where you want this thing to load, an empty DIV tag with an `id` attribute of something like "Foo" or whatever. Have code like this in a `<script>` tag in your `<head>` section: ``` function getIEVersion() { // or something like this var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); return ((msie > 0) ? parseInt(ua.substring(msie+5, ua.indexOf(".", msie))) : 0); } function loadAppropriatePlugin() { if(getIEVersion() != 0) { // this means we are in IE document.getElementById("Foo").innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc"; } else { // if you want to maybe do the same for FF and load that stuff... } } ``` Does that help?
``` var object = document.createelement('object') object.setAttribute('id','name') object.setAttribute('clssid','CLSID:{}') ``` And the same for other parameters.
How can I dynamically add an <object> tag with JavaScript in IE?
[ "", "javascript", "internet-explorer", "dynamic-data", "object-tag", "" ]
I'm relatively new to NHibernate, but have been using it for the last few programs and I'm in love. I've come to a situation where I need to aggregate data from 4-5 databases into a single database. Specifically it is serial number data. Each database will have its own mapping file, but ultimately the entities all share the same basic structure (Serial class). I understand NHibernate wants a mapping per class, and so my initial thought was to have a base Serial Class and then inherit from it for each different database and create a unique mapping file (the inherited class would have zero content). This should work great for grabbing all the data and populating the objects. What I would then like to do is save these inherited classes (not sure what the proper term is) to the base class table using the base class mapping. The problem is I have no idea how to force NHIbernate to use a specific mapping file for an object. Casting the inherited class to the base class does nothing when using 'session.save()' (it complains of no mapping). Is there a way to explicitly specify which mapping to use? Or is there just some OOP principal I am missing to more specifically cast an inherited class to base class? Or is this idea just a bad one. All of the inheritance stuff I could find with regards to NHibernate (Chapter 8) doesn't seem to be totally applicable to this function, but I could be wrong (the table-per-concrete-class looks maybe useful, but I can't wrap my head around it totally with regards to how NHibernate figures out what to do).
I don't know if this'll help, but I wouldn't be trying to do that, basically. Essentially, I think you're possibly suffering from "golder hammer" syndrome: when you have a REALLY REALLY nice hammer (i.e. Hibernate (and I share your opinion on it; it's a MAGNIFICENT tool)), everything looks like a nail. I'd generally try to simply have a "manual conversion" class, i.e. one which has constructors which take the hibernate classes for your individual Serial Classes and which simply copies the data over to its own specific format; then Hibernate can simply serialize it to the (single) database using its own mapping. Effectively, the reason why I think this is a better solution is that what you're effectively trying to do is have asymmetric serialization in your class; i.e. read from one database in your derived class, write to another database in your base class. Nothing too horrible about that, really, except that it's fundamentally a unidirectional process; if you really want conversion from one database to the other, simply do the conversion, and be over with it.
This might help; [Using NHibernate with Multiple Databases](http://www.codeproject.com/KB/aspnet/NHibernateMultipleDBs.aspx) From the article; > Introduction > > ... > described using NHibernate with > ASP.NET; it offered guidelines for > communicating with a single database. > **But it is sometimes necessary to > communicate with multiple databases > concurrently.** For NHibernate to do > this, a session factory needs to exist > for each database that you will be > communicating with. But, as is often > the case with multiple databases, some > of the databases are rarely used. So > it may be a good idea to not create > session factories until they're > actually needed. This article picks up > where the previous NHibernate with > ASP.NET article left off and describes > the implementation details of this > simple-sounding approach. Although the > previous article focused on ASP.NET, > the below suggestion is supported in > both ASP.NET and .NET. > > ... > > **The first thing to do when working > with multiple databases is to > configure proper communications. > Create a separate config file for each > database, put them all into a central > config folder, and then reference them > from the web/app.config.** > > ...
NHibernate: One base class, several mappings
[ "", "c#", "nhibernate", "oop", "nhibernate-mapping", "" ]
Can someone explain the main benefits of different types of references in C#? * Weak references * Soft references * Phantom references * Strong references. We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.
Soft and phantom references come from Java, I believe. A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference. If there is an analog to SoftReference in C#, I don't know what it is. Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected once all strong references have gone out of scope. They can be useful for holding on to large objects that are expensive to initialize, but should be available for garbage collection if they are not actively in use. Whether or not this will be useful in reducing the memory consumption of your application will depend completely on the specifics of the application. For example, if you have a moderate number of cached objects hanging around that may or may not be reused in the future, weak references could help improve the memory consumption of the caches. However, if the app is working with a very large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.
MSDN has a good explanation of [weak references](http://msdn.microsoft.com/en-us/library/ms404247.aspx). The key quote is at the bottom where it says: > **Avoid using weak references as an** > **automatic solution to memory** > **management problems**. Instead, develop > an effective caching policy for > handling your application's objects. Every time I've seen a WeakReference in the wild, it's been used as an automatic solution to memory management problems. There are likely better solutions to your application's problems.
Weak reference benefits
[ "", "c#", "winforms", "memory", "reference", "weak-references", "" ]
Greetings, I have a particular object which can be constructed from a file, as such: ``` public class ConfigObj { public ConfigObj(string loadPath) { //load object using .Net's supplied Serialization library //resulting in a ConfigObj object ConfigObj deserializedObj = VoodooLoadFunction(loadpath); //the line below won't compile this = thisIsMyObj; } } ``` I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are: * Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable. * Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y. I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?
Your second option is what is called a [factory method](http://en.wikipedia.org/wiki/Factory_method_pattern) and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.
There's nothing wrong with having a static method instead of a constructor. In fact, it has a [number of advantages](https://stackoverflow.com/questions/194496/static-method-or-instance-constructor).
Best Practice for Loading Object from Serialized XML in C#
[ "", "c#", ".net", "serialization", "xml-serialization", "" ]
Does anyone know what this means. Getting this in C# winforms applications: > Not a legal OleAut date
It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a **double**. Start by looking for any uses of the methods: [DateTime.FromOADate](http://msdn.microsoft.com/en-us/library/system.datetime.fromoadate.aspx) [DateTime.ToOADate](http://msdn.microsoft.com/en-us/library/system.datetime.tooadate.aspx)
An OADate is represented as a double value whose value is the number of days from midnight on 30 december 1899 (negative values representing earlier dates). This exception is thrown when trying to convert a value that is outside the valid range of Ole Automation dates to/from a .NET DateTime value (methods DateTime.FromOADate and DateTime.ToOADate - which are also used implicitly for COM Interop). I believe to be valid for conversion to an OADate the .NET DateTime value needs to be strictly greater than 01/01/0100. To convert from OADate to a .NET DateTime value, the double value needs to be strictly greater than -657435 (= 01/01/0100) and strictly less than 2958466.0 (01/01/10000).
Meaning of exception in C# app: "Not a legal OleAut date"?
[ "", "c#", "winforms", "datetime", "" ]
Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way. I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user and passed onto the function. Here is my basic read in function: ``` template <class T, class U> void get_list(vector<T>& v, const char *inputFile, U) { ifstream myFile; T object; myFile.open("inputFile") while(!myFile.eof()) { myFile >> object; insert(v, object, U) } } ``` insert is just another function that will go through and insert the data into my data structure. I just want to make sure this is the best way to pass that data on if it will even work.
It looks like it will work fine, and I would say this is probably the best way to do it. But why are you asking here instead of just testing it yourself?
You made the old mistake of testing against eof in the condition. EOF is not set until you try and read past the end of file. So this method will insert one extra value into the vector that you don't want. ``` template <class T, class U> void get_list(vector<T>& v, const char *inputFile, U) { ifstream myFile("inputFile"); // Why hard code this? // When you pass inputFile as a parameter? T object; while(myFile >> object) // Get the object here. // If it fails because of eof() or other // It will not get inserted. { insert(v, object, U) } } ```
C++ Opening a file and inputting data to a class object
[ "", "c++", "class", "input", "ifstream", "" ]
In my database application I sometimes have to deal with `null` strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using `JTextField` for example - cannot handle null strings. (`.setText(null)` fails) (**EDIT:** I just noticed that `JTextField` actually accepts a `null` string, but the question remains for all other cases where unexpected `null` values can lead to problems.) The null values have no special meaning, they can (must) be treated as empty strings. What is the best practice to deal with this problem? *Unfortunatly I cannot change the database*. * Checking every value if it is `null` before calling `setText()`? * Adding a try-catch handler to every `setText()` call? * Introducing a static method which filters all `null` strings? * Replace all `null` values to empty strings immediatly after reading from the database? * ... [your suggestions]
If you are using any ORM tool or somehow you map your DB fields to Java bean you can allways have: ``` public void setFoo(String str) { this.foo = str != null ? str : ""; } ```
From a SQL angle try: ``` select ISNULL(column_name,'') from ... ```
Best practice for handling null strings from database (in Java)
[ "", "java", "database", "swing", "" ]
How can I replace Line Breaks within a string in C#?
Use replace with `Environment.NewLine` ``` myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ; ``` As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of [new line control characters](http://en.wikipedia.org/wiki/Newline).
The solutions posted so far either only replace `Environment.NewLine` or they fail if the replacement string contains line breaks because they call `string.Replace` multiple times. Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks. ``` string result = Regex.Replace(input, @"\r\n?|\n", replacementString); ```
Replace Line Breaks in a String C#
[ "", "c#", ".net", "string", "" ]
For a simple linked list in which random access to list elements is not a requirement, are there any significant advantages (performance or otherwise) to using `std::list` instead of `std::vector`? If backwards traversal is required, would it be more efficient to use `std::slist` and `reverse()` the list prior to iterating over its elements?
As usual the best answer to performance questions is to [profile](https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code) both implementations for your use case and see which is faster. In general if you have insertions into the data-structure (other than at the end) then `vector` may be slower, otherwise in most cases `vector` is expected to perform better than `list` if only for [data locality issues](http://en.wikipedia.org/wiki/Locality_of_reference), this means that if two elements that are adjacent in the data-set are adjacent in memory then the next element will already be in the processor's cache and will not have to page fault the memory into the cache. Also keep in mind that the space overhead for a `vector` is constant (3 pointers) while the space overhead for a `list` is paid for each element, this also reduces the number of full elements (data plus overhead) that can reside in the cache at any one time.
Default data structure to think of in C++ is the **Vector**. Consider the following points... **1] Traversal:** List nodes are scattered everywhere in memory and hence list traversal leads to ***cache misses***. But traversal of vectors is smooth. **2] Insertion and Deletion:** Average 50% of elements must be shifted when you do that to a Vector but caches are very good at that! But, with lists, you need to ***traverse* to the point of insertion/deletion...** so again... cache misses! And surprisingly vectors win this case as well! **3] Storage:** When you use lists, there are 2 pointers per elements(forward & backward) so a List is much bigger than a Vector! Vectors need just a little more memory than the actual elements need. Yout should have a reason not to use a vector. --- Reference: I learned this in a talk of The Lord Bjarne Stroustrup: <https://youtu.be/0iWb_qi2-uI?t=2680>
Relative performance of std::vector vs. std::list vs. std::slist?
[ "", "c++", "data-structures", "stl", "performance", "linked-list", "" ]
How can I dynamically invoke a class method in PHP? The class method is not static. It appears that ``` call_user_func(...) ``` only works with static functions? Thanks.
It works both ways - you need to use the right syntax ``` // Non static call call_user_func( array( $obj, 'method' ) ); // Static calls call_user_func( array( 'ClassName', 'method' ) ); call_user_func( 'ClassName::method' ); // (As of PHP 5.2.3) ```
Option 1 ``` // invoke an instance method $instance = new Instance(); $instanceMethod = 'bar'; $instance->$instanceMethod(); // invoke a static method $class = 'NameOfTheClass'; $staticMethod = 'blah'; $class::$staticMethod(); ``` Option 2 ``` // invoke an instance method $instance = new Instance(); call_user_func( array( $instance, 'method' ) ); // invoke a static method $class = 'NameOfTheClass'; call_user_func( array( $class, 'nameOfStaticMethod' ) ); call_user_func( 'NameOfTheClass::nameOfStaticMethod' ); // (As of PHP 5.2.3) ``` Option 1 is faster than Option 2 so try to use them unless you don't know how many arguments your going to be passing to the method. --- Edit: Previous editor did great job of cleaning up my answer but removed mention of call\_user\_func\_array which is different then call\_user\_func. PHP has ``` mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) ``` <http://php.net/manual/en/function.call-user-func.php> AND ``` mixed call_user_func_array ( callable $callback , array $param_arr ) ``` <http://php.net/manual/en/function.call-user-func-array.php> Using call\_user\_func\_array is orders of magnitude slower then using either option listed above.
How do I dynamically invoke a class method in PHP?
[ "", "php", "callback", "" ]
I have a C#/.NET program that can run both as a console application and as a service. Currently I give it a command-line option to start as a console application, but I would like to avoid that. Is it possible to programmatically detect whether my program is being started as a service? If it was pure Win32, I could try starting as a service with StartServiceCtrlDispatcher and fall back to console if it returned ERROR\_FAILED\_SERVICE\_CONTROLLER\_CONNECT, but System.ServiceProcess.ServiceBase.Run() pops up an errordialog if it fails and then just returns without signaling an error to the program. Any ideas?
Rasmus, [this is the earlier question](https://stackoverflow.com/questions/200163/am-i-running-as-a-service#200183). From the answers it seems the most popular way is to use a simple command line option, or try accessing the Console object in a try catch block (in a Service the Console is not attached to the process and trying to access it throws an exception). Or if you're having trouble testing/debugging the service, move code into a separate dll assembly and create a seprate test harness (winforms/console etc). (Just noticed that Jonathan has added his solution to the end of the question.)
[Environment.UserInteractive](http://msdn.microsoft.com/en-us/library/system.environment.userinteractive.aspx) will do the magic.
C#/.NET: Detect whether program is being run as a service or a console application
[ "", "c#", ".net", "service", "" ]
Given an amount of days, say 25, convert it into a duration text such as "3 Weeks, 4 Days" C# and F# solutions would both be great if the F# variation offers any improvement over C#. Edit: The solution should expand past weeks to include months and years. Bonus points for including centuries and so on. Extra bonus if it is somewhat configurable, meaning you can tell the method to exclude the normalization of weeks.
This is a recursive solution. Note that a duration only really makes sense measured against a particular point in time on a given calendar because month and year lengths vary. But here is a simple solution assuming fixed lengths: ``` let divmod n m = n / m, n % m let units = [ ("Centuries", TimeSpan.TicksPerDay * 365L * 100L ); ("Years", TimeSpan.TicksPerDay * 365L); ("Weeks", TimeSpan.TicksPerDay * 7L); ("Days", TimeSpan.TicksPerDay) ] let duration days = let rec duration' ticks units acc = match units with | [] -> acc | (u::us) -> let (wholeUnits, ticksRemaining) = divmod ticks (snd u) duration' ticksRemaining us (((fst u), wholeUnits) :: acc) duration' (TimeSpan.FromDays(float days).Ticks) units [] ```
``` String.Format("{0} Weeks, {1} days", days / 7, days % 7); ```
Converting Days into Human Readable Duration Text
[ "", "c#", "f#", "" ]
As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).
Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name. ``` // myclass.h class MyClass { public: MyClass(); void foo(); // ... }; extern MyClass g_MyClassInstance; // myclass.cpp MyClass g_MyClassInstance; MyClass::MyClass() { // ... } ``` Now, in any other module just include `myclass.h` and use `g_MyClassInstance` as usual. If you need to make more, there is a constructor ready for you to call.
First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler). But to achieve the affect you want you can use a variation of the Singleton. Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be destroyed in the reverse order of creation (so this guarantees the destructor will be used). ``` class MyVar { public: static MyVar& getGlobal1() { static MyVar global1; return global1; } static MyVar& getGlobal2() { static MyVar global2; return global2; } // .. etc } ```
Global instance of a class in C++
[ "", "c++", "singleton", "" ]
I teach a C++ course using Visual Studio. One of my students has a Mac and was looking for an IDE to use on his machine. What would be good to recommend?
[Xcode](http://developer.apple.com/tools/xcode/) which is part of the MacOS Developer Tools is a great IDE. There's also [NetBeans](http://www.netbeans.org) and [Eclipse](http://www.eclipse.org) that can be configured to build and compile C++ projects. [Clion](https://www.jetbrains.com/clion/) from JetBrains, also is available now, and uses Cmake as project model.
Emacs! Eclipse might work too.
C++ IDE for Macs
[ "", "c++", "macos", "ide", "" ]
I have a third party JavaScript plug-in but including the file breaks IntelliSense for jQuery amongst other things. The only way I can get IntelliSense back working with jQuery is by commenting out the plug-in. Is there a way I can hide the plug-in file from the IntelliSense parser?
Service Pack 1 added the following feature: If you "anyfile.js" and "anyfile-vsdoc.js" in the same directory, then any references to "anyfile.js" will automagically be converted to a reference to "anyfile-vsdoc.js" behind the scenes. Add an empty file next to your plugin with "-vsdoc" appended to the filename. That should "hide" the plug-in from the external javascript processor.
You could always load it from your code-behind instead of the scriptmanager in your aspx/master. That way the IntelliSense doesn't know it's there. Using ScriptManager.RegisterClientScriptInclude(..).
Is there any way to 'hide' a JavaScript file from IntelliSense in Visual Studio 2008?
[ "", "asp.net", "javascript", "jquery", "intellisense", "" ]
On the PHP website, the only real checking they suggest is using `is_uploaded_file()` or `move_uploaded_file()`, [here](http://ca.php.net/manual/en/features.file-upload.php). Of course you usually don't want user's uploading any type of file, for a variety of reasons. Because of this, I have often used some "strict" mime type checking. Of course this is very flawed because often mime types are wrong and users can't upload their file. It is also very easy to fake and/or change. And along with all of that, each browser and OS deals with them differently. Another method is to check the extension, which of course is even easier to change than mime type. If you only want images, using something like `getimagesize()` will work. What about other types of files? PDFs, Word documents or Excel files? Or even text only files? **Edit:** If you don't have [mime\_content\_type](http://php.net/manual/en/function.mime-content-type.php) or [Fileinfo](http://php.net/manual/en/function.finfo-file.php) and system("file -bi $uploadedfile") gives you the wrong file type, what other options are there?
Take a look at [mime\_content\_type](http://php.net/manual/en/function.mime-content-type.php) or [Fileinfo](http://php.net/manual/en/function.finfo-file.php). These are built-in PHP commands for determining the type of a file by looking at the contents of the file. Also check the comments on the above two pages, there are some other good suggestions. Personally I've had good luck using something that's essentially `system("file -bi $uploadedfile")`, but I'm not sure if that's the best method.
IMHO, all MIME-type checking methods are useless. Say you've got which should have MIME-type `application/pdf`. Standard methods are trying to find something that looks like a PDF header (`%PDF-` or smth. like that) and they will return 'Okay, seems like this is a PDF file' on success. But in fact this doesn't means anything. You can upload a file containing only `%PDF-1.4` and it will pass MIME-check. I mean if the file has an expected MIME-type - it will always pass the MIME-type check otherwise the result is undefined.
How to check file types of uploaded files in PHP?
[ "", "php", "validation", "file-upload", "mime-types", "" ]
I created a custom login page using Forms Authentication and using a sQL DB to store user data. I am able to create a session variable from the username, but wondering if it is possible to pull a separate field and create a session variable based on that. I would like the session variable to be based off a SalesNumber a 5 digit decimal field. Please give me any comments or suggestions. ``` cmd = new SqlCommand("Select pwd,SalesNumber from users where uname=@userName", conn); cmd.Parameters.Add("@userName", System.Data.SqlDbType.VarChar, 25); cmd.Parameters["@userName"].Value = userName; Session["userName"] = userName; ``` Thanks....
Also keep in mind you can store an entire object in the session instead of seperate variables: ``` UserObject user = DAL.GetUserObject(userName); Session["CurrentUser"] = user; // Later... UserObject user = Session["CurrentUser"] as UserObject; // ... ``` To add on, you could wrap it in a nice property: ``` private UserObject CurrentUser { get { return this.Session["CurrentUser"] as UserObject; } set { this.Session["CurrentUser"] = value; } } ```
When you get the SalesNumber from your database query, just use ``` Session["SalesNumber"] = <the value of the SalesNumber column from the query> ``` Or is there something else I'm missing in the question...?
Asp.net Session Variable from SQL DB
[ "", "c#", "asp.net", "" ]
Let's say I have an html form. Each input/select/textarea will have a corresponding `<label>` with the `for` attribute set to the id of it's companion. In this case, I know that each input will only have a single label. Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?
First, scan the page for labels, and assign a reference to the label from the actual form element: ``` var labels = document.getElementsByTagName('LABEL'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor != '') { var elem = document.getElementById(labels[i].htmlFor); if (elem) elem.label = labels[i]; } } ``` Then, you can simply go: ``` document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!'; ``` No need for a lookup array :)
If you are using jQuery you can do something like this ``` $('label[for="foo"]').hide (); ``` If you aren't using jQuery you'll have to search for the label. Here is a function that takes the element as an argument and returns the associated label ``` function findLableForControl(el) { var idVal = el.id; labels = document.getElementsByTagName('label'); for( var i = 0; i < labels.length; i++ ) { if (labels[i].htmlFor == idVal) return labels[i]; } } ```
Find html label associated with a given input
[ "", "javascript", "html", "label", "" ]
Given a class: ``` from django.db import models class Person(models.Model): name = models.CharField(max_length=20) ``` Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example: ``` # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_value = 'B' # ... that you can run the equivalent of this? Person.objects.filter(filter_by=filter_value) # ... which will throw an exception, since `filter_by` is not # an attribute of `Person`. ```
Python's argument expansion may be used to solve this problem: ``` kwargs = { '{0}__{1}'.format('name', 'startswith'): 'A', '{0}__{1}'.format('name', 'endswith'): 'Z' } Person.objects.filter(**kwargs) ``` This is a very common and useful Python idiom.
A simplified example: In a Django survey app, I wanted an HTML select list showing registered users. But because we have 5000 registered users, I needed a way to filter that list based on query criteria (such as just people who completed a certain workshop). In order for the survey element to be re-usable, I needed for the person creating the survey question to be able to attach those criteria to that question (don't want to hard-code the query into the app). The solution I came up with isn't 100% user friendly (requires help from a tech person to create the query) but it does solve the problem. When creating the question, the editor can enter a dictionary into a custom field, e.g.: ``` {'is_staff':True,'last_name__startswith':'A',} ``` That string is stored in the database. In the view code, it comes back in as `self.question.custom_query` . The value of that is a string that *looks* like a dictionary. We turn it back into a *real* dictionary with eval() and then stuff it into the queryset with \*\*kwargs: ``` kwargs = eval(self.question.custom_query) user_list = User.objects.filter(**kwargs).order_by("last_name") ```
In Django, how does one filter a QuerySet with dynamic field lookups?
[ "", "python", "django", "django-models", "" ]
pdb and winpdb both seem to be missing this essential (to me) feature. I saw something suggesting WingIDE has it but I'd prefer a solution that is free, and if I do have to pay, I'd prefer to pay for something that is better than Wing.
Please look what pydev in eclipse offers...
You should check out [Eric4](http://eric-ide.python-projects.org/) It's a very good Python IDE with a builtin debugger. The debugger has views for global variables, local variables and watchpoints.
Is there a free python debugger that has watchpoints?
[ "", "python", "debugging", "pdb", "watchpoint", "" ]
I have a class which constructor takes a [Jakarta enums](http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/enums/Enum.html). I'm trying to find how I can easily inject it via an [Spring](http://www.springframework.org/) XML aplicationContext. For example : The enum : ``` public class MyEnum extends org.apache.commons.lang.enums.Enum { public static final MyEnum MY_FIRST_VALUE = new MyEnum("MyFirstValue"); public static final MyEnum MY_SECOND_VALUE = new MyEnum("MySecondValue"); public static MyEnum getEnum(String name) { return (MyEnum) getEnum(MyEnum.class, name); } [...other standard enum methods] } ``` The class in which to inject : ``` public class MyService { private final MyEnum status; public MyService(MyEnum status) { this.status = status; } } ``` The application context : ``` <bean id="myService" class="MyService"> <constructor-arg index="0" value="MyFirstValue" /> </bean> ``` Of course, with this I have a `no matching editors or conversion strategy found` error. Is there an easy integration between Spring and the Jakarta enums ? Or should I write my own PropertyEditor ?
Check out the `<util:constant>` tag in Spring. It will require you to add the schema to your xml definition. So you would wind up with the following: ``` <bean id="myService" class="MyService"> <constructor-arg index="0"> <util:constant static-field="MyEnum.MY_FIRST_VALUE"/> </constructor-arg> </bean> ``` The definition and usage of the tag (including the XSD def) is found [here](http://static.springframework.org/spring/docs/2.5.x/reference/xsd-config.html#xsd-config-body-schemas-util).
I found a solution, but it is very verbose (far too much to my taste) : ``` <bean id="myService" class="MyService"> <constructor-arg index="0"> <bean class="MyEnum" factory-method="getEnum"> <constructor-arg value="MyFirstValue" /> </bean> </constructor-arg> </bean> ```
How to inject a Jakarta enums in a Spring application context?
[ "", "java", "spring", "enums", "" ]
I just realized from an article in CACM that Doxygen works with Java (and several other languages) too. But Java has already the Javadoc tool. Can someone explain what are the pros and cons of either approach? Are they mutually exclusive? Is there a Maven plugin for Doxygen?
Doxygen has a number of features that JavaDoc does not offer, e.g. the class diagrams for the hierarchies and the cooperation context, more summary pages, optional source-code browsing (cross-linked with the documentation), additional tag support such as @todo on a separate page and it can generate output in TeX and PDF format.It also allows a lot of visual customization. Since Doxygen supports the standard JavaDoc tags you can run Doxygen on any source code with JavaDoc comments on it. It often can even make sense to run on source code without JavaDoc since the diagrams and source code browsing can help understanding code even without the documentation. And since the JavaDoc tool ignores unknown tags you can even use additional Doxygen tags without breaking JavaDoc generation. Having said all this I must admit that I haven't used Doxygen for a long time. I tend to rely heavily on my IDE nowadays to provide the same visualization and I usually don't read JavaDoc as HTML pages but import the source files into my IDE so it can generate JavaDoc flyouts and I can jump to the definitions. That's even more powerful than what Doxygen has to offer. If you want to have documentation outside the IDE and are happy to run non-Java tooling then Doxygen is worth a try since it doesn't require any change to your Java code.
I'd only use Doxygen with Java if you're new to Java and you've used Doxygen before, reducing the learning curve you'd experience with javadoc. If you haven't used Doxygen before, I'd stick with javadoc, since it was specifically designed with Java in mind. If you don't know either one, and you work in C++ (or other supported languages) as much as you do Java, Doxygen is a good choice, as you'll be able to use it for both languages. Both tools are easy to use, with a similar feature set. Both have plugins (or are pre-built in) for NetBeans and Eclipse making it even faster to generate doc. There is a lot of overlap in the comment style used by each, but they're not *exactly* the same, so it would be difficult to mix them together (you'd have to know the details of *both*, leaving out any features that are specific to one or the other). I've never used it, but there does seem to be a [Maven plugin for Doxygen](http://doodleproject.sourceforge.net/mavenite/index.html).
Doxygen vs Javadoc
[ "", "java", "maven-2", "documentation", "doxygen", "" ]
I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase. My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise). I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.) My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.) I *conjecture* that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds. I have looked at [PyMedia](http://pymedia.org/), but it requires me to migrate to PCM to process the data. Similarly, [LAME](http://lame.sourceforge.net) wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags. Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?
I got three quality answers, and I thank you all for them. I haven't chosen any as the accepted answer, because each addressed one aspect, so I wanted to write a summary. **Do you need to work in MP3?** * Transcoding to PCM and back to MP3 is unlikely to result in a drop in quality. * Don't optimise audio-quality prematurely; test it with a simple prototype and listen to it. **Working in MP3** * Wikipedia has a summary of the [MP3 File Format](http://en.wikipedia.org/wiki/MP3). * MP3 frames are short (1152 samples, or just a few milliseconds) allowing for moderate precision at that level. * However, [Wikipedia](http://en.wikipedia.org/wiki/MP3) warns that "Frames are not independent items ("byte reservoir") and therefore cannot be extracted on arbitrary frame boundaries." * Existing libraries are unlikely to be of assistance, if I really want to avoid decoding. **Working in PCM** There are several libraries at this level: * [LAME](http://lame.sourceforge.net/) (latest release: October 2017) * [PyMedia](http://pymedia.org/) (latest release: February 2006) * [PyMad](http://spacepants.org/src/pymad/) (Linux only? Decoder only? Latest release: January 2007) **Working at a higher level** * [Echo Nest Remix API](https://echonest.github.io/remix/) (Mac or Linux only, at the moment) is an API to a web-service that supports quite sophisticated operations (e.g. finding the locations of music beats and tempo, etc.) * [mp3DirectCut](http://mpesch3.de1.cc/mp3dc.html#dwn) (Windows only) is a GUI that apparently performs the operations I want, but as an app. It is not open-source. (I tried to run it, got an Access Denied installer error, and didn't follow up. A GUI isn't suitably for me, as I want to repeatedly run these operations on a changing library of files.) My plan is now to start out in PyMedia, using PCM.
If you want to do things low-level, use [pymad](https://spacepants.org/src/pymad/). It turns MP3s into a buffer of sample data. If you want something a little higher-level, use the Echo Nest [Remix API](https://web.archive.org/web/20121003042054/http://code.google.com/p/echo-nest-remix/) (disclosure: I wrote part of it for my dayjob). It includes a few examples. If you look at the [cowbell](https://web.archive.org/web/20121006023439/http://code.google.com:80/p/echo-nest-remix/source/browse/#svn/trunk/examples/cowbell) example (i.e., [MoreCowbell.dj](https://web.archive.org/web/20221121114258/https://morecowbell.dj/)), you'll see a fork of pymad that gives you a [NumPy](https://numpy.org/) array instead of a buffer. That datatype makes it easier to slice out sections and do math on them.
Python library to modify MP3 audio without transcoding
[ "", "python", "mp3", "codec", "" ]
Given a collection of user specified tags how do I determine which ones **are not** in the tags table with 1 SQL Statement? Assuming a table schema `tags (id, tag)` and I'm using mysql, if there's an optimization I'm unaware of. thanks
``` SELECT Tag FROM UserSpecifiedTags LEFT OUTER JOIN AllTags ON UserSpecifiedTags.Tag = AllTags.Tag WHERE AllTags.Tag IS NULL ``` This should return what you want. In my experience, executing a join and looking for rows which don't have a match is **much** quicker than using the `IN` operator.
``` select * from canonical_list_of_tags where tag not in (select tag from used_tags) ``` At least that works in T-SQL for SQL Server ... **Edit:** Assuming that the table `canonical_list_of_tags` is populated with the result of "*Given a collection of user specified tags*"
Which tags are not in the database?
[ "", "sql", "mysql", "" ]
I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected. Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes). Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.
I'd do it like this: ``` // first, build a reverse lookup var optCount = mySelect.options.length; var reverseLookup = {}; for (var i = 0; i < optCount; i++) { var option = mySelect.options[i]; if (!reverseLookup[option.value]) { // use an array to account for multiple options with the same value reverseLookup[option.value] = []; } // store a reference to the DOM element reverseLookup[option.value].push(option); } // then, use it to find the option var foundOptions = reverseLookup["Value that you are looking for"]; if (foundOptions && foundOptions.length) { alert(foundOptions[0].id); } ```
I would suggest not having thousands of options in your select. Perhaps you could structure your data differently a select with thousands of entries to me seems wrong. Perhaps your app requires this but it would not be typical usage of this element.
Is there any fast way to get an <option> from a <select> by value, using JavaScript?
[ "", "javascript", "html", "" ]
In eclipse developing a java app, there are several class files that are generated by a custom ant script. This happens automatically, and it is set up as an export/publish dependency for /WEB-INF/classes. With publishing it happens alright, however on exporting to .WAR these files just got missing. Is there a way to automate this?
I'd suggest generating your war file using Ant. I like my deliverables to be easy to generate using a simple toolchain, i.e. not need to fire up Eclipse to generate them; this way things are easier to automate and document. six years after edit: I was an Ant man when I wrote this- today I'd probably suggest Maven
1. Go to the project properties you will export. 2. Setup the Java EE Module Dependencies Now they should exist in your exported war.
How to specify in Eclipse what to include in a .WAR file
[ "", "java", "eclipse", "jakarta-ee", "" ]
I have spent several hours trying to find a means of writing a cross platform password prompt in php that hides the password that is input by the user. While this is easily accomplished in Unix environments through the use of stty -echo, I have tried various means of passthru() and system() calls to make windows do the same thing to no avail. I have tried: ``` passthru('set /p pass=Password: '); system('echo %pass% > out.txt'); $pass = file_get_contents('out.txt', 'r'); ``` This seems to hang on the passthru('set /p pass=Password: '); line without allowing me to input any text and must be killed with a Ctrl-c. I have also tried various methods of fgetc and fgets and printing backspace characters to hide the input since this works in other languages. However, PHP does not appear to be able to interact with text prior to a carriage return. I would really like to find a way to make this work, is this an impossible task or is this something that can be done? Note that I am aware that I could wrap the php script in a batch file and pass the password as a command line argument, but that doesn't work for me in this case.
Here's a Windows solution, using the COM extension for PHP. I tested this on Windows XP with PHP 5.2.6. ``` <?php $pwObj = new Com('ScriptPW.Password'); print "Password: "; $passwd = $pwObj->getPassword(); echo "Your password is $passwd\n"; ?> ```
There doesn't seem to be an IOCTL or STTY extension for PHP. I found the following trick [here](http://www.usenet-forums.com/php-language/35386-hide-password-input-cli-php-script.html): ``` <?php echo 'Password: '; $pwd = preg_replace('/\r?\n$/', '', `stty -echo; head -n1 ; stty echo`); echo "\n"; echo "Your password was: {$pwd}.\n"; ?> ```
Is it really not possible to write a php cli password prompt that hides the password in windows?
[ "", "php", "passwords", "" ]
What I'm trying to do is run the same SQL select on many Oracle databases (at least a dozen), and display the output in a Gridview. I've hacked together something that works but unfortunately it's very slow. I think its exacerbated by the fact that at least 1 of the dozen databases will invariably be unreachable or otherwise in an error state. As well as being slow I can't help thinking it's not the best way of doing it, nor very '.NET' like. I've written something similar in the past as a simple loop in PHP that just connects to each db in turn, runs the sql and writes another `<tr>`, and it works at least twice as fast, for a given query. But I'm not really happy with that, I'd like to improve my knowledge! I'm learning C# and ASP.NET so please excuse the horrible code :) ``` public void BindData(string mySQL) { OracleConnection myConnection; OracleDataAdapter TempDataAdapter; DataSet MainDataSet = new DataSet(); DataTable MainDataTable = new DataTable(); DataSet TempDataSet; DataTable TempDataTable; string connectionString = ""; Label1.Visible = false; Label1.Text = ""; foreach (ListItem li in CheckBoxList1.Items) { if (li.Selected) { connectionString = "Data Source=" + li.Text + ""; connectionString += ";Persist Security Info=True;User ID=user;Password=pass;Unicode=True"; myConnection = new OracleConnection(connectionString); try { TempDataAdapter = new OracleDataAdapter(mySQL, myConnection); TempDataSet = new DataSet(); TempDataTable = new DataTable(); TempDataAdapter.Fill(TempDataSet); TempDataTable = TempDataSet.Tables[0].Copy(); /* If the main dataset is empty, create a table by cloning from temp dataset, otherwise copy all rows to existing table.*/ if (MainDataSet.Tables.Count == 0) { MainDataSet.Tables.Add(TempDataTable); MainDataTable = MainDataSet.Tables[0]; } else { foreach (DataRow dr in TempDataTable.Rows) { MainDataTable.ImportRow(dr); } } } catch (OracleException e) { Label1.Visible = true; Label1.Text = Label1.Text + e.Message + " on " + li.Text + "<br>"; } finally { if (myConnection != null) { myConnection.Close(); myConnection = null; } TempDataSet = null; TempDataAdapter = null; TempDataTable = null; } } } GridView1.DataSourceID = String.Empty; if (MainDataSet.Tables.Count != 0) { GridView1.DataSource = MainDataSet; if (GridView1.DataSource != null) { GridView1.DataBind(); } } } protected void Button1_Click(object sender, EventArgs e) { BindData(TextBox1.Text); } ``` Thanks! UPDATE: The SQL code varies, for testing I have used very simple queries such as `select sysdate from dual` or `select name from v$database`. In eventual use, it will be much more complicated, the idea is that I should be able to run pretty much anything, hence the `BindData(TextBox1.Text)` UPDATE: The reason for connecting to many databases from the ASP.NET code rather than a stored proc on one or all dbs, or replicating to one db, is twofold. Firstly, the dbs in question are frequently updated replicas of several similar production environments (typically development, testing and support for each client), so anything done to the actual dbs would have to be updated or redone regularly as they are reloaded anyway. Secondly, I don't know in advance what kind of query might be run, this form lets me just type e.g. `select count (name) from dbusers` against a dozen databases without having to first think about replicating the dbusers table to a master db.
If you run the DataAdapter.Fill method on a DataTable object the table will be updated with the results from the query. So instead of creating new DataTable and DataSet objects and then copying the DataRows manually you can just add rows to the same table. Try something like this (in untested C# code): ``` public void BindData(string mySQL) { OracleConnection myConnection; // Empty connection string for now OracleDataAdapter MainDataAdapter = new OracleDataAdapter(mySQL, ""); DataTable MainDataTable = new DataTable(); string connectionString = ""; Label1.Visible = false; Label1.Text = ""; foreach (ListItem li in CheckBoxList1.Items) { if (li.Selected) { connectionString = "Data Source=" + li.Text + ""; connectionString += ";Persist Security Info=True;User ID=user;Password=pass;Unicode=True"; MainDataAdapter.SelectCommand.Connection.ConnectionString = connectionString try { MainDataAdapter.Fill(MainDataTable); } catch (OracleException e) { Label1.Visible = true; Label1.Text = Label1.Text + e.Message + " on " + li.Text + "<br>"; } } } GridView1.DataSourceID = String.Empty; GridView1.DataSource = MainDataTable; GridView1.DataBind(); } ``` I did the following changes: * Created one data adapter and assigned it a select command using your mySQL query * Gave the connection an empty connection string * Created a data table object and removed the data sets (you only need them if your query returns several rows) * Changed you loop to just set the connection string of the SelectCommand (you may have to change this to replacing the SelectCommand with a new one) * Removed the connection.Close() calls. The DataAdapter does this automatically. And thats it. If your databases are offline you will still experience slowdowns, but at least the code is simpler and faster since you don't have to copy all the rows between your tables. One more thing. You can probably set a timeout for the connection in the connection string. Try to lower this one.
could be a lot of factors causing it to be slow. What's the sql statement being executed that's running slow? If anyone reading this is using sql server, Scott Mitchell just wrote a nice article to help solve this in sql server: **[Running the Same Query Against Multiple Databases](http://scottonwriting.net/sowblog/posts/13587.aspx)**
good way to query many databases in ASP.NET
[ "", "c#", "asp.net", "gridview", "multiple-databases", "" ]
In an earlier question about [how to return a string from a dialog window](https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form), **yapiskan** suggested [overloading the child form's ShowDialog() method](https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form#280731) to include an out parameter. My question is whether or not this is a good approach in C#. Here is some example code, based on yapiskan's suggestion. In the child form (in this example, it's a form with a textbox on it), you just need to add the ShowDialog overload and assign UI values to the out parameter: ``` public DialogResult ShowDialog(out string s) { DialogResult result = this.ShowDialog(); s = this.textBox1.Text; return result; } ``` And to show the form and retrieve the entered text, you do this: ``` using (CustomDialog frm = new CustomDialog()) { string s; if (frm.ShowDialog(out s) == DialogResult.OK) { // do something with s } } ``` One advantage I can think of is that this approach forces the user of the CustomDialog form to get the information it contains through the form's ShowDialog method (rather than from a who-knows-what-it's-called method like GetMyData() or something).
Better to have a Public property/method and get the information. What would you do if you would need 3..4..5 informations, having 5 parameters out? More clean to have accessors to get your information from the Dialog.
It should not be OK since .net framework does not use this design. In the case of OpenFileDialog class, it has a parameterless ShowDialog() method returning a DialogResult. Once this method called, user is supposed to get the selected files by using the FileName, FileNames, SafeFileName and SafeFileNames methods. Let's assume that this implented in the "out parameter" way. I would have to write code like this just to get the SafeFileName: ``` string dummyFileName; string[] dummyFileNames; string safeFileName; string[] dummySafeFileNames; myDialog.ShowDialog(out dummyFileName, out dummyFileNames, out safeFileName, out dummySafeFileNames); ```
Is it OK to overload ShowDialog() so that a child form returns information as an out parameter?
[ "", "c#", ".net", "winforms", "" ]
I have an ASP.NET GridView which has columns that look like this: ``` | Foo | Bar | Total1 | Total2 | Total3 | ``` Is it possible to create a header on two rows that looks like this? ``` | | Totals | | Foo | Bar | 1 | 2 | 3 | ``` The data in each row will remain unchanged as this is just to pretty up the header and decrease the horizontal space that the grid takes up. The entire GridView is sortable in case that matters. I don't intend for the added "Totals" spanning column to have any sort functionality. **Edit:** Based on one of the articles given below, I created a class which inherits from GridView and adds the second header row in. ``` namespace CustomControls { public class TwoHeadedGridView : GridView { protected Table InnerTable { get { if (this.HasControls()) { return (Table)this.Controls[0]; } return null; } } protected override void OnDataBound(EventArgs e) { base.OnDataBound(e); this.CreateSecondHeader(); } private void CreateSecondHeader() { GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); TableCell left = new TableHeaderCell(); left.ColumnSpan = 3; row.Cells.Add(left); TableCell totals = new TableHeaderCell(); totals.ColumnSpan = this.Columns.Count - 3; totals.Text = "Totals"; row.Cells.Add(totals); this.InnerTable.Rows.AddAt(0, row); } } } ``` In case you are new to ASP.NET like I am, I should also point out that you need to: 1) Register your class by adding a line like this to your web form: ``` <%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%> ``` 2) Change asp:GridView in your previous markup to foo:TwoHeadedGridView. Don't forget the closing tag. **Another edit:** You can also do this without creating a custom class. Simply add an event handler for the DataBound event of your grid like this: ``` protected void gvOrganisms_DataBound(object sender, EventArgs e) { GridView grid = sender as GridView; if (grid != null) { GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); TableCell left = new TableHeaderCell(); left.ColumnSpan = 3; row.Cells.Add(left); TableCell totals = new TableHeaderCell(); totals.ColumnSpan = grid.Columns.Count - 3; totals.Text = "Totals"; row.Cells.Add(totals); Table t = grid.Controls[0] as Table; if (t != null) { t.Rows.AddAt(0, row); } } } ``` The advantage of the custom control is that you can see the extra header row on the design view of your web form. The event handler method is a bit simpler, though.
[This article](https://web.archive.org/web/20100201202857/http://blogs.msdn.com/mattdotson/articles/541795.aspx) should point you in the right direction. You can programmatically create the row and add it to the collection at position 0.
I took the accepted answer approach, but added the header to the existing GridView instead of a custom inherited GridView. After I bind my GridView, I do the following: ``` /*Create header row above generated header row*/ //create row GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal); //spanned cell that will span the columns I don't want to give the additional header TableCell left = new TableHeaderCell(); left.ColumnSpan = 6; row.Cells.Add(left); //spanned cell that will span the columns i want to give the additional header TableCell totals = new TableHeaderCell(); totals.ColumnSpan = myGridView.Columns.Count - 3; totals.Text = "Additional Header"; row.Cells.Add(totals); //Add the new row to the gridview as the master header row //A table is the only Control (index[0]) in a GridView ((Table)myGridView.Controls[0]).Rows.AddAt(0, row); /*fin*/ ```
ASP.NET GridView second header row to span main header row
[ "", "c#", "asp.net", "gridview", "" ]
How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command `mkdir -p /path/to/nested/directory` does this.
On Python ≥ 3.5, use [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir): ``` from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True) ``` For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try [`os.path.exists`](https://docs.python.org/library/os.path.html#os.path.exists), and consider [`os.makedirs`](https://docs.python.org/library/os.html#os.makedirs) for the creation. ``` import os if not os.path.exists(directory): os.makedirs(directory) ``` As noted in comments and elsewhere, there's a race condition – if the directory is created between the `os.path.exists` and the `os.makedirs` calls, the `os.makedirs` will fail with an `OSError`. Unfortunately, blanket-catching `OSError` and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc. One option would be to trap the `OSError` and examine the embedded error code (see [Is there a cross-platform way of getting information from Python’s OSError](https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror)): ``` import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise ``` Alternatively, there could be a second `os.path.exists`, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled. Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation. Modern versions of Python improve this code quite a bit, both by exposing [`FileExistsError`](https://docs.python.org/3.3/library/exceptions.html?#FileExistsError) (in 3.3+)... ``` try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass ``` ...and by allowing [a keyword argument to `os.makedirs` called `exist_ok`](https://docs.python.org/3.2/library/os.html#os.makedirs) (in 3.2+). ``` os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists. ```
## Python 3.5+: ``` import pathlib pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) ``` [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir) as used above recursively creates the directory and does not raise an exception if the directory already exists. If you don't need or want the parents to be created, skip the `parents` argument. ## Python 3.2+: **Using `pathlib`:** If you can, install the current `pathlib` backport named [`pathlib2`](https://pypi.python.org/pypi/pathlib2/). Do not install the older unmaintained backport named [`pathlib`](https://pypi.python.org/pypi/pathlib/). Next, refer to the Python 3.5+ section above and use it the same. If using Python 3.4, even though it comes with `pathlib`, it is missing the useful `exist_ok` option. The backport is intended to offer a newer and superior implementation of `mkdir` which includes this missing option. **Using `os`:** ``` import os os.makedirs(path, exist_ok=True) ``` [`os.makedirs`](https://docs.python.org/library/os.html#os.makedirs) as used above recursively creates the directory and does not raise an exception if the directory already exists. It has the optional `exist_ok` argument only if using Python 3.2+, with a default value of `False`. This argument does not exist in Python 2.x up to 2.7. As such, there is no need for manual exception handling as with Python 2.7. ## Python 2.7+: **Using `pathlib`:** If you can, install the current `pathlib` backport named [`pathlib2`](https://pypi.python.org/pypi/pathlib2/). Do not install the older unmaintained backport named [`pathlib`](https://pypi.python.org/pypi/pathlib/). Next, refer to the Python 3.5+ section above and use it the same. **Using `os`:** ``` import os try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise ``` While a naive solution may first use [`os.path.isdir`](https://docs.python.org/2/library/os.path.html#os.path.isdir "os.path.isdir") followed by [`os.makedirs`](https://docs.python.org/2/library/os.html#os.makedirs "os.makedirs"), the solution above reverses the order of the two operations. In doing so, it prevents a common race condition having to do with a duplicated attempt at creating the directory, and also disambiguates files from directories. Note that capturing the exception and using `errno` is of limited usefulness because `OSError: [Errno 17] File exists`, i.e. `errno.EEXIST`, is raised for both files and directories. It is more reliable simply to check if the directory exists. ## Alternative: [`mkpath`](https://docs.python.org/distutils/apiref.html#distutils.dir_util.mkpath) creates the nested directory, and does nothing if the directory already exists. This works in both Python 2 and 3. Note however that [`distutils`](https://docs.python.org/3/library/distutils.html#module-distutils) has been deprecated, and is scheduled for removal in Python 3.12. ``` import distutils.dir_util distutils.dir_util.mkpath(path) ``` Per [Bug 10948](http://bugs.python.org/issue10948), a severe limitation of this alternative is that it works only once per python process for a given path. In other words, if you use it to create a directory, then delete the directory from inside or outside Python, then use `mkpath` again to recreate the same directory, `mkpath` will simply silently use its invalid cached info of having previously created the directory, and will not actually make the directory again. In contrast, `os.makedirs` doesn't rely on any such cache. This limitation may be okay for some applications. --- With regard to the directory's *mode*, please refer to the documentation if you care about it.
How do I create a directory, and any missing parent directories?
[ "", "python", "exception", "path", "directory", "operating-system", "" ]
I want my application to clean all the temp files it used, the problem is that not all the temp files are under my control, so I just want to "brutally" unlock them in order to delete them programatically.
Take a look at [this](http://www.codeguru.com/Cpp/W-P/files/fileio/article.php/c1287/#more) article. I think that you'll struggle to do this in C# natively, even using interop, but writing a C++/CLI wrapper assembly may be a good compromise. Note also that the user needs to have the SE\_DEBUG privilege for this to work.
I've struggled with this as well, and ended up just shelling out to Unlocker's command line implementation. In my case it has to run many times daily and ends up unlocking thousands of files per day without any problem.
How can I unlock a file that is locked by a process in .NET
[ "", "c#", "temporary-files", "file-locking", "" ]
How do I remove empty elements from an array in JavaScript? Is there a straightforward way, or do I need to loop through it and remove them manually?
**EDIT:** This question was answered almost nine years ago when there were not many useful built-in methods in the `Array.prototype`. Now, certainly, I would recommend you to use the `filter` method. Take in mind that this method will return you *a new array* with the elements that pass the criteria of the callback function you provide to it. For example, if you want to remove `null` or `undefined` values: ``` var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,]; var filtered = array.filter(function (el) { return el != null; }); console.log(filtered); ``` It will depend on what you consider to be "empty" for example, if you were dealing with strings, the above function wouldn't remove elements that are an empty string. One typical pattern that I see often used is to remove elements that are *falsy*, which include an empty string `""`, `0`, `NaN`, `null`, `undefined`, and `false`. You can pass to the `filter` method, the `Boolean` constructor function, or return the same element in the filter criteria function, for example: ``` var filtered = array.filter(Boolean); ``` Or ``` var filtered = array.filter(function(el) { return el; }); ``` In both ways, this works because the `filter` method in the first case, calls the `Boolean` constructor as a function, converting the value, and in the second case, the `filter` method internally turns the return value of the callback implicitly to `Boolean`. If you are working with sparse arrays, and you are trying to get rid of the "holes", you can use the `filter` method passing a callback that returns true, for example: ``` var sparseArray = [0, , , 1, , , , , 2, , , , 3], cleanArray = sparseArray.filter(function () { return true }); console.log(cleanArray); // [ 0, 1, 2, 3 ] ``` **Old answer:** Don't do this! I use this method, extending the native Array prototype: ``` Array.prototype.clean = function(deleteValue) { for (var i = 0; i < this.length; i++) { if (this[i] == deleteValue) { this.splice(i, 1); i--; } } return this; }; test = new Array("", "One", "Two", "", "Three", "", "Four").clean(""); test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]; test2.clean(undefined); ``` Or you can simply push the existing elements into other array: ``` // Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string) function cleanArray(actual) { var newArray = new Array(); for (var i = 0; i < actual.length; i++) { if (actual[i]) { newArray.push(actual[i]); } } return newArray; } cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]); ```
## A few simple ways: ``` var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,]; arr.filter(n => n) // [1, 2, 3, -3, 4, 4, 5, 6] arr.filter(Number) // [1, 2, 3, -3, 4, 4, 5, 6] arr.filter(Boolean) // [1, 2, 3, -3, 4, 4, 5, 6] ``` **or - (only for *single* array items of type "text")** ``` ['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); // output: ["1","2","3","4","5"] ``` **or - Classic way: simple iteration** ``` var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,], len = arr.length, i; for(i = 0; i < len; i++ ) arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array arr.splice(0 , len); // cut the array and leave only the non-empty values // [1,2,3,3,[],Object{},5,6] ``` ## jQuery: ``` var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,]; arr = $.grep(arr, n => n == 0 || n); // [1, 2, 3, 3, 0, 4, 4, 5, 6] ```
Remove empty elements from an array in Javascript
[ "", "javascript", "arrays", "" ]
In a form, I added an overload of ShowDialog(). In Visual Studio, this overload shows up in Intellisense as the third version. How can I make my overloaded function appear as #1 (i.e. the default)?
As far as I know, there is no way to control the order of overloads in the overload selection intellisense tip.
You should use a plugin for that: one that accomplishes the required task is the Visual Assist from Tomato - <http://www.wholetomato.com/> It does exactly what you want(among the other options): display the non-inherited members on the top of the suggestion list and(or) makes them bold
Is there a way in .NET to make your overload of a method appear first in the Intellisense dropdown?
[ "", "c#", ".net", "visual-studio", "intellisense", "" ]
Say you have a class declaration, e.g.: ``` class MyClass { int myInt=7; int myOtherInt; } ``` Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not? Note the difference between being initialised with an explicit default value, and being left to it's implicit default value (myOtherInt will be initialised to 0, by default). From my own research it looks like there is no way to do this - but I thought I'd ask here before giving up. [Edit] Even with nullable and reference types I want to distingush between those that have been left as null, and those that have been explicitly initialised to null. This is so that I can say that fields with an initialiser are "optional" and other fields are "mandatory". At the moment I'm having to do this using attributes - which niggles me with their redundancy of information in this case.
I compiled your code and load it up in ILDASM and got this ``` .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.7 IL_0002: stfld int32 dummyCSharp.MyClass::myInt IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: nop IL_000e: ret } // end of method MyClass::.ctor ``` Note the `ldc.i4.7` and `stfld int32 dummyCSharp.MyClass::myInt` seems to be instructions to set the default values for the myInt field. **So such assignment is actually compiled as an additional assignment statement in a constructor.** To detect such assignment, then you will need reflection to reflect on the IL of MyClass's constructor method and look for `stfld` (set fields?) commands. --- EDIT: If I add some assignment into the constructor explicitly: ``` class MyClass { public int myInt = 7; public int myOtherInt; public MyClass() { myOtherInt = 8; } } ``` When I load it up in ILDASM, I got this: ``` .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.7 IL_0002: stfld int32 dummyCSharp.MyClass::myInt IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: nop IL_000e: nop IL_000f: ldarg.0 IL_0010: ldc.i4.8 IL_0011: stfld int32 dummyCSharp.MyClass::myOtherInt IL_0016: nop IL_0017: ret } // end of method MyClass::.ctor ``` Note that the extra assigment on myOtherInt that I added was addded *after* a call the Object class's constructor. ``` IL_0008: call instance void [mscorlib]System.Object::.ctor() ``` So there you have it, **Any assignment done *before* the call to Object class's constructor in IL is a default value assignment.** Anything following it is a statement inside the class's actual constructor code. More extensive test should be done though. p.s. that was fun :-)
You might want to consider a nullable int for this behavior: ``` class MyClass { int? myInt = 7; int? myOtherInt = null; } ```
Can you detect if a C# field has been assigned a default value?
[ "", "c#", "reflection", "default", "" ]
I have an HTML input box ``` <input type="text" id="foo" value="bar"> ``` I've attached a handler for the '*keyup*' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be! I've tried picking up '*keypress*' and '*change*' events, same problem. I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future! *Is there anyway to obtain the current value during those events?* EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with: ``` function showMe(e) { // i am spammy! alert(e.value); } .... <input type="text" id="foo" value="bar" onkeyup="showMe(this)" /> ```
To give a ***modern*** approach to this question. This works well, including `Ctrl`+`v`. [GlobalEventHandlers.oninput](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput). ``` var onChange = function(evt) { console.info(this.value); // or console.info(evt.target.value); }; var input = document.getElementById('some-id'); input.addEventListener('input', onChange, false); ```
How to get the new value of an HTML input after a keypress has modified it?
[ "", "javascript", "html", "dom", "" ]
I'm relatively new to Javascript and was wondering if there's a quick way to shuffle content that is contained in multiple `<div>` tags. For example ``` <div id='d1'> <span>alpha</span> <img src='alpha.jpg'> </div> <div id='d2'> <span>beta</span> <img src='beta.jpg'> </div> <div id='d3'> <span>gamma</span> <img src='gamma.jpg'> </div> <button onclick='shuffle_content();'>Shuffle</button> ``` After clicking on the button, I'd like the content in d1, d2, d3 to change places (for example maybe d3 would be first, then d1, then d2). A quick way to kind of move things around is to copy the first div element (d1), then put it at the very end (after d3), and then delete the original d1. But that doesn't really randomize things. It just makes things go in the cycle (which might be ok). Any suggestions would be appreciated. Thanks.
are you ok with using a javascript library like [jQuery](http://jquery.com)? here's a quick jQuery example to accomplish what you're after. the only modification to your HTML is the addition of a container element as suggested: ``` <div id="shuffle"> <div id='d1'>...</div> <div id='d2'>...</div> <div id='d3'>...</div> </div> ``` and javascript: ``` function shuffle(e) { // pass the divs to the function var replace = $('<div>'); var size = e.size(); while (size >= 1) { var rand = Math.floor(Math.random() * size); var temp = e.get(rand); // grab a random div from our set replace.append(temp); // add the selected div to our new set e = e.not(temp); // remove our selected div from the main set size--; } $('#shuffle').html(replace.html() ); // update our container div with the // new, randomized divs } shuffle( $('#shuffle div') ); ```
A recent question was just closed as duplicate of this, but I feel I've got a better answer than any here. This method is very direct. There's no mucking with copying HTML, thus preserving changes to the DOM, styles, event handlers, etc. To shuffle all the children of some parent element, select a random child and append it back to the parent one at a time until all the children have been re-appended. Using jQuery: ``` var parent = $("#shuffle"); var divs = parent.children(); while (divs.length) { parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); } ``` **Demo:** <http://jsfiddle.net/C6LPY/2> Without jQuery it's similar and just as simple: ``` var parent = document.getElementById("shuffle"); var divs = parent.children; var frag = document.createDocumentFragment(); while (divs.length) { frag.appendChild(divs[Math.floor(Math.random() * divs.length)]); } parent.appendChild(frag); ``` **Demo:** <http://jsfiddle.net/C6LPY/5/> --- **Edit:** Here's a break down of the code: ``` // Create a document fragment to hold the shuffled elements var frag = document.createDocumentFragment(); // Loop until every element is moved out of the parent and into the document fragment while (divs.length) { // select one random child element and move it into the document fragment frag.appendChild(divs[Math.floor(Math.random() * divs.length)]); } // appending the document fragment appends all the elements, in the shuffled order parent.appendChild(frag); ```
Any way to shuffle content in multiple div elements
[ "", "javascript", "dom", "dhtml", "" ]
Up till now all my programming experience has been desktop development (mostly C/C++ with OpenGL/DirectX) but I'm interested in trying my hand at some web dev. The two directions I'm considering are Ruby on Rails and ASP.net. Which is most widely used? Which would be a more marketable skill to have? Thanks!
Why don't you take a few days or a week to experiment with Rails, just for fun? You might, like many other devs before, find a real liking for it and 'fall in love' with Ruby and revitalize your programming interest. If not you just embrace ASP.net which will feel more natural to you anyway. Other commenters have not mentioned that the number 1 advantage of both Ruby and Rails is 'pleasure of programming'. Alsa these days talented Ruby programmers are in very high demand. There is much more demand than supply. You can do the math as far as earning potential.
PHP, Ruby On Rails, ASP.Net, or Java. It's a religious choce and it depends on who you ask. Everyone you ask will give you a different answer. You should ask yourself how you want to work, PHP java and ASP all let you write markup that is interspersed with code or code that writes the markup for you. To be honest it's subjective and no one will be able to give you a straight answer. Given your two options ASP is probably a better choice for industry though, there is a lot of money in it and C# is close enough to C/C++ for it to be readable.
Moving from Desktop Development to Web Development
[ "", "c#", "asp.net", "ruby-on-rails", "ruby", "" ]
I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form: ``` OtherForm newForm=new OtherForm(); newForm.Show(); ``` How can i communicate from the new winform with the form that opened it? So that I can add some items in it.
I think I have found the answer here: <http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx> I have to use delegates. In the second form I define: ``` public delegate void AddItemDelegate(string item); public AddItemDelegate AddItemCallback; ``` And from the form that opened it I write: ``` private void btnScenario2_Click(object sender, EventArgs e) { FrmDialog dlg = new FrmDialog(); //Subscribe this form for callback dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn); dlg.ShowDialog(); } private void AddItemCallbackFn(string item) { lstBx.Items.Add(item); } ```
The simplest way is to override the constructor, eg, `OtherForm newForm=new OtherForm(string title, int data);`. This also works for reference types (which would be a simple way to send the data back).
How to call the main program from a winform opened by it'?
[ "", "c#", "winforms", "" ]
I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below: I have a test Ruby XML-RPC server as follows: ``` require "xmlrpc/server" class ExampleBar def bar() return "hello world!" end end class ExampleFoo def foo() return ExampleBar.new end def test() return "test!" end end s = XMLRPC::Server.new( 9090 ) s.add_introspection s.add_handler( "example", ExampleFoo.new ) s.serve ``` And I have a test Python XML-RPC Client as follows: ``` import xmlrpclib s = xmlrpclib.Server( "http://127.0.0.1:9090/" ) print s.example.foo().bar() ``` I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code: ``` example = ExampleFoo.new puts example.foo().bar() ``` However it generates an error: "xmlrpclib.ProtocolError: <ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error>". print s.example.test() works fine. I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured. Can XML-RPC support this kind of usage or is it too basic? So I guess my question really is; how can I get this working, if not with XML-RPC what with?
Your client (s in you Python code) is a ServerProxy object. It only accepts return values of type boolean, integers, floats, arrays, structures, dates or binary data. However, without you doing the wiring, there is no way for it to return another ServerProxy, which you would need for accessing another class. You could probably implement an object cache on the Ruby side, but it would involve keeping track of active session and deciding when to remove objects, how to handle missing objects, etc. Instead I would suggest exposing a thin wrapper on the ruby side that does atomic operations like: ``` def foobar() return ExampleFoo.new().foo().bar() end ```
XML-RPC can't pass objects. The set of parameter types is limited (as jakber says).
Access Ruby objects with Python via XML-RPC?
[ "", "python", "ruby", "xml-rpc", "interop", "" ]
while writing a custom attribute in C# i was wondering if there are any guidelines or best practices regarding exceptions in attributes. Should the attribute check the given parameters for validity? Or is this the task of the user of the property? In a simple test I did the exception was not thrown until i used GetCustomAttributes on a type with an exception throwing attribute. I just think it's a bit awkward to get an exception from an Attribute only when explicitly asking for them. --- Example Attribute with exception: ``` [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] sealed public class MyAttribute : Attribute { public string SomeValue { get; private set; } public MyAttribute(string someValue) { if(string.IsNullOrEmpty(someValue)) { throw new ArgumentNullException("path"); } if(!someOtherCheck(someValue)) { throw MyAttributeException("An other error occured"); } SomeValue = someValue; } } ```
Attributes are only actually constructed when you use reflection, so that's the only time you *can* throw an exception. I can't remember *ever* using an attribute and having it throw an exception though. Attributes usually provide data rather than real behaviour - I'd expect the code which *uses* the attribute to provide any validation. I know this isn't like normal encapsulation, but it's the way it tends to be in my experience.
With a few exceptions with compiler-sepcific meaning (such as `[PrincipalPermission]` etc.) attributes can't interact directly with code without being asked to. However, if you use the AOP (Aspect Oriented Programming) tool "[PostSharp](http://www.postsharp.net/)", your aspect attributes *can* add behaviour to your class. Not simple, but it's a very useful trick sometimes.
Custom Attributes and Exceptions in .net
[ "", "c#", ".net", "exception", "attributes", "" ]
I am writing a multi-threaded Windows application in Microsoft Visual C# 2008 Express Edition. Recently, the debugger has been acting strangely. While I am Stepping Over lines of code using the F10, sometimes it will interpret my Step Over (F10) command just like a Continue command (F5) and then the program will resume running and the debugging session will be done. Does anyone know why this happening? In what circumstances can the Step Over command result in the debugger stopping? It's not a problem with the code being debugged: it doesn't just happen on particular lines of code. It happens on a random line that is different each time I run the debugger. It's not a problem with my keyboard: the same thing happens when I just click Step Over in the Debug toolbar. It may be a problem with the other threads in my program. Maybe one of them is randomly doing something that has a side effect of interrupting the debugger. Is that possible? Thanks in advance!
You ought to take a look at this [KB article](http://support.microsoft.com/default.aspx/kb/957912) and consider its matching hotfix. EDIT: the hotfix does solve these kind of debugging problems. Unfortunately, the source code changes for the hotfix didn't make it back into the main branch and VS2010 shipped with the exact same problems. This got corrected again by its Service Pack 1.
I've seen this a few times. It generally happens when there's a context switch to another thread. So you might be stepping through thread with ID 11, you hit F10, and there's a pre-emptive context switch so now you're running on thread ID 12 and so Visual Studio merrily allows the code to continue. There are some good debugging tips [here](http://www.eggheadcafe.com/articles/20050511.asp): > Tip: Break only when a specific thread calls a method: To set a per-thread breakpoint, you need to uniquely identify a particular thread that you have given a name with its Name property. You can set a conditional breakpoint for a thread by creating a conditional expression such as "ThreadToStopOn" == Thread.CurrentThread.Name . > > You can manually change the name of a thread in the Watch window by watching variable "myThread" and entering a Name value for it in the value window. If you don't have a current thread variable to work with, you can use Thread.CurrentThread.Name to set the current thread's name. There is also a private integer variable in the Thread class, DONT\_USE\_InternalThread, this is unique to each thread. You can use the Threads window to get to the thread you want to stop on, and in the Watch window, enter Thread.CurrentThread.DONT\_USE\_InternalThread to see the value of it so you can create the right conditional breakpoint expression. EDIT: There are also some good tips [here](http://www.learn2debug.com/articles/visual-studio-net/debugging-managed-thread-applications-using-visual-studio-net.aspx). I found this by googling for 'visual studio prevent thread switch while debugging'.
Why does Microsoft Visual C# 2008 Express Edition debugger randomly exit?
[ "", "c#", "visual-studio", "visual-studio-2008", "multithreading", "debugging", "" ]
If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate. What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?
``` Boolean a = true; Boolean b = false; Boolean c = null; ``` I would use that. It's the most straight-forward. Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required: ``` public enum ThreeState { TRUE, FALSE, TRALSE }; ``` There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass `true` and `false`. If you don't like the `null`, since it's telling rather little about its meaning here, you can still make a `public static final Boolean tralse = null;` in your class.
In Java 8, there is also the **Optional** option: ``` public static final Optional<Boolean> TRI_TRUE = Optional.of(true); public static final Optional<Boolean> TRI_FALSE = Optional.of(false); public static final Optional<Boolean> TRI_UNKNOWN = Optional.empty(); ``` As a bonus, you will get all those *map* and *consume* methods.
Best way to define true, false, unset state
[ "", "java", "boolean", "" ]
I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null: ``` bool isNull = (i == null); ``` or ``` bool isNull = !i.HasValue; ``` Also when assigning to a non-null type is this: ``` long? i = 1; long j = (long)i; ``` better than: ``` long? i = 1; long j = i.Value; ```
Use the forms that were specially implemented for you by the C# team. If anyone objects, tell them Anders said it was okay. What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience. Note that in terms of performance, both forms compile down to the same IL, ie: ``` int? i = 1; bool isINull = i == null; int j = (int)i; ``` Ends up like this after the C# compiler has got to it: ``` int? i = 1; bool isINull = !i.HasValue; int j = i.Value; ```
I would use this: ``` long? i = 1; ...some code... long j = i ?? 0; ``` That means, if *i* is **null**, than 0 will be assigned.
Using nullable types in C#
[ "", "c#", "nullable", "" ]
I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example: ``` >>> foo = 'baz "\"' >>> foo 'baz ""' ``` So instead of `baz "\"` like I want I'm getting `baz ""`. If I then try to escape the backslash, it doesn't help either: ``` >>> foo = 'baz "\\"' >>> foo 'baz "\\"' ``` Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :) ``` >>> foo = 'baz "\\"' >>> foo 'baz "\\"' >>> print(foo) baz "\" ``` Incidentally, there's another string form which might be a bit clearer: ``` >>> print(r'baz "\"') baz "\" ```
Use a raw string: ``` >>> foo = r'baz "\"' >>> foo 'baz "\\"' ``` Note that although it looks wrong, it's actually right. There is only one backslash in the string `foo`. This happens because when you just type `foo` at the prompt, python displays the result of `__repr__()` on the string. This leads to the following (notice only one backslash and no quotes around the `print`ed string): ``` >>> foo = r'baz "\"' >>> foo 'baz "\\"' >>> print(foo) baz "\" ``` And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem: ``` >>> foo = r'baz \' File "<stdin>", line 1 foo = r'baz \' ^ SyntaxError: EOL while scanning single-quoted string ``` Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes: ``` >>> foo = 'baz \\' >>> print(foo) baz \ ``` However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the `os.path.normpath()` function: ``` myfile = os.path.normpath('c:/folder/subfolder/file.txt') open(myfile) ``` This will save a lot of escaping and hair-tearing. [This page](https://web.archive.org/web/20081029013246/http://pythonconquerstheuniverse.blogspot.com/2008/06/python-gotcha-raw-strings-and.html) was handy when going through this a while ago.
Quoting backslashes in Python string literals
[ "", "python", "string", "" ]
I am using Visual Studio 2008 SP1 (version 9.0.30729.1). My problem is that the only reporting-related toolbox items I see are 3 "Textbox" controls. Where are the other stuff? Do I need to add a reference to a different assembly? Here are the steps I take: 1) Open Visual Studio 2) Add new project --> "Reports Application" 3) Open Report1.rdlc 4) Open the toolbox and no controls are available (except the repeating 3 Textbox controls) Thanks for your help.
My good sense tells me that something got corrupted in your installation. Here's what I would try before attempting a repair (this happened recently): I fixed this by going into my profile as follows: C:\Documents and Settings\MYUSERNAME\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies There are four HIDDEN files in there that make up what is apparently the toolbox cache. If you erase them, they will be re-generated and #13119 will go back to General. As I said, these files appear to be hidden so configure the file explorer accordingly. Second problem: my User controls disappeared from the toolbox. I was able to fix it by going into the VS menus: Visual Studio "Tools" menu "Options" submenu "Windows Form Designer" tab "General" tab Set "AutoToolboxPopulate" to "True"
My problem was The Report Items Toolbox was showing multiple textboxes instead of valid Report controls. Solution: 1) Close the visual studio 2005. 2) delete the folders under C:\Documents and Settings\\Local Settings\application Data\microsoft\visualStudio\ 3) Open your visual studio 2005 project. It should work
No Report Items in toolbox (VS 2008 SP1)
[ "", "c#", "visual-studio-2008", "report", "toolbox", "" ]
I have the following tuple, which contains tuples: ``` MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) ``` I'd like to sort this tuple based upon the **second** value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C). Any thoughts?
``` from operator import itemgetter MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1))) ``` or without `itemgetter`: ``` MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1])) ```
From [Sorting Mini-HOW TO](http://wiki.python.org/moin/HowTo/Sorting#head-d121eed08556ad7cb2a02a886788656dadb709bd) > Often there's a built-in that will > match your needs, such as str.lower(). > The operator module contains a number > of functions useful for this purpose. > For example, you can sort tuples based > on their second element using > operator.itemgetter(): ``` >>> import operator >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)] >>> map(operator.itemgetter(0), L) ['c', 'd', 'a', 'b'] >>> map(operator.itemgetter(1), L) [2, 1, 4, 3] >>> sorted(L, key=operator.itemgetter(1)) [('d', 1), ('c', 2), ('b', 3), ('a', 4)] ``` Hope this helps.
Sorting a tuple that contains tuples
[ "", "python", "sorting", "tuples", "" ]
Is there a way to query the current DATEFORMAT SQLServer 2005 is currently using with T-SQL? I have an application that reads pregenerated INSERT-statements and executes them against a database. To make the data to be inserted culture independent I store datetime-values represented in the invariant culture (month/day/year...) . The database server may run under different locales, depending on the system locale (maybe using day/month/year) , so the insert may crash because the datetime cannot be parsed. I know there are the "SET LANGUAGE" and "SET DATEFORMAT" statements in T-SQL to set the locale to be used. I do not want to make these changes permanent (are they permanent?), so I'm looking for a way to read the DATEFORMAT from the DB, store it, change the format to my liking and reset it to the stored value after the data has been inserted. Any ideas where to find that value in the server?
Set Language and Set DateFormat only affect the current session. If you Disconnect from the database and connect again, the language and Dateformat are set back to their default values. There is a 'trick' you could use to determine if the DateFormat is m/d/y, or d/m/y. ``` Select DatePart(Month, '1/2/2000') ``` This date is valid either way. It's Jan 2, or Feb 1. If this query returns a 1, then you have MDY. If it returns a 2, you have DMY.
The following statement will perform a date parsing operation using a given date format (the @dateFormat variable) and then re enable the original date format. ``` declare @dateFormat nvarchar(3); set @dateFormat = 'dmy'; declare @originalDateFormat nvarchar(3); select @originalDateFormat = date_format from sys.dm_exec_sessions where session_id = @@spid; set dateformat @dateFormat; --Returns 1. select isdate('31/12/2010'); set dateformat @originalDateFormat; ``` Note that the date format changes apply only to the current connection. Re enabling the original date format is only performed to ensure that later statements executed on the same connection are not affected by this change.
Setting and resetting the DATEFORMAT in SQLServer 2005
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "datetime", "" ]
I need to change a static property on an object in our web application. The property has a default value that is hard-coded into the object. If I change the static property in my Application\_Start does that change stick: A) Forever (well, until the app is recycled) B) Until the object is GC'd then re-inialised by the next accessor C) Depends Note that the property I'd be setting is just a String
The scope of a static variable is its AppDomain. So no, it won't get garbage collected - but if the AppDomain is recycled (which can happen a fair amount in ASP.NET) then you'll end up with a "new" static variable, effectively.
In my experience with our web apps here, the answer is A. As far as I know, a static class will never be GCed, it lives on for the life of the process (in this case, the ASP.NET worker process)
The effect of static properties in a web context
[ "", "c#", "asp.net", "" ]
I am embarking on a new RIA project with Java on the backend. I'm the only developer, and the app is a line-of-business application. My current stack looks like this: MySQL || Spring(JdbcTemplate for data access) || BlazeDS (remoting) || Flex(Cairngorm) My question is: what changes can I make to improve productivity? Manually coding SQL, server-side entity objects, client-side value objects and all the Cairngorm stuff is obviously a drag, but I'm not sure what higher-level frameworks to introduce. What Flex/Java stack has served you well?
*Manually coding SQL* [Hibernate](http://www.hibernate.org/) is an option to cut this out. One thing that may be of interest is Grails with the available Flex Plugin. It's built on Spring, Hibernate and BlazeDS, so it's all there for you. It was unbelieveably easy to get it remoting stored objects and responding to AMF calls. I was using this and then moved over to a RESTful E4X implementation as I found it a lot easier to debug and tweak as I could inspect the server output in a browser and have tighter control over exactly what I returned to my Flex app (lazy loading problems in collections using BlazeDS were a headache at times). Here is a quick tutorial showing how easy the whole Grails + Flex Plugin stack is: [BlazeDS in Grails](http://marceloverdijk.blogspot.com/2008/01/blazeds-test-drive-sample-in-grails.html)
I would seriously reconsider using Cairngorm. In my opinion it's a pretty bloated framework that introduces a lot of abstraction you'll never use. Check out: <http://code.google.com/p/swizframework> <http://www.spicefactory.org> Both introduce the concept of dependency-injection into your Flex app. Also +1 for Hibernate. I would use the standard JPA annotations on a Java class and extend that with Hibernate Annotations as you find you need additional functionality.
How to boost productivity in my Flex/Java stack?
[ "", "java", "apache-flex", "frameworks", "" ]
I'm looking for a way to embed an image in a library (Windows-only). I don't want to go the 'traditional' way of putting it in the resources (because of special circumstances that make it not so convenient to mess around with the resource handle. Ideally, there would be something like xpm files: a 'text' representation of an image that is put in a c array and that some code converts into a bitmap in memory, which can then somehow be loaded into an HIMAGE or an HICON. The images I want to embed are 32-bit bitmaps (bmp). Any ideas? I'm using MFC so an MFC library would be fine, but of course I can use a library that doesn't use MFC too. Thanks.
Google for a bin2c utility (something like <http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c>). It takes a file's binary representation and spits out a C source file that includes an array of bytes initialized to that data. Just link the file in and you have your image sitting in a chunk of memory. Using this kind of tool is really common on embedded systems where such things as 'resources' and even files might not exist.
[The Gimp](http://www.gimp.org/) can export to C files. I think that would be the easiest way to do it.
Embed image in code, without using resource section or external images
[ "", "c++", "visual-c++", "mfc", "" ]
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); } ```
Paging depends on Ordering in a strong way. Why not tightly couple the operations? Here's one way to do that: Support objects ``` public interface IOrderByExpression<T> { ApplyOrdering(ref IQueryable<T> query); } public class OrderByExpression<T, U> : IOrderByExpression<T> { public IQueryable<T> ApplyOrderBy(ref IQueryable<T> query) { query = query.OrderBy(exp); } //TODO OrderByDescending, ThenBy, ThenByDescending methods. private Expression<Func<T, U>> exp = null; //TODO bool descending? public OrderByExpression (Expression<Func<T, U>> myExpression) { exp = myExpression; } } ``` The method under discussion: ``` public IQueryable<Category> List(int startIndex, int count, IOrderByExpression<Category> ordering) { NorthwindEntities ent = new NorthwindEntities(); IQueryable<Category> query = ent.Categories; if (ordering == null) { ordering = new OrderByExpression<Category, int>(c => c.CategoryID) } ordering.ApplyOrdering(ref query); return query.Skip(startIndex).Take(count); } ``` Some time later, calling the method: ``` var query = List(20, 20, new OrderByExpression<Category, string>(c => c.CategoryName)); ```
How to check for the presence of an OrderBy in a ObjectQuery<T> expression tree
[ "", "c#", "linq", "generics", "linq-to-entities", "code-generation", "" ]
Is it possible in plain JPA or JPA+Hibernate extensions to declare a composite key, where an element of the composite key is a sequence? This is my composite class: ``` @Embeddable public class IntegrationEJBPk implements Serializable { //... @ManyToOne(cascade = {}, fetch = FetchType.EAGER) @JoinColumn(name = "APPLICATION") public ApplicationEJB getApplication() { return application; } @Column(name = "ENTITY", unique = false, nullable = false, insertable = true, updatable = true) public String getEntity() { return entity; } @GeneratedValue(strategy = GenerationType.AUTO, generator = "INTEGRATION_ID_GEN") @SequenceGenerator(name = "INTEGRATION_ID_GEN", sequenceName = "OMP_INTEGRATION_CANONICAL_SEQ") @Column(name = "CANONICAL_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getCanonicalId() { return canonicalId; } @Column(name = "NATIVE_ID", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeId() { return nativeId; } @Column(name = "NATIVE_KEY", unique = false, nullable = false, insertable = true, updatable = true) public String getNativeKey() { return nativeKey; } //... } ``` I already supply the values for `application`, `entity`, `nativeId` and `nativeKey`. I want to construct an entity like the one below: ``` IntegrationEJB i1 = new IntegrationEJB(); i1.setIntegrationId(new IntegrationEJBPk()); i1.getIntegrationId().setApplication(app1); i1.getIntegrationId().setEntity("Entity"); i1.getIntegrationId().setNativeId("Nid"); i1.getIntegrationId().setNativeKey("NK"); ``` And when I call `em.persist(i1`), I want that the `canonicalId` is generated and the integration is inserted. Is this possible? If so, what's the simple way? (I prefer not to use application-provided keys or native sql).
I believe that this is not possible with plain JPA.
Using @GeneratedValue for composite PKs is not specified withi JPA 2 spec. From the JPA spec: > 11.1.17 GeneratedValue Annotation > > The GeneratedValue annotation provides for the specification of > generation strategies for the values of primary keys. The > GeneratedValue annotation may be applied to a primary key property or > field of an entity or mapped superclass in conjunction with the Id > annotation.[97] The use of the GeneratedValue annotation is only > required to be supported for simple primary keys. Use of the > GeneratedValue annotation is not supported for derived primary keys. Note that under a different scenario, you can have a parent entity with a simple PK (@Id) that uses @GeneratedValue, and then have a child entity that has a composite PK that includes the generated Id from the parent, plus another column. * Give the child a @ManyToOne relationship to the parent entity, so that it inherits the generated ID in a FK column. * Then give the child a composite PK, via @IdClass specified against the entity, plus two @Id columns within the entity. > ``` > @Entity > public class ParentEntity { > ``` ``` @Id @GenerateValue(IDENTITY) // If using DB auto-increment or similar int id; // ... } ``` > ``` > @Entity > @IdClass(ChildId.class) > public class ChildEntity { > // The child table will have a composite PK: > // (parent_ID, child_name) > @Id > @ManyToOne > int parentEntity; > ``` ``` @Id String childName; String favoriteColor; // plus other columns // ... } ``` > ``` > // child Id attributes have the same name as the child entity > // however the types change to match the underlying PK attributes > // (change ParentEntity to int) > public class ChildId implements Serializable { > ``` ``` int parentEntity; String childName; public ChildId() { //... } // Add extra constructor & remove setter methods so Id objects are immutable public ChildId(int parentEntity, String childName) { //... } public int getParentEntity() { //... } // make Id objects immutable: // public void setParentEntity(int parentEntity) { //... } public String getChildName() { //... } // public void setChildName(String childName) { //... } } ```
JPA Composite Key + Sequence
[ "", "java", "hibernate", "jpa", "composite-key", "" ]
I have a program in which the user adds multiple objects to a scene. These objects are all represented as a classes. Now I want the user to be able to save the scenario, so it can be loaded again. Is there some genereic save method I can use, or do I have to write my own that saves the values of all properties and such and then create new objects and insert the saved values into them when the user loads the scenario again. /P Edit: Thanks for the quick replys guys. I'm actually storing default values for the objects in a SQL compact 3.5 database right now. So if anyone knows how to serialize to SQL, that would be great info. Edit 2: Thanks again! I'm going to serialize to xml, then store it as a string to the SQL database.
Assuming your objects have all values available as public properties, you can use an XMLSerializer to convert the object to an XML string, then use a XMLDeserializer to re-create the object. There is an extension method to accomplish this [here](https://stackoverflow.com/questions/271398/post-your-extension-goodies-for-c-net-codeplexcomextensionoverflow#271423). If you have private variables, you can still write your own custom serialize/deserialize methods. Edit in response to original question edit: You can use any of these serialization techniques to store the string into a database. Another option would be to use an ORM (Object Relational Mapper) to bridge the gap between your objects and the databases.
Usually one would use a database to do this kind of thing. That's probably the recommended practise. However if you want a quick and dirty method you can serialise to Xml or Binary with relatively little code. Check out the System.Runtime.Serialization stuff. The trade-off of Xml or Binary is that versioning sucks big time. Consider a collection of xml files containing objects from your 1.0 app. If you've added fields to those objects since 1.0 then they wont be compatible with any new 1.1 objects. To get around this you have to write a manual update sequence from type 1.0 -> 1.1. Even worse if you use autodiscovery code (which automatically serialises) such as they xml or binary serializer you may even have to name your objects different names Product1 / Product1.1 / etc, it's either that or write your own serialisation code. If your app starts approaching any level of seriousness I'd say you'll probably want to use a database. SqlLite is very nice and simple for 1 user apps, anything bigger and you'll want a proper RDBMS.
How to save the state of an C# app to be able to load later
[ "", "c#", ".net", "" ]