Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I wrote a simple javascript function to display a progressbar with the help of JQuery ProgressBar([check here](http://t.wits.sg/misc/jQueryProgressBar/demo.php#)). The progressBar function can be set to display different background images with different values. I want to display values in [0, MAX*0.3] as red, (MAX*0.3, MAX*0.7] as orange, and (MAX*0.7, MAX] as green. So I write a helper function as follows: ``` function setBar(bar, cur, total) { var v1 = parseInt(total * 0.3); var v2 = parseInt(total * 0.7); // if I run alert(v1) and alert(v2) here, the values are all right. bar.progressBar(cur, { max: total, textFormat: 'fraction', boxImage: '/img/pbar/progressbar.gif', barImage: { 0: '/img/pbar/progressbg_red.gif', v1: '/img/pbar/progressbg_orange.gif', v2: '/img/pbar/progressbg_green.gif' } }); } ``` The argument *cur* is the current value while *total* is the MAX value of the progress bar. The function doesn't seem to work, but when I replace "v1:" and "v2:" with actual values like 50 and 120, the function works well. And I have also checked the value of *v1* and v2 before calling bar.progressBar, they are all right. So the problem seems that I cannot pass a variable instead of a constant to the function bar.progressBar, I think it maybe have relations with javascript argument evaluation order, is there any fix to this problem?
try building the object before you pass it: ``` var barImageObj = {}; barImageObj[0] = '/img/pbar/progressbg_red.gif'; barImageObj[v1] = '/img/pbar/progressbg_orange.gif'; barImageObj[v2] = '/img/pbar/progressbg_green.gif'; bar.progressBar(cur, { max: total, textFormat: 'fraction', boxImage: '/img/pbar/progressbar.gif', barImage: barImageObj }); ``` the problem is that javascript interperets `{a:'foo'}` and `{'a':'foo'}` as an object with the string key "a", not with whatever the value of the variable `a` happens to be
Your problem is in ``` barImage: { 0: '/img/pbar/progressbg_red.gif', v1: '/img/pbar/progressbg_orange.gif', v2: '/img/pbar/progressbg_green.gif' } ``` When using the object literal form, the element names are taken as literals, i.e the fact that v1 and v2 are variables has no effect, the object you created has elements 0, 'v1' and 'v2'. To do what you want you need ``` barImage = { }; barImage[0] = '/img/pbar/progressbg_red.gif'; barImage[v1] = '/img/pbar/progressbg_orange.gif'; barImage[v2] = '/img/pbar/progressbg_green.gif'; ```
How does javascript evaluate arguments?
[ "", "javascript", "jquery", "" ]
I have a dll called Test.dll in which I have a class called ABC which has a method FindTYpe. Now, I have a project called TestB and I have added the reference of Test.dll in TestB. Now, if I am trying to find a type XYZ in TestB, from `Test.ABC.FindTYpe()`, it's throwing an exception, `TypeNotLaoded Exception`. Please have a look at the problem and tell me how can I resolve it.
You'll need to post your code for FindType(). My guess is that you're doing something like; ``` System.Reflection.Assembly.GetExecutingAssembly().GetTypes() ``` to find a list of types to search through, and the type in TestB.dll isn't in Test.dll, so the item isn't found. You might want to try something like this instead; ``` /// <summary> /// Returns all types in the current AppDomain /// </summary> public static IEnumerable<Type> LoadedType() { return AppDomain .CurrentDomain .GetAssemblies() .SelectMany(assembly => assembly.GetTypes()); } ``` which should give you the all types loaded into the current application domain -- which, unless you're doing anything odd with appdomains, will be the list of all types loaded into your program. None of the code has been tested, but it should help you find the classes and methods you'll need to use.
Mos probably the type **XYZ** that you are trying to find is not loaded or not present in the paths your app looks for assemblies. The Test.dll and ABC should be present it you added the reference in your project to Test.dll.
How to add an assembly in other assembly?
[ "", "c#", "" ]
I am building a DLL that another application would use. I want to store the current state of some data globally in the DLL's memory before returning from the function call so that I could reuse state on the next call to the function. For doing this, I'm having to save some iterators. I'm using a std::stack to store all other data, but I wasn't sure if I could do that with the iterators also. Is it safe to put list iterators inside container classes? If not, could you suggest a way to store a pointer to an element in a list so that I can use it later? I know using a vector to store my data instead of a list would have allowed me to store the subscript and reuse it very easily, but unfortunately I'm having to use only an std::list.
Yes, it'll work fine. Since so many other answers go on about this being a special quality of list iterators, I have to point out that it'd work with *any* iterators, including vector ones. The fact that vector iterators get invalidated if the vector is modified is hardly relevant to a question of whether it is legal to store iterators in another container -- it *is*. Of course the iterator can get invalidated if you do anything that invalidates it, but that has nothing to do with whether or not the iterator is stored in a stack (or any other data structure).
Iterators to list are invalidated only if the list is destroyed or the "pointed" element is removed from the list.
Storing iterators inside containers
[ "", "c++", "stl", "iterator", "" ]
to create an instance of another class from a class even if the class I want to have an instance of is declared next of the class I am creating an instance from. Just like in C# and Java. Thank you
Sure. You just need a forward declaration. Something like this works just fine: ``` #include <iostream> class B; class A { public: void hello( B &b ); void meow(); }; class B { public: void hello( A &a ); void woof(); }; void A::hello( B &b ) { b.woof(); } void A::meow() { std::cout << "Meow!" << std::endl; } void B::hello( A &a ) { a.meow(); } void B::woof() { std::cout << "Woof!" << std::endl; } int main() { A a; B b; a.hello( b ); b.hello( a ); return 0; } ``` The key here is that you can only use pointers or references to a class until it has been fully defined. So in the example I gave, the hello() method in A can be *declared* to take a reference to B, even though we haven't defined B at the point. After the definition of B, however, the *definition* of the method A::hello() is free to use B as it pleases.
You can use a forward declaration for some purposes, but you will need to have the complete type whenever you actually make use of it. It could be advisable to make the question more specific as to what you really want to achieve, as there might be simpler approaches to your problem (if order is important it might indicate a circular dependency between classes A and B, and that is not usually good). ``` class B; class A { public: A( B b, B* bp, B& br ) : bp_(bp), br_(br) {} // ok, incomplete types can be used as argument types B f() // { return B(); } // nok: cannot create objects of incomplete type ; B* f2() { return bp_; } // ok B& f3() { return br_; }; // ok void g() // { bp_->g(); br_.g(); } // nok: cannot call methods of an incomplete type ; void g( B const & b ) // { b.g(); } // nok: cannot call methods of an incomplete type private: B * bp_; // ok (also const version) B & br_; // ok (also const version) // B b_; // nok: B must be a complete type here }; class B { // A is complete, any use is correct here void g() {} }; // From here on, B is a complete type and can be used in any possible way B A::f() { return B(); // ok, now B is complete } void A::g() { br_.g(); // ok, B is complete here bp_->g(); // ok, B is complete here } void A::g( B const & b ) { b.g(); } ```
is this possible in C++?
[ "", "c++", "class", "" ]
I have a prototype: ``` int[] medianFileter(int[] data); ``` and an array ``` int[] intVal = new int[5]; ``` How can I pass the intVal to the prototype in C#?
Um, you just call it (assuming you've got a real implementation to call): ``` int[] result = medianFileter(intVal); ``` Note that any changes made to the array within the method will show up in `intVal`: you're not passing each of the integers individually, but a reference to the whole array. (There could be some trickiness here due to your use of the word "prototype" - it's not standard C# terminology, so I'm not exactly sure what you mean. If you could clarify the question, that would help.) On a side note, method names in .NET are usually Pascal-cased, so this should probably be: ``` int[] result = ApplyMedianFilter(intVal); ```
It's either I don't see some obvious weirdness here, or it's just usual function invocation: ``` int[] medianFiltered = medialFileter(intVal); ```
How to pass array in C#
[ "", "c#", "" ]
I have the following code for adding to/extracting from Zip. I'm trying to refactor this to make it test-ready. Can someone provide pointers on how I can accomplish this? Aside: I'm using Moq as my mock framework and MSTest as my Unit Testing tool ``` private const long BufferSize = 4096; public static void ExtractZip(string zipFilename, string folder) { using (var zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)) { foreach (var part in zip.GetParts()) { using (var reader = new StreamReader(part.GetStream(FileMode.Open, FileAccess.Read))) { using (var writer = new FileStream(folder + "\\" + Path.GetFileName(part.Uri.OriginalString), FileMode.Create, FileAccess.Write)) { var buffer = System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd()); writer.Write(buffer, 0, buffer.Length); } } } } } public static void AddFileToZip(string zipFilename, string fileToAdd) { using (var zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)) { var destFilename = ".\\" + Path.GetFileName(fileToAdd); var uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative)); if (zip.PartExists(uri)) { zip.DeletePart(uri); } var part = zip.CreatePart(uri, "", CompressionOption.Normal); using (var fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read)) { using (var dest = part.GetStream()) { CopyStream(fileStream, dest); } } } } ``` Thanks in advance.
I would make these two static methods (ExtractZip and AddFileToZip) instance methods, and put it into an interface: ``` public interface IZipper { void ExtractZip(string zipFilename, string folder); void AddFileToZip(string zipFilename, string fileToAdd); } public class Zipper : IZipper { public void ExtractZip(string zipFilename, string folder) { //... } void AddFileToZip(string zipFilename, string fileToAdd) { //... } } // client code class Foo { private IZipper myZipper; // gets an instance of the zipper (injection), but implements only // against the interface. Allows mocks on the IZipper interface. public Foo(IZipper zipper) { myZipper = zipper; } } ``` Client code is now easy to test. What about the Zipper class? * Consider if it is worth to test anyway. * In our project, we distinguish between unit tests (isolated) and integration tests, where it is possible to use the database or the file system. You could declare it as an "file system integration test". Of course, only the test target folder is allowed to be used. This shouldn't make any problems. * Consider to move the file operations out, and only work with streams. Then you can easily test the zipping on memory streams. The file operations still need to be somewhere and aren't tested.
I'm pasting the final code here as it might help someone and also allow me to get feedback. Thanks to Stefan for pointing me in the right direction. ``` /// <summary> /// The commented methods are marked for future /// </summary> public interface IZipper { //void Create(); void ExtractAll(); void ExtractAll(string folder); //void Extract(string fileName); void AddFile(string fileName); //void DeleteFile(string fileName); } public interface IZipStreamProvider { Stream GetStream(string fileName); } public class ZipStreamProvider : IZipStreamProvider { public Stream GetStream(string fileName) { //Create a read/writable file return new FileStream(fileName, FileMode.Create); } } public class Zipper : IZipper { private const long BufferSize = 4096; public string ZipFileName { get; set;} //seam.. to use property injection private IZipStreamProvider ZipStreamProvider { get; set;} public Zipper(string zipFilename) { ZipFileName = zipFilename; //By default, write to file ZipStreamProvider = new ZipStreamProvider(); } public void ExtractAll() { ExtractAll(Environment.CurrentDirectory); } public void ExtractAll(string folder) { using (var zip = System.IO.Packaging.Package.Open(ZipStreamProvider.GetStream(ZipFileName))) { foreach (var part in zip.GetParts()) { using (var reader = new StreamReader(part.GetStream(FileMode.Open, FileAccess.Read))) { using (var writer = ZipStreamProvider.GetStream(folder + "\\" + Path.GetFileName(part.Uri.OriginalString))) { var buffer = System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd()); writer.Write(buffer, 0, buffer.Length); } } } } } public void AddFile(string fileToAdd) { using (var zip = System.IO.Packaging.Package.Open(ZipFileName, FileMode.OpenOrCreate)) { var destFilename = ".\\" + Path.GetFileName(fileToAdd); var uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative)); if (zip.PartExists(uri)) { zip.DeletePart(uri); } var part = zip.CreatePart(uri, "", CompressionOption.Normal); using (var fileStream = ZipStreamProvider.GetStream(fileToAdd)) { using (var dest = part.GetStream()) { CopyStream(fileStream, dest); } } } } private long CopyStream(Stream inputStream, Stream outputStream) { var bufferSize = inputStream.Length < BufferSize ? inputStream.Length : BufferSize; var buffer = new byte[bufferSize]; int bytesRead; var bytesWritten = 0L; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0) { outputStream.Write(buffer, 0, bytesRead); bytesWritten += bufferSize; } return bytesWritten; } } ```
Unit Testing Adding to Zip / Extracting from Zip
[ "", "c#", "unit-testing", "mocking", "mstest", "stubbing", "" ]
I wanted to call Test1() Method Within WaitAndCallFunc() Function. Code: ``` typedef void (*func)(); void StartTimer(void* pFuncAddr); void WaitAndCallFunc(void* pPtr); void WaitAndCallFunc(void* pPtr) { int i = 0; int nWaitTime = 3; while(1) { Sleep(1000); // I want pPtr to call Test1 Function; if(i == nWaitTime) break; } _endthread(); } void StartTimer(void* pFuncAddr) { _beginthread(WaitAndCallFunc, 0, pFuncAddr); } void Test1(); int main(int argc, char* argv[]) { StartTimer(Test1); Sleep(5000); return 0; } void Test1() { cout << "Testing Thread\n"; } ```
I'm not sure I understand what your question is exactly, but try this: ``` ((func)pPtr)(); ```
Cast and call: ``` typedef void (*func)(); void WaitAndCallFunc(void* pPtr) { int i = 0; int nWaitTime = 3; while(1) { Sleep(1000); func f=(func)pPtr; // cast to correct pointer to function type f(); // and call! if(i == nWaitTime) break; } _endthread(); } ```
How to Convert Address to Function Pointer to Call Method
[ "", "c++", "c", "multithreading", "function-pointers", "" ]
Does anyone know if you can programmatically save a report shown in a reportviewer control in C#? When a report is shown there are "Export to..." buttons and I would like to automate the saving to PDF function.
You can do this with [ReportViewer Control](http://msdn.microsoft.com/en-us/library/ms251771(VS.80).aspx)(with [LocalReport.Render Method](http://msdn.microsoft.com/en-us/library/ms251839(VS.80).aspx)), check "Email a report" example at the <http://www.gotreportviewer.com/>
``` string _sPathFilePDF = String.Empty; String v_mimetype; String v_encoding; String v_filename_extension; String[] v_streamids; Microsoft.Reporting.WinForms.Warning[] warnings; string _sSuggestedName = String.Empty; Microsoft.Reporting.WinForms.ReportViewer reportViewer1; Microsoft.Reporting.WinForms.LocalReport objRDLC = new Microsoft.Reporting.WinForms.LocalReport(); reportViewer1.LocalReport.ReportEmbeddedResource = "reportViewer1.rdlc"; reportViewer1.LocalReport.DisplayName = _sSuggestedName; objRDLC.DataSources.Clear(); byte[] byteViewer = rptvFlightPlan.LocalReport.Render("PDF", null, out v_mimetype, out v_encoding, out v_filename_extension, out v_streamids, out warnings); SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "*PDF files (*.pdf)|*.pdf"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; saveFileDialog1.FileName = _sSuggestedName; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { FileStream newFile = new FileStream(saveFileDialog1.FileName, FileMode.Create); newFile.Write(byteViewer, 0, byteViewer.Length); newFile.Close(); } ```
Export C# reportviewer control programmatically
[ "", "c#", "export", "reportviewer", "" ]
I am trying to convert an array of the RECT structure (given below) into an IntPtr, so I can send the pointer using PostMessage to another application. ``` [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; // lots of functions snipped here } // so we have something to send, in reality I have real data here // also, the length of the array is not constant RECT[] foo = new RECT[4]; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(foo[0]) * 4); Marshal.StructureToPtr(foo, ptr, true); // -- FAILS ``` This gives an ArgumentException on the last line ("The specified structure must be blittable or have layout information."). I need to somehow get this array of RECTs over to another application using PostMessage, so I really need a pointer to this data. What are my options here? *UPDATE*: This seems to work: ``` IntPtr result = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.RECT)) * foo.Length); IntPtr c = new IntPtr(result.ToInt32()); for (i = 0; i < foo.Length; i++) { Marshal.StructureToPtr(foo[i], c, true); c = new IntPtr(c.ToInt32() + Marshal.SizeOf(typeof(Win32.RECT))); } ``` *UPDATED AGAIN* to fix what arbiter commented on.
StructureToPtr expects struct object, and foo is not structure it is array, that is why exception occurs. I can suggest you to write structures in cycle (sadly, StructureToPtr does not have overload with Index): ``` long LongPtr = ptr.ToInt64(); // Must work both on x86 and x64 for (int I = 0; I < foo.Length; I++) { IntPtr RectPtr = new IntPtr(LongPtr); Marshal.StructureToPtr(foo[I], RectPtr, false); // You do not need to erase struct in this case LongPtr += Marshal.SizeOf(typeof(Rect)); } ``` Another option is to write structure as four integers, using Marshal.WriteInt32: ``` for (int I = 0; I < foo.Length; I++) { int Base = I * sizeof(int) * 4; Marshal.WriteInt32(ptr, Base + 0, foo[I].Left); Marshal.WriteInt32(ptr, Base + sizeof(int), foo[I].Top); Marshal.WriteInt32(ptr, Base + sizeof(int) * 2, foo[I].Right); Marshal.WriteInt32(ptr, Base + sizeof(int) * 3, foo[I].Bottom); } ``` And the last, you can use **unsafe** keyword, and work with pointers directly.
Arbiter has given you one good answer for how to marshal arrays of structs. For blittable structs like these I, personally, would use unsafe code rather than manually marshaling each element to unmanaged memory. Something like this: ``` RECT[] foo = new RECT[4]; unsafe { fixed (RECT* pBuffer = foo) { //Do work with pointer } } ``` or you could pin the array using a GCHandle. Unfortunately, you say you need to send this information to another process. If the message you are posting is not one of the ones for which Windows provides automatic marshaling then you have another problem. Since the pointer is relative to the local process it means nothing in the remote process and posting a message with this pointer will cause unexpected behavior, including likely program crash. So what you need to do is write the RECT array to the other process' memory not your own. To do this you need to use OpenProcess to get a handle to the process, VitualAllocEx to allocate the memory in the other process and then WriteProcessMemory to write the array into the other process' virtual memory. Unfortunately again, if you are going from a 32bit process to a 32bit process or from a 64bit process to a 64bit process things are quite straightforward but from a 32bit process to a 64bit process things can get a little hairy. VirtualAllocEx and WriteProcessMemory are not really supported from 32 to 64. You may have success by trying to force VirtualAllocEx to allocate its memory in the bottom 4GB of the 64bit memory space so that the resultant pointer is valid for the 32bit process API calls and then write with that pointer. In addition, you may have struct size and packing differences between the two process types. With RECT there is no problem but some other structs with packing or alignment issues might need to be manually written field by field to the 64bit process in order to match the 64bit struct layout.
Convert array of structs to IntPtr
[ "", "c#", ".net", "marshalling", "" ]
I'm trying to find the best way (in code) to determine the final destination of a shortened URL. For instance <http://tinyurl.com> redirects to an eBay auction. I'm trying to get the URL for the eBay auction. I'm trying to do this from within .NET so I can compare multiple URLs to ensure that there is no duplicates. TIA
While I spent a minute writing the code to ensure that it worked the answer was already delivered, but I post the code anyway: ``` private static string GetRealUrl(string url) { WebRequest request = WebRequest.Create(url); request.Method = WebRequestMethods.Http.Head; WebResponse response = request.GetResponse(); return response.ResponseUri.ToString(); } ``` This will work as long as the short url service does a regular redirect.
You should issue a HEAD request to the url using a HttpWebRequest instance. In the returned HttpWebResponse, check the ResponseUri. Just make sure the AllowAutoRedirect is set to true on the HttpWebRequest instance (it is true by default).
Determine Final Destination of a Shortened URL
[ "", "c#", "asp.net", "class", "" ]
I have used two GUIDs to open the folders *My Computer* and *My Documents*. ``` Process.Start("iexplore.exe", "::{20d04fe0-3aea-1069-a2d8-08002b30309d}"); Process.Start("iexplore.exe", "::{450d8fba-ad25-11d0-98a8-0800361b1103}"); ``` But it opens Internet Explorer and then opens the folders *My Computer* and *My Documents*.
Better still would be to skip `explorer` entirely and just "start" the GUIDs directly: `Process.Start("::{20d04fe0-3aea-1069-a2d8-08002b30309d}");`...
Using those hard coded Guid values doesn't look like the best way of achieving this. You could use the [Environment.GetFolderPath](http://msdn.microsoft.com/en-us/library/14tx8hby.aspx) function to get the path of any of the system special folders. It accepts an [Environment.SpecialFolder](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx) enum. This way it'd be more robust, because you wouldn't have any "magic" hardcoded values. Here's how you'd use it: ``` //get the folder paths string myComputerPath = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //open explorer and point it at the paths System.Diagnostics.Process.Start("explorer", myComputerPath); System.Diagnostics.Process.Start("explorer", myDocumentsPath); ``` **Important note for Windows 7 users** It seems that trying to use this code to open My Computer on Windows 7 incorrectly results in the Libraries folder being opened instead. This is because the default behaviour of running explorer with an empty path has changed in Windows 7. I've filed the following bug report over at connect, go and give it an upvote if you think that this is important! <https://connect.microsoft.com/VisualStudio/feedback/details/757291/environment-getfolderpath-not-working-correctly-in-windows-7#details> *(Thanks to JeremyK in the comments for pointing this out)*
How do I open the "My Documents" and "My Computer" folders from C#?
[ "", "c#", "shortcut", "" ]
I have an API that can be implemented by various vendors. I can send and receive data and get different return codes with the API. What I want to do is be able to test the API and in an automated fashion and keep everything as clean as possible. Not really doing unit testing. This would be for use in a testing/QA setting. What I have done is to create a dummy app in C# and use NUnit to create a suite of tests. So I have all the tests in different classes based on functionality and I can start up NUnit and run my tests and see my results. I like how I can do setup and tear down. This allows me to get the API into a known state. I also like the assertion methods in NUnit. I don't think this is the intention of NUnit, I would expect most people use NUnit inside of their app to test their own code. My question is, how bad is what I am doing? And what would be better?
This sounds fine, I think. I imagine if you didn't use NUnit, you'd just write something yourself that was a poor copy of NUnit, so stay with it.
What you are doing is perfectly legitimate. Just because the author may not have intended it shouldn't deter you at all. There is definitely value to it... just wait until you get the first update from the vendor and can verify the existing API still works. I've done the same sort of thing in C with CUnit.
Using automated unit test for black box integration test, how bad is that and what is better?
[ "", "c#", "nunit", "automated-tests", "black-box", "" ]
Is there any java utility to convert string to hex value (integer) ?
When you have a string starting with 0x or # ``` Integer.decode(hexStr); ``` is the goal Or ``` Integer.parseInt(hexString, 16); ```
Is this what you are looking for? ``` Integer.toHexString(Integer.parseInt(String)); ```
string to hex value
[ "", "java", "string", "" ]
Is having tags inside a jstl tag considered bad form? So for example I know the following will work but is it considered bad form to have the script tags inside my jstl tags in my jsp ? ``` <c:choose> <c:when test="${!empty bean.value}"> <p>Its not empty</p> </c:when> <c:otherwise> **<script> callJSSomeFunction(); </script>** </c:otherwise> </c:choose> ```
I don't know about *bad form* (a bit harsh) but you might consider that to someone viewing your page without JS enabled your `<c:otherwise>` will effectively output nothing, and that's not very graceful. Also, if the page is rendered incrementally your function call might execute as it has been ouput, and before the DOM has been fully loaded by the browser and thus behave unpredictably (or just not work at all - I've had this happen). I would consider putting all function invocations in the head, and use one of the many available tricks for detecting when the DOM has loaded ([jQuery's $(document).ready() for example](http://docs.jquery.com/How_jQuery_Works)) to enforce a neater separation, and make your life that much easier.
I don't think so - this is how you conditionally do things in JSTL, I don't think you should have a script tag just to have one.
JSTL and Javascript
[ "", "javascript", "jsp", "jstl", "" ]
I'm trying to test code around a web service that is not available yet. I'm trying to dummy up my own version. According to the specs it will be called like this. ``` var service = new Service(); service.SD = new ServiceData(); service.SD.ID = "ABC123"; service.SD.Auth = "00000"; string result = service.DoMyThing(); ``` This is the closest I've gotten. ``` var service = new Service(); service.set_SD(new ServiceData()); service.get_SD().ID = "ABC123"; service.get_SD().Auth = "00000"; service.DoMyThing(); ``` The problem is with the SD property. How do I write the service so that Visual Studio 2008 generates the web reference correctly? Here is my current dummy web service code. ``` public class Service : System.Web.Services.WebService { // This doesn't show up in the generated proxy at all public static ServiceData SDTest; // For extra credit explain why this needs to be static for it to work private static ServiceData _sd; public ServiceData SD { [WebMethod(EnableSession = true)] get { return _sd; } [WebMethod(EnableSession = true)] set { _sd = value; } } [WebMethod] public string DoMyThing() { // Presumably the real service accesses SD in here return ""; } } public class ServiceData { public string ID { get; set; } public string Auth { get; set; } } ```
I'm with casperOne on this. I think using fakie properties are more annoying than useful. Still, if you're married to this just eliminate the getter for the property. You don't need it. Do this instead: ``` var service = new Service(); ServiceData sd = new ServiceData(); sd.ID = "ABC123"; sd.Auth = "00000"; service.SD = sd; string result = service.DoMyThing(); ``` If Visual Studio still names the setter property incorrectly you can use one of the soap attributes to rename it. **EDIT:** You'll also need to define SD as a SOAP Header.
Your design is flawed. Web services are not meant to have properties. They should only expose methods, the reason being that the HTTP protocol is stateless (and web services assume this too), so exposing a property doesn't make sense unless you want it to apply to all callers of the instance (and still, even in that situation, it doesn't make sense to expose it). Rather, what you want to do is have the DoMyThing method take the instance of ServiceData (if required) and operate on that, returning the appropriate result set. If you really have a need to expose properties of the service, you would have a GetProperties method (or something like that) which takes no parameters and returns the appropriate data structure with the service information.
Can I Create a Web Service that has Properties?
[ "", "c#", "web-services", "properties", "asmx", "" ]
I am writing unit for a class which looks like following using nunit and Rhino mock. ``` Class MyClass { private void M() { N("Hi"); } private void N(string text) { ........ do something } } ``` For the unit test for method M I want to check if method N was called with argument "Hi". How do I do it?
It seems to me that from the point of view of testing, you're delving into the implementation details of your object. Can't you perform your tests by checking the ultimate result of your method call ? That is, presumably these method calls have some effect. So rather than checking the arguments being passed, you should be checking the final result. That way you can change your underlying code at a later date, and your unit tests will confirm that the ultimate result is the same, independent of your implementation.
+1 to Brian's response. The alternative is to split "N" out to a different class, and then use a mocked instance of that class in your test. You can then set up the mock to expect a call with a specific parameter. But, it might not actually be appropriate to split it out. Depends on your exact scenario.
How to check if a private method was called with expected argument in unit test?
[ "", "c#", "unit-testing", "" ]
In the book "The C Programming Language" it says: > "Many of the functions in the library set status indicators when error or end of file occur. These > indicators may be set and tested explicitly. In addition, the integer expression `errno` (declared > in `<errno.h>`) may contain an error number that gives further information about the most > recent error." Where can I see a list of these functions?
The standard says this about `errno`: > The value of errno is zero at program startup, but is never set to zero by any library > function. The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard. Which says to me that any library function can screw around with `errno` in any way it likes except: * it can't set `errno` to `0` * it can't do what it likes if the standard explicitly says otherwise Note that the standard suggests the following in a footnote: > Thus, a program that uses `errno` for error checking should set it to zero before a library function call, then inspect it before a subsequent library function call. Of course, a library function can save the value of `errno` on entry and then set it to zero, as long as the original value is restored if `errno`'s value is still zero just before the return. As noted in other answers, it's common for functions that are not in the standard to set `errno` as well.
You should assume that any function can set errno, not just those in the standard library. A list would therefore be a little pointless.
Where can I see the list of functions that interact with errno?
[ "", "c++", "c", "error-handling", "standard-library", "errno", "" ]
I've been tasked with taking an **existing single threaded monte carlo simulation** and **optimising** it. This is a c# console app, no db access it loads data once from a csv file and writes it out at the end, so it's **pretty much just CPU bound**, also only uses about 50mb of memory. I've run it through Jetbrains dotTrace profiler. Of total execution time about 30% is generating uniform random numbers, 24% translating uniform random numbers to normally distributed random numbers. The basic **algorithm is a whole lot of nested for loops**, with random number calls and matrix multiplication at the centre, each iteration returns a double which is added to a results list, this list is periodically sorted and tested for some convergence criteria (at check points every 5% of total iteration count) if acceptable the program breaks out of the loops and writes the results, else it proceeds to the end. I'd like developers to weigh in on: * should I use **new Thread v ThreadPool** * should I look at the **Microsoft Parallels Extension library** * should I look at **AForge.Net Parallel.For**, <http://code.google.com/p/aforge/> any other libraries? Some **links to tutorials** on the above would be most welcome as **I've never written any parallel or multi-threaded code**. * best strategies for generating en-mass normally distributed random numbers, and then consuming these. Uniform random numbers are never used in this state by the app, they are always translated to **normally distributed** and then consumed. * good fast libraries (parallel?) for random number generation * **memory considerations as I take this parallel**, how much extra will I require. Current app takes 2 hours for 500,000 iterations, business needs this to scale to 3,000,000 iterations and be called mulitple times a day so need some heavy optimisation. **Particulary would like to hear from people** who have used **Microsoft Parallels Extension** or **AForge.Net Parallel** This needs to be productionised fairly quickly so **.net 4 beta is out** even though I know it has concurrency libraries baked in, we can look at migrating to .net 4 later down the track once it's released. For the moment the server has .Net 2, I've submitted for review an upgrade to .net 3.5 SP1 which my dev box has. Thanks **Update** I've just tried the Parallel.For implementation but it comes up with some weird results. Single threaded: ``` IRandomGenerator rnd = new MersenneTwister(); IDistribution dist = new DiscreteNormalDistribution(discreteNormalDistributionSize); List<double> results = new List<double>(); for (int i = 0; i < CHECKPOINTS; i++) { results.AddRange(Oblist.Simulate(rnd, dist, n)); } ``` To: ``` Parallel.For(0, CHECKPOINTS, i => { results.AddRange(Oblist.Simulate(rnd, dist, n)); }); ``` Inside simulate there are many calls to rnd.nextUniform(), **I think I am getting many values that are the same**, is this likely to happen because this is now parallel? Also maybe issues with the List AddRange call not being thread safe? I see this System.Threading.Collections.BlockingCollection might be worth using, but it only has an Add method no AddRange so I'd have to look over there results and add in a thread safe manner. Any insight from someone who has used Parallel.For much appreciated. I switched to the **System.Random** for my calls temporarily as I was getting an exception when calling nextUniform with my Mersenne Twister implementation, **perhaps it wasn't thread safe** a certain array was getting an **index out of bounds**....
First you need to understand why you think that using multiple threads is an optimization - when it is, in fact, not. Using multiple threads will make your workload complete faster *only* if you have multiple processors, and then at most as many times faster as you have CPUs available (this is called the *speed-up*). The work is not "optimized" in the traditional sense of the word (i.e. the amount of work isn't reduced - in fact, with multithreading, the total amount of work typically grows because of the threading overhead). So in designing your application, you have to find pieces of work that can be done in a parallel or overlapping fashion. It may be possible to generate random numbers in parallel (by having multiple RNGs run on different CPUs), but that would also change the results, as you get different random numbers. Another option is have generation of the random numbers on one CPU, and everything else on different CPUs. This can give you a maximum speedup of 3, as the RNG will still run sequentially, and still take 30% of the load. So if you go for this parallelization, you end up with 3 threads: thread 1 runs the RNG, thread 2 produces normal distribution, and thread 3 does the rest of the simulation. For this architecture, a [producer-consumer architecture](http://devpinoy.org/blogs/jakelite/archive/tags/Threading+Patterns/default.aspx) is most appropriate. Each thread will read its input from a queue, and produce its output into another queue. Each queue should be blocking, so if the RNG thread falls behind, the normalization thread will automatically block until new random numbers are available. For efficiency, I would pass the random numbers in array of, say, 100 (or larger) across threads, to avoid synchronizations on every random number. For this approach, you don't need any advanced threading. Just use regular thread class, no pool, no library. The only thing that you need that is (unfortunately) not in the standard library is a blocking Queue class (the Queue class in System.Collections is no good). [Codeproject](http://www.codeproject.com/KB/recipes/boundedblockingqueue.aspx) provides a reasonably-looking implementation of one; there are probably others.
`List<double>` is definitely not thread-safe. See the section "thread safety" in the [System.Collections.Generic.List documentation](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx). The reason is performance: adding thread safety is not free. Your random number implementation also isn't thread-safe; getting the same numbers multiple times is exactly what you'd expect in this case. Let's use the following simplified model of `rnd.NextUniform()` to understand what is happening: 1. calculate pseudo-random number from the current state of the object 2. update state of the object so the next call yields a different number 3. return the pseudo-random number Now, if two threads execute this method in parallel, something like this may happen: * Thread A calculates a random number as in step 1. * Thread B calculates a random number as in step 1. Thread A has not yet updated the state of the object, so the result is the same. * Thread A updates the state of the object as in step 2. * Thread B updates the state of the object as in step 2, trampling over A's state changes or maybe giving the same result. As you can see, any reasoning you can do to prove that `rnd.NextUniform()` works is no longer valid because two threads are interfering with each other. Worse, bugs like this depend on timing and may appear only rarely as "glitches" under certain workloads or on certain systems. Debugging nightmare! One possible solution is to eliminate the state sharing: give **each task its own random number generator** initialized with another seed (assuming that instances are not sharing state through static fields in some way). Another (inferior) solution is to create a field holding **a lock object** in your `MersenneTwister` class like this: ``` private object lockObject = new object(); ``` Then use this lock in your `MersenneTwister.NextUniform()` implementation: ``` public double NextUniform() { lock(lockObject) { // original code here } } ``` This will prevent two threads from executing the NextUniform() method in parallel. The problem with the list in your `Parallel.For` can be addressed in a similar manner: separate the `Simulate` call and the `AddRange` call, and then add locking around the `AddRange` call. My recommendation: avoid sharing any mutable state (like the RNG state) between parallel tasks if at all possible. If no mutable state is shared, no threading issues occur. This also avoids locking bottlenecks: you don't want your "parallel" tasks to wait on a single random number generator that doesn't work in parallel at all. Especially if 30% of the time is spend acquiring random numbers. Limit state sharing and locking to places where you can't avoid it, like when aggregating the results of parallel execution (as in your `AddRange` calls).
Migrate a single threaded app to multi-threaded, parallel execution, monte carlo simulation
[ "", "c#", "multithreading", "parallel-processing", "threadpool", "" ]
Is there a jQuery way to perform iteration over an object's members, such as in: ``` for (var member in obj) { ... } ``` I just don't like this `for` sticking out from amongst my lovely jQuery notation!
``` $.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); }); ``` [each](https://api.jquery.com/jquery.each/)
You can use [`each`](https://api.jquery.com/jquery.each/) for objects too and not just for arrays: ``` var obj = { foo: "bar", baz: "quux" }; jQuery.each(obj, function(name, value) { alert(name + ": " + value); }); ```
Iterating a JavaScript object's properties using jQuery
[ "", "javascript", "jquery", "for-loop", "iteration", "" ]
I'm working with a 3rd party system to implement some forms in a website. The 3rd party system provides me with XML definitions for these forms. e.g. ``` <form> <segment> <label>The header</label> <fields> ... <field> <id>field_Dob</id> <type>Date</type> <label>Date of Birth</label> <required>1</required> </field> ... </fields> </segment> ... </form> ``` I am parsing this XML in a Server Control and programatically generating a tree of controls. The labels of the controls are passed through in the XML. It is part of our proposal to "inject" little help texts into this form. Ideally I would like to pass these help texts in from the markup of the top level control so that non-developers (HTML monkies) can change the help texts, and associate them with the field by it's ID. Something like so ``` <controls:MyCrazyForm runat="server"> <helpTexts> <helpText for="field_Dob"> Some rambling nonsense to do with the DOB field </helpText> ... </helpTexts> </controls:MyCrazyForm> ``` The controls are parsed recursively. The Form creates a fieldset for each segment, fieldsets create many FieldXXX (where XXX = date, text, combobox etc) depending on the data type. The FieldXXX types create a div and then several standard .net controls (TextBox, DropDownList, etc) to actually render themselves. It is at this point, within the containing div that I need to output the help text. **My Question** What is the "best" way to get these texts from the top-level form control to these child controls which are 3 or 4 levels deeper in the control tree. There will only ever be one of these forms on a page. Should I make the top level form as Singleton and get it like so...? ``` if(MyCrazyForm.Instance.HelpTexts.ContainsKey("theIdOfTheCurrentField")) { this.HelpText = MyCrazyForm.Instance.HelpTexts["theIdOfTheCurrentField"]; } ``` Should I pass a reference to the form into every control all the way down the tree (this seems messy)? Am I miles of target with my *architecture* of this (although it's working realyl nicely at the moment) form and should I look at a different method of implementation? Thanks
It may be more complicated at first, but makes it easier to maintain, why not run the xml file through an xsl procesor? The xslt file would assign the helptext nodes of your helptexts file to the corresponding field nodes. ``` <?xml version="1.0" encoding="ISO-8859-1"?> <form> <segment> <label>The header</label> <fields> <field> <id>field_name</id> <type>string</type> <label>Name</label> <required>1</required> </field> <field> <id>field_Dob</id> <type>Date</type> <label>Date of Birth</label> <required>1</required> </field> </fields> </segment> </form> ``` XSLT file: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/> <xsl:template match="/form/segment/fields/field[id='field_name']"> <xsl:copy> <xsl:element name="helptext">This is a Name helptext.</xsl:element> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="/form/segment/fields/field[id='field_Dob']"> <xsl:copy> <xsl:element name="helptext">This is a Date of birth helptext.</xsl:element> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="node() | text()"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates/> </xsl:copy> </xsl:template> </xsl:stylesheet> ``` yields this: ``` <form> <segment> <label>The header</label> <fields> <field> <helptext>This is a Name helptext.</helptext> <id>field_name</id> <type>string</type> <label>Name</label> <required>1</required> </field> <field> <helptext>This is a Date of birth helptext.</helptext> <id>field_Dob</id> <type>Date</type> <label>Date of Birth</label> <required>1</required> </field> </fields> </segment> </form> ``` This xml file can now be parsed like before, but now you can get the help text at the same time as you are generating the form elements. Your HTML monkies then only need to edit the XSLT file, or you simply include another file : ``` <xsl:template match="/form/segment/fields/field[id='field_Dob']"> <xsl:copy> <xsl:element name="helptext"> <xsl:copy-of select="document('field_Dob.txt')"/> </xsl:element> <xsl:apply-templates/> </xsl:copy> </xsl:template> ``` You can try out XSL online [here](http://www.tnevin.com/xslt/xslt/translator.faces)
As well as looking at different ways of passing information between controls, as the other answers here have put forward, I think that a different approach may be of value, depending on the specifics of your case. An analogous problem to the one you describe - associating some specific text with some controls on a form - has been solved for the more general case of internationalization, with Resources. I know this is different from the other answers and not directly what you asked in your question, but Resources seem to meet the needs quite well, as described below. Rather than answer your specific question about information flow between controls, I'm trying to consider the end result you're trying to achieve. Go easy on me if I've misunderstood anything :-) 1. Each form and field within a form have a unique identity. Hence, a resource ID can be constructed uniquely from the form and field. 2. A resource source file is just XML, completely separate from the specifics of the UI and can be given over to non-developers to fill up with the relevant help text. If you change the UI, this file need not change *at all*. 3. At render time, you can just get the resource for a field in a form using its resource ID and incorporate the text in the UI any how you want. 4. As the same approach is used for I18N/L10N, it is well documented, well understood, declarative, simple and performant.
The correct pattern for passing data to child controls in a server control
[ "", "c#", "asp.net", ".net-3.5", "servercontrols", "" ]
What is a good random number generator to use for a game in C++? My considerations are: 1. Lots of random numbers are needed, so speed is good. 2. Players will always complain about random numbers, but I'd like to be able to point them to a reference that explains that I really did my job. 3. Since this is a commercial project which I don't have much time for, it would be nice if the algorithm either a) was relatively easy to implement or b) had a good non-GPL implementation available. 4. I'm already using `rand()` in quite a lot of places, so any other generator had better be good to justify all the changes it would require. I don't know much about this subject, so the only alternative I could come up with is the [Mersenne Twister](http://en.wikipedia.org/wiki/Mersenne_Twister); does it satisfy all these requirements? Is there anything else that's better? --- Mersenne Twister seems to be the consensus choice. But what about point #4? Is it really that much better than `rand()`? Let me be a little clearer on point 2: There is no way for players to cheat by knowing the random numbers. Period. I want it random enough that people (at least those who understand randomness) can't complain about it, but I'm not worried about predictions. That's why I put speed as the top consideration.
[George Marsaglia](http://en.wikipedia.org/wiki/George_Marsaglia) has developed some of the best and fastest RNGs currently available [Multiply-with-carry](http://en.wikipedia.org/wiki/Multiply-with-carry) being a notable one for a uniform distribution. **=== Update 2018-09-12 ===** For my own work I'm now using [Xoshiro256\*\*](https://github.com/colgreen/Redzen/blob/master/Redzen/Random/Xoshiro256StarStarRandom.cs), which is a sort of evolution/update on Marsaglia's XorShift. **=== Update 2021-02-23 ===** In .NET 6 (currently in preview) the implementation of System.Random has been changed to use xoshiro256\*\*, but only for the parameterless constructor. The constructor that takes a seed uses the old PRNG in order to maintain backwards compatibility. For more info see [Improve Random (performance, APIs, ...)](https://github.com/dotnet/runtime/pull/47085)
The other thread mentioned Marsaglia's xorshf generator, but no one posted the code. ``` static unsigned long x=123456789, y=362436069, z=521288629; unsigned long xorshf96(void) { //period 2^96-1 unsigned long t; x ^= x << 16; x ^= x >> 5; x ^= x << 1; t = x; x = y; y = z; z = t ^ x ^ y; return z; } ``` I've used this one all over the place. The only place it failed was when I was trying to produce random binary matrices. Past about 95x95 matrices, it starts generating too few or too many singular matrices (I forget which). It's been shown that this generator is equivalent to a linear shift feedback register. But unless you are doing cryptography or serious monte carlo work, this generator rocks.
What is a good random number generator for a game?
[ "", "c++", "performance", "random", "" ]
I'm trying to store member function pointers by templates like this: (This is a simplified version of my real code) ``` template<class Arg1> void connect(void (T::*f)(Arg1)) { //Do some stuff } template<class Arg1> void connect(void (T::*f)()) { //Do some stuff } class GApp { public: void foo() {} void foo(double d) {} }; ``` Then I want to do like the following for every overloaded methods in GApp: ``` connect(&GApp::foo); ``` Calling this for `foo()` is ok, but how can I call this for `foo(double d)`? Why isn't the following working? ``` connect((&GApp::foo)(double)); ``` It will give me > syntax error : 'double' should be preceded by ')' I don't understand the syntax which must be used here. This may be a stupid qustion, but can any one help me on this?
Your code as written doesn't compile. I've make some "assumptions" about what you wanted to do, and have changed the code. To summarise, you can call the correct function by explicitly specifying the function parameter type: ``` connect<double> (&GApp::foo); ``` If the connect methods are members of a class template, then it is only necessary to specify the class type once: ``` template <typename T> class A { public: template<class Arg1> void connect(void (T::*f)(Arg1)) { //Do some stuff } void connect(void (T::*f)()) { //Do some stuff } }; class GApp { public: void foo() {} void foo(double d) {} }; int main () { A<GApp> a; a.connect (&GApp::foo); // foo () a.connect<double> (&GApp::foo); // foo (double) } ``` **UPDATE:** In response to the new code sample, all the information is being passed in. The "rare" case is the 'signal\_void' case as this is where the signal has a template argument, but the member function doesn't. Therefore we special case that example and then we're done. The following now compiles: ``` template <class Arg = void> class signal {}; signal<double> signal_double; signal<> signal_void; // Arg1 is deduced from signal<Arg1> and then we use it in the declaration // of the pointer to member function template<class T, class Arg1> void connect ( signal<Arg1>& sig, T& obj, void (T::*f)(Arg1) ) {} // Add special case for 'void' without any arguments template<class T> void connect (signal<> & sig, T& obj, void (T::*f)()) {} void bar () { GApp myGApp; //Connecting foo() connect(signal_void, myGApp, &GApp::foo); // Matches second overload //Connecting foo(double) connect(signal_double, myGApp, &GApp::foo); // Matches first overload } ```
The C++ Programming Language, 3E, Section 7.7, p159: > You can take the address of an overloaded function by assigning to or initializing a pointer to function. In that case, the type of the target is used to select from the set of overloaded functions. For example: ``` void f(int); int f(char); void (*pf1)(int) = &f; // void f(int); int (*pf2)(char) = &f; // int f(char); void (*pf3)(char) = &f; // error: no void f(char) ``` As far as I know (haven't checked), the same applies to member functions. So the solution is probably to split across two lines: ``` connect((&GApp::foo)(double)); ``` becomes: ``` void (GApp::*tmp)(double) = &GApp::foo; connect(tmp); ``` Never call variables `tmp` ;-) I would guess that newacct's cast is safe too, for exactly the same reason. Casting to `void (GApp::*)(double)` is defined to be the same as initializing a temporary of type `void (GApp::*)(double)`. Since the expression used to initialize it is `&GApp::foo`, I would expect the same magic to apply to the cast as applies to any other initialization with an overloaded function. Stroustrup doesn't say "initializing a pointer-to-function variable", he says "initializing a pointer-to-function". So that should include temporaries. So if you prefer a one-liner: ``` connect((void (GApp::*)(double))(&GApp::foo)); ``` However, I'm assuming that the standard has the same idea of consistency as I do, and I haven't checked.
Overloaded member function pointer to template
[ "", "c++", "templates", "pointer-to-member", "" ]
I want to write an SQL query using the `LIKE` keyword. It should search the first character or the starting character of my column with the search parameter. Is there a specific syntax for doing this?
Is this what you're looking for ``` SELECT * FROM yourtable WHERE yourcolumn LIKE 'X%' ``` This will find all rows where `yourcolumn` starts with the letter X. To find all that ends with X: ``` ... WHERE yourcolumn LIKE '%X' ``` ...and contains an X... ``` ... WHERE yourcolumn LIKE '%X%' ```
Try ``` select * from table where column like 'c%' ``` where 'c' is the character you want
How to use the LIKE keyword in SQL?
[ "", "sql", "" ]
I'm trying to write a callback event system in DirectX9. I'm attempting to use method function pointers to trigger events to mouseclicks; but I'm having some problems. My game uses a gamestate manager to manage the rendering. All of my gamestates are derived from a base class AbstractGameState. I have a sprite object with this specific method: ``` m_NewGameSprite->OnClick(this, &MainMenuState::StartGame); ``` MainMenuState is the current gamestate that my game is in, and StartGame is a void method part of this class. I'd like to store the function pointer in a variable within my sprite class so that I can execute it when the user clicks. ``` template <typename T> void OnClick(GameState* LinkedState, void (T::*EventPointer)()) { m_LinkedGameState = LinkedState; m_EventPointer = EventPointer; // <- Doesnt compile } ``` I've tried downcasting the pointer, but that didn't really work. My sprite class also contains these two variables ``` void (GameState::*m_EventPointer)(); GameState* m_LinkedGameState; ``` Any help would be appreciated
I don't really know why your assignment is not working, no doubt litb will be along shortly to explain why. [Boost.Function](http://www.boost.org/doc/libs/1_39_0/doc/html/function.html) is a beautiful, generic, typesafe and standard function object that can be used as a replacement for function pointers in almost all circumstances. I would do this: ``` typedef boost::function0<void> Event; Event m_Event; ``` Note that the event class now encapsulates the state of the function call, including the object you want to call it on. Normally you also use [Boost.Bind](http://www.boost.org/doc/libs/1_39_0/libs/bind/bind.html) to create a closure, but you can easily bind to a free function or some other function object as well. ``` void OnClick(Event &event) { m_Event=event; } ``` Call it like this: ``` OnClick(boost::bind(&MainMenuState::StartGame, this)); ``` With this scheme, you don't really need to store the "linked game state" - this is encapsulated in the event object.
The problem here is that `StartGame` can't be called with any `GameState` instance using its `this` parameter. It can only by called with a `this` parameter of type `MainMenuState`. To have a `void (GameState::*)()` point to a method defined in `MainMenuState`, the method must be a virtual method that is also defined in `GameState`. I would recommend that instead of trying to store a member function pointer, store a "command object" (or functor) pointer, using something like: ``` class Callback { public: virtual void Execute() = 0; }; ``` And then defining an implementation like this: ``` template <typename TClass> class MemberCallback : public Callback { public: MemberCallBack(TClass * pThis, void (TClass::*pFunc)() ) { m_pThis = pThis; m_pFunc = pFunc; } void Execute() { m_pThis->*m_pFunc(); } private: TClass * m_pThis; void (TClass::*m_pFunc)(); }; ``` You can then define a member of type `Callback *`.
Polymorphic member function pointer
[ "", "c++", "function-pointers", "" ]
I am running a HTTP server on my development machine. I have a website, on some web server on the Internet. How can I get Firefox to allow communication from this website to `localhost` temporarily while I develop? Thanks, Isaac Waller
The approach I use in this situation is to insert a hosts-file entry mapping localhost to a subdomain of the target internet site.
You could use a local proxy (such as [fiddler](http://www.fiddler2.com/)) to route the AJAX requests to the service on your LocalHost.
Firefox 3: Enable AJAX to localhost from outside domain
[ "", "javascript", "ajax", "firefox", "localhost", "xss", "" ]
I have one form with several text fields and one button. When i enter one of the text fields, the submit button become highlighted and if i press enter while typing, the button is pressed, so i got an unexpecte behaviour because my page is submitted. Firefox doesn't act such a way. Is there some attribute or configuration to avoid this undesired behaviour or i have to use some javascript technique?
Generally what I do in this situation is make the first button on the form do nothing and then hide it with CSS. Kludgy? Sure. Effective? Absolutely. In fact, this is a duplicate of [Stopping IE from highlighting the first submit-button in a form](https://stackoverflow.com/questions/442548/stopping-ie-from-highlighting-the-first-submit-button-in-a-form).
You need to disable the Enter key for those input elements to prevent form submission. Take a look at [this article](http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx).
How to avoid internet explorer first button selection?
[ "", "javascript", "events", "cross-browser", "" ]
What's the best way to convert an Object array to a Vector? JDE < 1.5 ``` public Vector getListElements() { Vector myVector = this.elements; return myVector; } ``` this.elements is an Object[] Thanks, rAyt **I should clarify my question** My target platform is a blackberry. Collections aren't supported. Array.asList() isn't, either :/ Full Class ``` package CustomElements; import net.rim.device.api.ui.component .*; import net.rim.device.api.collection.util.*; import net.rim.device.api.util.*; import java.util.*; public class ContactsList extends SortedReadableList implements KeywordProvider { // Constructor public ContactsList(Vector contacts) { super(new ContactsListComparatorByFirstName()); loadFrom(contacts.elements()); } // Add Element to ContactsSortedReadableList void addElement(Object element) { doAdd(element); } public Vector getListElements() { return new Vector(Collection Vector test = this.getElements(); } // getKeywords public String[] getKeywords(Object element) { return StringUtilities.stringToWords(((Contact)element).get_contactFirstName()); // return StringUtilities.stringToWords(element.toString()); } // Comparator sorting Contact objects by name final static class ContactsListComparatorByFirstName implements Comparator { public int compare(Object o1, Object o2) { // Sticky Entries Implementation if(((ContactsListObject)o2).getSticky()) { return 1; } else if (((ContactsListObject)o1).getSticky()) { return -1; } else { if(((ContactsListObject)o1).get_contactFirstName().compareTo(((ContactsListObject)o2).get_contactFirstName()) <0) { return -1; } if(((ContactsListObject)o1).get_contactFirstName().compareTo(((ContactsListObject)o2).get_contactFirstName()) >0) { return 1; } else { return 0; } } } } } ```
``` return new Vector(Arrays.asList(elements)); ``` Now, it may look as if you are copying the data twice, but you aren't. You do get one small temporary object (a `List` from `asList`), but this provides a view of the array. Instead of copying it, read and write operations go through to the original array. It is possible to extends `Vector` and poke its `protected` fields. This would give a relatively simple way of having the `Vector` become a view of the array, as `Arrays.asList` does. Alternatively, just copying data into the fields. For Java ME, this is about as good as it gets without writing the obvious loop. Untested code: ``` return new Vector(0) {{ this.elementData = (Object[])elements.clone(); this.elementCount = this.elementData.length; }}; ``` Of course, you are probably better off with a `List` than a `Vector`. 1.4 has completed its End of Service Life period. Even 1.5 has completed most of its EOSL period.
In J2ME, you're stuck iterating over the array and add the elements one by one. ``` Vector v = new Vector(); for (int i = 0; i < this.elements.length; i++) { v.add(this.elements[i]); } ```
Java Convert Object[] Array to Vector
[ "", "java", "arrays", "java-me", "vector", "" ]
I have a .net datagrid with some 20 columns. I need a column's visibilty to be toggled based on the click of a button using javascript. Any ideas?
You want to use COLGROUP to do this, otherwise you have to apply a style to *every* cell on *every* row, which will be terribly inefficient and will likely hang the browser, especially if your grid is large. All of the aforementioned answers that rely on a third-party library (jQuery) are doing it the slow/lazy way. Since all Javascript runs on the client-side, you probably want to have a little more consideration when it comes to efficiency. Here ya go... ``` function hideColumns(tableId, colIndexArray) { var tbl = document.getElementById(tableId); if(!tbl) return; var rows = tbl.getElementsByTagName("TBODY"); if(rows.length == 0) rows = tbl.getElementsByTagName("TR"); else rows = rows[0].getElementsByTagName("TR"); var cols = rows[rows.length - 1].getElementsByTagName("TD"); var colgroup = document.createElement("COLGROUP"); for(var i = 0, l = cols.length; i < l; i++) { var col = document.createElement("COL"); for(var num in colIndexArray) { if(colIndexArray[num] == i) { if(document.all) col.style.display = 'none' else col.style.visibility = 'collapse'; break; } } colgroup.appendChild(col); } tbl.insertBefore(colgroup, tbl.childNodes[0]); } ``` Use it like this... ``` var columnsToHide = [0, 1, 2]; // hide the first 3 columns var tableId = "tableIdHere"; // view the source of your page to get this hideColumns(tableId, columnsToHide); ``` Tested in IE7 and FF3: [Hide Table Columns Using Javascript](http://blog.josh420.com/examples/HideTableColumns/)
Use [jQuery](http://jquery.com/)! It's awesome. Your link can look like this: ``` <a href="javascript:ToggleColumn();">Toggle My Column</a> ``` Your javascript function can look like this: ``` function ToggleColumn() { $(".myColumn").toggle(); } ``` Each generated in the desired column will have to have the attribute class="myColumn" so your javascript can find it. To do this, you can add an `<ItemStyle />` element to the desired column of your DataGrid, like this: ``` <asp:TemplateColumn runat="server"> <ItemStyle CssClass="myColumn" /> </asp:TemplateColumn> ``` And finally, remember to include a link to jQuery in your header file somewhere, like this: ``` <script src="/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> ``` You can [download jQuery here](http://docs.jquery.com/Downloading_jQuery).
Hide a datagrid column with Javascript?
[ "", ".net", "javascript", "html", "dom", "" ]
**Question: How can I determine all processes in the child's *Process Tree* to kill them?** I have an application, written in C# that will: 1. Get a set of data from the server, 2. Spawn a 3rd party utility to process the data, then 3. Return the results to the server. This is working fine. But since a run consumes *a lot* of CPU and *may* take as long as an hour, I want to add the ability to have my app terminate its child processes. Some issues that make the simple solutions I've found elsewhere are: * My app's child process "A" (InstallAnywhere EXE I think) spawns the real processing app "B" (a *java.exe*), which in turns spawns more children "C1".."Cn" (*most* of which are also written in Java). * There will likely be *multiple copies* of my application (and hence, multiple sets of its children) running on the same machine. * The child process is not in my control so there might be some "D" processes in the future. * My application must run on 32-bit *and* 64-bit versions of MSWindows. On the plus side there is no issue of data loss, a "clean" shutdown doesn't matter as long as the processes end fairly quickly.
I guess you can kill your grandchildren with this code from [the MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d60f0793-cc92-48fb-b867-dd113dabcd5c). ``` public bool killProcess(int pid) { bool didIkillAnybody = false; try { Process[] procs = Process.GetProcesses(); for (int i = 0; i < procs.Length; i++) { didIkillAnybody = GetParentProcess(procsIdea.Id) == pid) && killProcess(procsIdea.Id); } try { Process myProc = Process.GetProcessById(pid); myProc.Kill(); return true; } catch { } } catch (Exception ex) { try { new Logger().Write("Exception caught at JobExecution.killProcess()", ex.Message, System.Diagnostics.EventLogEntryType.Warning, false); } catch { } } return didIkillAnybody; } private int GetParentProcess(int Id) { int parentPid = 0; using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'")) { mo.Get(); parentPid = Convert.ToInt32(mo["ParentProcessId"]); } return parentPid; } ```
The following code works for me: ``` private void KillProcessAndChildren(int pid) { using (var searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid)) using (ManagementObjectCollection moc = searcher.Get()) { foreach (ManagementObject mo in moc) { KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"])); } try { Process proc = Process.GetProcessById(pid); proc.Kill(); } catch (ArgumentException) { /* process already exited */ } } } ``` It works for the scenario I have. I'd be interested to hear if that works for others as well.
How to terminate all [grand]child processes using C# on WXP (and newer MSWindows)
[ "", "c#", "process", "parent-child", "kill", "" ]
To my surprise in the following program the Eclipse console doesn't print while in the loop. It prints only: "start: finish". When I use println instead it does. Of when I remove the comment it does too. Surprise: when I copy the lines "start: finish" in the console, the clipboard does contain all printed numbers. Interesting to know waht is the cause of this behaviour? ``` public static void main(String[] args) { System.out.print("start: "); for (int i = 0; i < 10000; i++) { // if (i > 1000 && i < 1010) System.out.print(i + " "); } System.out.println("finish"); } ```
Well, you have a very, very long line there. So, it is quite possible that you have exceeded the maximum line length that the Eclipse console can reliably display. The content probably has been printed there (as evidenced by the fact that it appeared in your clipboard when you copy and paste) but doesn't render well.
Println in Java or print("\n") In C & C++ flush the buffer and force it to print every thing in buffer but when use print whitout any \n (new line) it's not necessarily print buffer
Debug with System.out.print in a loop (Eclipse)
[ "", "java", "" ]
My understanding of C# says (thanks to Jeff Richter & Jon Skeet) that assignment is "atomic". What is not is when we mix reads & writes (increment/decrement) and hence we need to use methods on the Interlocked. If have only Read & assign would both the operations be atomic? ``` public class Xyz { private volatile int _lastValue; private IList<int> AvailableValues { get; set; } private object syncRoot = new object(); private Random random = new Random(); //Accessible by multiple threads public int GetNextValue() //and return last value once store is exhausted { //... var count = 0; var returnValue = 0; lock (syncRoot) { count = AvailableValues.Count; } if (count == 0) { //Read... without locking... potential multiple reads returnValue = _lastValue; } else { var toReturn = random.Next(0, count); lock (syncRoot) { returnValue = AvailableValues[toReturn]; AvailableValues.RemoveAt(toReturn); } //potential multiple writes... last writer wins _lastValue = returnValue; } return returnValue; } ```
`volatile` is actually more related to caching (in registers etc); with `volatile` you know that that value is actually written-to/read-from memory *immediately* (which isn't actually always the case otherwise). This allows different threads to immediately see updates from each other. There are other subtle issues with instruction re-ordering, but that gets complex. There are two meanings of "atomic" to consider here: * is a single read atomic by itself / write atomic by itself (i.e. could another thread get two different halves of two `Double`s, yielding a number that never actually existed) * is a read/write pair atomic/isolated *together* The "by itself" depends on the size of the value; can it be updated in a single operation? The read/write pair is more to do with isolation - i.e. preventing lost updates. In your example, it is possible for two threads to read the same `_lastValue`, both do the calculations, and then (separately) update `_lastValue`. One of those updates is going to get lost. In reality, I expect you want a `lock` over the **duration** of the read/write process.
> My understanding of C# says (thanks to > Jeff Richter & Jon Skeet) that > assignment is "atomic". **Assignment is not atomic in general.** The C# specification carefully calls out what is guaranteed to be atomic. See section 5.5: *Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are **not guaranteed to be atomic**.* (Emphasis added.) > If have only Read & assign would both > the operations be atomic? Again, section 5.5 answers your question: *there is no guarantee of atomic read-modify-write*
Assignment to volatile variable in C#
[ "", "c#", "volatile", "" ]
> **Possible Duplicate:** > [Maximum length of the textual representation of an IPv6 address?](https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address) What would you recommend as the maximum size for a database column storing client ip addresses? I have it set to 16 right now, but could I get an ip address that is longer than that with IPv6, etc?
For IPv4, you *could* get away with storing the 4 raw bytes of the IP address (each of the numbers between the periods in an IP address are 0-255, i.e., one byte). But then you would have to translate going in and out of the DB and that's messy. IPv6 addresses are 128 bits (as opposed to 32 bits of IPv4 addresses). They are usually written as 8 groups of 4 hex digits separated by colons: `2001:0db8:85a3:0000:0000:8a2e:0370:7334`. 39 characters is appropriate to store IPv6 addresses in this format. Edit: However, there is a caveat, see @Deepak's answer for details about IPv4-mapped IPv6 addresses. (The correct maximum IPv6 string length is **45 characters**.)
**There's a caveat with the general 39 character IPv6 structure.** For IPv4 mapped IPv6 addresses, the string can be longer (than 39 characters). An example to show this: IPv6 (39 characters) : ``` ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:ABCD ``` IPv4-mapped IPv6 (45 characters) : ``` ABCD:ABCD:ABCD:ABCD:ABCD:ABCD:192.168.158.190 ``` Note: the last 32-bits (that correspond to IPv4 address) can need up to 15 characters (as IPv4 uses 4 groups of 1 byte and is formatted as 4 decimal numbers in the range 0-255 separated by dots (the `.` character), so the maximum is `DDD.DDD.DDD.DDD`). **The correct maximum IPv6 string length, therefore, is 45.** This was actually a quiz question in an IPv6 training I attended. (We all answered 39!)
Max length for client ip address
[ "", "sql", "database", "database-design", "" ]
I've been playing a big with the DC obtained with `CreateDC(L"DISPLAY",NULL,NULL,NULL)` and I've been wondering why does windows let you draw on the whole screen that easily, cause I think you could do some pretty evil stuff with that like putting a TIMER at 1ms and drawing a black rectangle on the whole screen every time the timer ticks.
The fact that you could do some pretty evil stuff doesn't mean windows shouldn't let you do it. Just think of all the other evil things you could do: * Run in an infinite loop and eat up all the cpu time. * Write random bits to a file until you fill up the whole hard disk. * Delete random files all over the place. * Allocate memory like crazy until the computer slows to a crawl. Just because you CAN do those things doesn't mean windows should prevent you from writing to the hard drive or allocating memory or deleting files. The purpose of Windows is to provide an environment in which programs can run. The more flexible they make that environment, the more interesting (and, unfortunately, devious) programs it makes possible for developers to create. If they started putting in arbitrary restrictions on what you can do because you might abuse it... well, then it wouldn't be windows, it would be an iPhone :)
why does windows let you write to the hard drive so easily? you could do some pretty evil stuff like overwrite every file on the hard drive.
Why does windows let you draw on the whole screen?
[ "", "c++", "windows", "winapi", "gdi", "" ]
I'm learning python for a couple of days now and am struggling with its 'spirit'. I'm comming from the C/C++/Java/Perl school and I understand that python is not C (at all) that's why I'm trying to understand the spirit to get the most out of it (and so far it's hard)... My question is especially focused on exception handling and cleaning: The code at the end of this post is meant to simulate a fairly common case of file opening/parsing where you need to close the file in case of an error... Most samples I have seen use the 'else' clause of a try statement to close the file... which made sense to me until I realized that the error might be due to * the opening itself (in which case there is no need to close the not opened file) * the parsing (in which case the file needs to be closed) The trap here is that if you use the 'else' clause of a try bloc then the file never gets closed if the error happens during parsing! On the other end using the 'finally' clause result in an extra necessary check because the file\_desc variable may not exist if the error happened during the opened (see comments in the code below)... This extra check is inefficient and full of shit because any reasonable program may contain hundreds of symbols and parsing the results of dir() is a pain in the ass... Not to mention the lack of readability of such a statement... Most other languages allow for variable definitions which could save the day here... but in python, everything seems to be implicit... Normally, one would just declare a file\_desc variable, then use many try/catch blocs for every task... one for opening, one for parsing and the last one for the closing()... no need to nest them... here I don't know a way to declare the variable... so I'm stuck right at the begining of the problem ! so what is the spirit of python here ??? * split the opening/parsing in two different methods ? How ? * use some kind of nested try/except clauses ??? How ? * maybe there is a way to declare the file\_desc variable and then there would be no need for the extra checking... is it at all possible ??? desirable ??? * what about the close() statement ??? what if it raises an error ? thanx for your hints... here is the sample code: ``` class FormatError(Exception): def __init__(self, message): self.strerror = message def __str__(self): return repr(message) file_name = raw_input("Input a filename please: ") try: file_desc = open(file_name, 'r') # read the file... while True: current_line = file_desc.readline() if not current_line: break print current_line.rstrip("\n") # lets simulate some parsing error... raise FormatError("oops... the file format is wrong...") except FormatError as format_error: print "The file {0} is invalid: {1}".format(file_name, format_error.strerror) except IOError as io_error: print "The file {0} could not be read: {1}".format(file_name, io_error.strerror) else: file_desc.close() # finally: # if 'file_desc' in dir() and not file_desc.closed: # file_desc.close() if 'file_desc' in dir(): print "The file exists and closed={0}".format(file_desc.closed) else: print "The file has never been defined..." ```
The easiest way to deal with this is to use the fact that file objects in Python 2.5+ are [context managers](http://www.python.org/doc/2.5.2/lib/typecontextmanager.html). You can use the [`with`](http://www.python.org/dev/peps/pep-0343/) statement to enter a context; the context manager's `__exit__` method is automatically called when exiting this `with` scope. The file object's context management automatically closes the file then. ``` try: with file("hello.txt") as input_file: for line in input_file: if "hello" not in line: raise ValueError("Every line must contain 'hello'!") except IOError: print "Damnit, couldn't open the file." except: raise else: print "Everything went fine!" ``` The open hello.txt handle will automatically be closed, and exceptions from within the with scope are propagated outside.
Just a note: you can always declare a variable, and then it would become something like this: ``` file_desc = None try: file_desc = open(file_name, 'r') except IOError, err: pass finally: if file_desc: close(file_desc) ``` Of course, if you are using a newer version of Python, the construct using context manager is way better; however, I wanted to point out how you can generically deal with exceptions and variable scope in Python.
cleaning up when using exceptions and files in python
[ "", "python", "exception", "file-io", "" ]
I am creating a `java.util.logging.FileHandler` that is allowed to cycle through files. When multiple instances of my application are run, a new log file is created for each instance of the application. I need to know what file is being used by the application because I want to upload the log file to my servers for further review. How can I tell what file is being used by a certain FileHandler?
The easiest way is to put some kind of identifier in the file name itself, i.e. the `pattern` argument when you create the FileHandler. Since these are instances of the same application, one way to distinguish them is by their process id, so you could make that part of the pattern. A better approach is to pass in an identifier through the command line and use that to make your filename. That way you control the files being created in some sense. Finally, if your application has some knowledge of why it's different from all the others, for example it connects to a particular database server, then you could just use that database server name as part of the filename. EDIT: There does not seem to be any API to get the name of the file being used by a FileHandler. I would suggest looking into the logging extensions in x4juli (which ports a lot of the log4j functionality to the java.util.logging specs): * <http://www.x4juli.org/> You should be able to substitute an instance of their FileHandler which provides a getFile() method: * <http://www.x4juli.org/api/org/x4juli/handlers/FileHandler.html>
Actually, you could do this much simpler by simply extending FileHandler yourself. For example... MyFileHandler.java: ``` import java.io.IOException; import java.util.logging.FileHandler; public class MyFileHandler extends FileHandler { protected String _MyFileHandler_Patern; public MyFileHandler(String pattern) throws IOException { _MyFileHandler_Patern = pattern; } public String getMyFileHandlerPattern() { return _MyFileHandler_Patern; } } ``` DeleteMe.java: ``` import java.io.IOException; import java.util.logging.Handler; import java.util.logging.Logger; public class DeleteMe { public static void main(String[] args) throws IOException { Logger log = Logger.getLogger(DeleteMe.class.getName()); MyFileHandler output = new MyFileHandler("output.log"); log.addHandler(output); for (Handler handler : log.getHandlers()) { if (handler instanceof MyFileHandler) { MyFileHandler x = (MyFileHandler) handler; if ("output.log".equals(x.getMyFileHandlerPattern())) { System.out.println("found hanlder writing to output.log"); } } } } } ```
Determine file being used by FileHandler
[ "", "java", "logging", "" ]
I'm using [Sphinx](https://www.sphinx-doc.org) and the [autodoc extension](https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html) to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a `**kwargs` parameter. Does anyone have a good example of a clear way to document these?
I think [`subprocess`-module's docs](http://docs.python.org/library/subprocess.html) is a good example. Give an exhaustive list of all parameters for a [top/parent class](http://docs.python.org/2/library/subprocess.html#subprocess.Popen). Then just refer to that list for all other occurrences of `**kwargs`.
After finding this question I settled on the following, which is valid Sphinx and works fairly well: ``` def some_function(first, second="two", **kwargs): r"""Fetches and returns this thing :param first: The first parameter :type first: ``int`` :param second: The second parameter :type second: ``str`` :param \**kwargs: See below :Keyword Arguments: * *extra* (``list``) -- Extra stuff * *supplement* (``dict``) -- Additional content """ ``` The `r"""..."""` is required to make this a "raw" docstring and thus keep the `\*` intact (for Sphinx to pick up as a literal `*` and not the start of "emphasis"). The chosen formatting (bulleted list with parenthesized type and m-dash-separated description) is simply to match the automated formatting provided by Sphinx. Once you've gone to this effort of making the "Keyword Arguments" section look like the default "Parameters" section, it seems like it might be easier to roll your own parameters section from the outset (as per some of the other answers), but as a proof of concept this is one way to achieve a nice look for supplementary `**kwargs` if you're already using Sphinx.
What is the correct way to document a **kwargs parameter?
[ "", "python", "python-sphinx", "autodoc", "" ]
I have a class that retrieves its memeber (more or less 10 members) from a database. My question is: is it more efficient to fetch them every time from the db (MySQL), leaving just an ID in the session's array or store them directly in the session's array? And is the difference in performance terms so great? (given a database with say 100.000 rows)
Considering you're storing an ID in the session anyway, the session makes the most sense. Doing a session\_start() loads your session information so whether you've loaded 1 or 10 items after that is largely irrelevant (unless they're really large but that'll be a problem in any case). So stick with the session. If you get really concerned about speed use an in-memory cache like APC or memcache. Worrying about speed for 10 items from the filesystem or database is a distraction. The difference is going to be so minimal as to be irrelevant. Note: the above assumes two things: 1. The query is performant (retrieving 10 rows out of 100k should be doable in under 0.1 seconds); and 2. You are doing one query not 10.
Depends what you mean by 'efficient'. One's time-efficient, one's disk-space-efficient. And it's very difficult to judge the two against each other, unless your requirements are at either extreme end of the spectrum. You'd probably do OK just flipping a coin, measuring performance over time, and adjusting based on any observed problems. > Premature optimisation is the root of > all evil.
php: sessions vs. database
[ "", "php", "mysql", "performance", "session", "" ]
I have a table in my database: ``` Name | Element 1 2 1 3 4 2 4 3 4 5 ``` I need to make a query that for a number of arguments will select the value of Name that has on the right side these and only these values. E.g.: arguments are 2 and 3, the query should return only 1 and not 4 (because 4 also has 5). For arguments 2,3,5 it should return 4. My query looks like this: ``` SELECT name FROM aggregations WHERE (element=2 and name in (select name from aggregations where element=3)) ``` What do i have to add to this query to make it not return 4?
A simple way to do it: ``` SELECT name FROM aggregations WHERE element IN (2,3) GROUP BY name HAVING COUNT(element) = 2 ``` If you want to add more, you'll need to change both the `IN (2,3)` part and the `HAVING` part: ``` SELECT name FROM aggregations WHERE element IN (2,3,5) GROUP BY name HAVING COUNT(element) = 3 ``` A more robust way would be to check for everything that isn't not in your set: ``` SELECT name FROM aggregations WHERE NOT EXISTS ( SELECT DISTINCT a.element FROM aggregations a WHERE a.element NOT IN (2,3,5) AND a.name = aggregations.name ) GROUP BY name HAVING COUNT(element) = 3 ``` It's not very efficient, though.
Create a temporary table, fill it with your values and query like this: ``` SELECT name FROM ( SELECT DISTINCT name FROM aggregations ) n WHERE NOT EXISTS ( SELECT 1 FROM ( SELECT element FROM aggregations aii WHERE aii.name = n.name ) ai FULL OUTER JOIN temptable tt ON tt.element = ai.element WHERE ai.element IS NULL OR tt.element IS NULL ) ``` This is more efficient than using `COUNT(*)`, since it will stop checking a `name` as soon as it finds the first row that doesn't have a match (either in `aggregations` or in `temptable`)
Select values in SQL that do not have other corresponding values except those that i search for
[ "", "sql", "" ]
``` SELECT app_contracts.*, app_customers.id as customer, app_boards.id as board WHERE app_customers.id=app_contracts.customer_id AND app_boards.id=app_contracts.board_id ORDER BY app_contracts.id DESC ``` Error: > Error Number: 1064 > > You have an error in your SQL syntax; > check the manual that corresponds to > your MySQL server version for the > right syntax to use near 'WHERE > app\_customers.id=app\_contracts.customer\_id > AND app\_boards.id=app\_contracts' at > line 2
you need to select FROM something (a table, say) before your WHERE-clause
You're missing the "FROM" clause before the "WHERE". SELECT app\_contracts.\*, app\_customers.id as customer, app\_boards.id as board **FROM app\_customers, app\_contracts** WHERE app\_customers.id=app\_contracts.customer\_id AND app\_boards.id=app\_contracts.board\_id ORDER BY app\_contracts.id DESC
What's wrong with this mysql query?
[ "", "php", "mysql", "" ]
I have a project in Eclipse. When I run it from inside Eclipse, everything works just fine. However, when I run the Ant build script and execute the JAR either from the command line or using a batch script, I get a NullPointerException. The NullPointerException in question is being thrown from a third-party JAR that I compiled from source. But, I doubt that's the problem - it works when I execute it inside Eclipse! What could be causing this and how can I go about isolating the problem and correcting it? Here is as much of the stack trace as I can show: ``` java.lang.NullPointerException at java.io.FilterInputStream.read(Unknown Source) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at java.io.DataInputStream.readUnsignedByte(Unknown Source) at com.jhlabs.dbf.DBFFile.readHeader(DBFFile.java:129) at com.jhlabs.dbf.DBFFile.<init>(DBFFile.java:76) at com.jhlabs.map.shapefile.Shapefile.<init>(Shapefile.java:102) at com.jhlabs.map.layer.ShapefileLayer.<init>(ShapefileLayer.java:62) ``` I checked the classpath - the third party JAR is indeed on the classpath. However, I expected that, as I would most likely get a NoClassDefFoundException if it was not and I tried to utilize the classes in the JAR. I also checked the locations where I used a classloader, and they were not null and were correctly loading the proper files.
One guess: it's trying to find a resource using `ClassLoader.getResourceAsStream()` or similar, and it's not finding it in the jar. Of course we'd be guessing rather less if you'd tell us the rest of the stack trace instead of just that it's an NPE... and the fact that you've got the source means you should be able to work out *exactly* where it's going wrong! EDIT: Yes, with that stack trace it's probably creating a `FilterInputStream` but passing in a `null` stream to wrap. (The JDK should really throw an exception in the constructor, but it's too late to fix that now.)
Looks more like the DBF file path is not resolving correctly in the latter case. The file path from where you run your class file in Eclipse is mostly different from where you are running the batch file from. (Not the class-path, but the physical path from where you are doing java -jar ..., like say, D:\my\app\bin) The path Eclipse runs from is in Run Configurations -> Arguments tab -> Working directory field.
What would cause a NullPointerException when running a JAR from the command line, but not from an IDE?
[ "", "java", "jar", "nullpointerexception", "" ]
I saw the [other topic](//stackoverflow.com/q/334630) and I'm having another problem. The process is starting (saw at task manager) but the folder is not opening on my screen. What's wrong? ``` System.Diagnostics.Process.Start("explorer.exe", @"c:\teste"); ```
Have you made sure that the folder "`c:\teste`" exists? If it doesn't, explorer will open showing some default folder (in my case "`C:\Users\[user name]\Documents`"). **Update** I have tried the following variations: ``` // opens the folder in explorer Process.Start(@"c:\temp"); // opens the folder in explorer Process.Start("explorer.exe", @"c:\temp"); // throws exception Process.Start(@"c:\does_not_exist"); // opens explorer, showing some other folder) Process.Start("explorer.exe", @"c:\does_not_exist"); ``` If none of these (well, except the one that throws an exception) work on your computer, I don't think that the problem lies in the code, but in the environment. If that is the case, I would try one (or both) of the following: * Open the Run dialog, enter "explorer.exe" and hit enter * Open a command prompt, type "explorer.exe" and hit enter
Just for completeness, if all you want to do is to open a folder, use this: ``` System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = "C:\\teste\\", UseShellExecute = true, Verb = "open" }); ``` Ensure FileName ends with `Path.DirectorySeparatorChar` to make it unambiguously point to a folder. (Thanks to @binki.) This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.
Open a folder using Process.Start
[ "", "c#", "explorer", "" ]
How can I get fontSize of element in `px` or `pt`? Or can I use any other methods? I need to make the size of `<a href="...">MAKE ME BIGGER</a>` bigger on 130%, 140%, N% from current size.
to make the size of text element bigger, insert all content of element in the child span and set to this span style="font-size: N%": ``` function makeBigger(lnk){ var Span = document.createElement('span') for(var i = lnk.childNodes.length - 1; i >=0; i--){ Span.insertBefore(lnk.childNodes[i], Span.firstChild) } Span.style.fontSize = '120%' lnk.appendChild(Span) } ``` of course, it doesn't work in the constructions like this: ``` <a ... >MAKE ME BIGGER <label class="some_class_with_fixed_font_size">but not me</label></a> ```
If you use the `em` unit instead this is relative to the current size, see; <http://www.w3schools.com/css/css_units.asp> *1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a font of 12 pt, then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt automatically to the font that the reader uses* **[EDIT]** Your label is part of the anchor, does it have to be? What about if you construct the page with; ``` <label class="fixed-font"> <a class="scaled-font">BIGGER TEXT</a> Normal Sized Text </label> ``` Then created the styles with scaled-font a child selector of fixed-font e.g. ``` label.fixed-font { font-size:12px } label.fixed-font a.scaled-font { font-size:1.6em; } ```
How can I get current fontSize of link-element?
[ "", "javascript", "" ]
I want to know how `malloc` and `free` work. ``` int main() { unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char)); memset(p,0,4); strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes** cout << p; free(p); // Obvious Crash, but I need how it works and why crash. cout << p; return 0; } ``` I would be really grateful if the answer is in depth at memory level, if it's possible.
OK some answers about malloc were already posted. The more interesting part is **how free works** (and in this direction, malloc too can be understood better). In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB). So returning 40 Bytes to the OS will just not work. So what does free do? Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens. The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list. There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations. **Why does your code crash:** The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system. This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why! Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.
As aluser says in [this forum thread](http://www.linuxquestions.org/questions/programming-9/how-does-malloc-and-free-functions-work-262165/): > Your process has a region of memory, from address x to address y, > called the heap. All your malloc'd data lives in this area. malloc() > keeps some data structure, let's say a list, of all the free chunks of > space in the heap. When you call malloc, it looks through the list for > a chunk that's big enough for you, returns a pointer to it, and > records the fact that it's not free any more as well as how big it is. > When you call free() with the same pointer, free() looks up how big > that chunk is and adds it back into the list of free chunks(). If you > call malloc() and it can't find any large enough chunk in the heap, it > uses the brk() syscall to grow the heap, i.e. increase address y and > cause all the addresses between the old y and the new y to be valid > memory. brk() must be a syscall; there is no way to do the same thing > entirely from userspace. malloc() is system/compiler dependent so it's hard to give a specific answer. Basically however it does keep track of what memory it's allocated and depending on how it does so your calls to free could fail or succeed. ***`malloc() and free() don't work the same way on every O/S.`***
How do malloc() and free() work?
[ "", "c++", "c", "memory-management", "malloc", "free", "" ]
**Update**: My bad. The error I am getting is ECONNREFUSED and not EINPROGRESS. After checking the `error` variable I've found that it is greater than 0, I printfed `errno` instead of `error`. Of course `errno` is `EINPROGRESS` because it value didn't change since the call to `connect()`. Question answered. Thanks folks. > I am using the the the same piece of code as in Stevens' UNIX Network Programming non >blocking connect() example: > > 1. Setting socket to nonblocking > 2. Initiate nonblocking connect() > 3. Check for immediate completion > 4. Call select() with timeout and wait for read or write readiness > 5. When select() returns with value greater than 0 do getsockopt(socket, SOL\_SOCKET, SO\_ERROR, &error, &len). > > The error I am getting is EINPROGRESS. > The code is executed on rhel5 server. > > Any ideas why I am getting this error? **Code snippet**: ``` flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); if ((retVal = connect(sockfd, saptr, salen)) < 0) if (errno != EINPROGRESS) return (-1); if (retVal == 0) { // restore file status flags fcntl(sockfd, F_SETFL, flags); return 0; } FD_ZERO(&rset); FD_SET(sockfd, &rset); wset = rset; tval.tv_sec = nsec; tval.tv_usec = 0; if ((retVal = select(sockfd + 1, &rset, &wset, NULL, &tval)) == 0) { // timeout close(sockfd); errno = ETIMEDOUT; return (-1); } if (retVal < 0) { // select() failed return (-1); } if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) { len = sizeof(error); error = 0; if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) return (-1); if (error > 0) //<<<<< error == EINPROGRESS >>> { close(sockfd); errno = error; return (-1); } } else { return (-1); } // restore file status flags fcntl(sockfd, F_SETFL, flags); ```
Shucks....I give up. I tried and tried but could not find a problem with your code. So, all I offer are some suggestions and hypothesis. * Use FD\_COPY to copy rset to wset. * Can you do a getsockopt when the first connect fails. I am suspecting that Select is returning 0 and because of above, somehow your writefd set is set and doing a getsockopt is returning you the stale error from the previous connect. IMO, a subsquent connect should return EALREADY (although it could be platform dependant) Please do the above (and downvote me if I am wrong about using FD\_COPY) and share the results
EINPROGRESS indicates that the non-blocking connect() is still... in progress. So I would ask - are you checking that after the select() returns, the connect()ing file descriptor is still set in the writefds fd\_set? If it isn't, then that means select() has returned for some other reason.
getsockopt() returns EINPROGRESS in non blocking connect()+select() flow
[ "", "c++", "c", "sockets", "unix", "" ]
How can I validate a string using Regular Expressions to only allow alphanumeric characters in it? (I don't want to allow for any spaces either).
Use the following expression: ``` ^[a-zA-Z0-9]*$ ``` ie: ``` using System.Text.RegularExpressions; Regex r = new Regex("^[a-zA-Z0-9]*$"); if (r.IsMatch(SomeString)) { ... } ```
In .NET 4.0 you can use LINQ: ``` if (yourText.All(char.IsLetterOrDigit)) { //just letters and digits. } ``` `yourText.All` will stop execute and return `false` the first time `char.IsLetterOrDigit` reports `false` since the contract of `All` cannot be fulfilled then. **Note!** this answer do not strictly check alphanumerics (which typically is A-Z, a-z and 0-9). This answer allows local characters like `åäö`. **Update 2018-01-29** The syntax above only works when you use a single method that has a single argument of the correct type (in this case `char`). To use multiple conditions, you need to write like this: ``` if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x))) { } ```
How can I validate a string to only allow alphanumeric characters in it?
[ "", "c#", "regex", "" ]
I want to pull down information from two tables from a db. One row from A, and the rows in B with an FK to the row I pulled from A. I'd like to make this a single stored proc with two select statements, rather than having to make two calls to the DB. I know several ways to pull the information from a single select...but can't remember how to get data from multiple selects. Googling has proven to be difficult, since I'm having trouble coming up with nouns/verbs to describe the situation that don't describe a million other things. Can someone point me in the right direction? (To keep things simple, I know to use "using" statements and such...I just need the basic idea of the approach). ``` using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand com = new SqlCommand(commandString, conn)) { <somehow get multiple select's of data here in one call> } } ```
If you're used to using the SqlDataReader then you just need to have your stored procedure or sql statement perform multiple selects and call `NextResult()` to move to the next result set: ``` using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(commandString, conn); // Add parameters here using (SqlDataReader reader = cmd.ExecuteReader()) { // This will read the first result set while(reader.Read()) { // Read data } // This will read the second result set if (!reader.NextResult()) { throw new ApplicationException("Only one result set returned"); } while (reader.Read()) { // Read data } } } ``` If you're used to using the data adapter returning data tables then all you need to do is have your data adapter fill a dataset and extract the result sets from the Tables property: ``` using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlDataAdapter da = new SqlDataAdapter(commandString, conn); DataSet ds = new DataSet(); da.Fill(ds); DataTable firstResult = ds.Tables[0]; DataTable secondResult = ds.Tables[1]; } ```
``` var reader = com.ExecuteReader(); while(reader.Read()) { //do operations for the first select here } reader.NextResult(); while(reader.Read()) { //do operations for the second select here } ``` Note: there may be syntax error, not checked. But the point is, use SqlDataReader.NextResult().
Two SELECTS, One query
[ "", ".net", "sql", "" ]
Working with stl:list and stl::vector types under interrupt handlers I want to avoid malloc() calls. The question: What is a best way to prevent malloc() calls in STL list and vector? Is it enough to create structure with predefined size and then avoid push/pop/erase calls? Thank you in advance
As a testimonial: we use two methods mentioned in other answers at my workplace: * **custom allocators**: for our memory leak tracking system, our instrumenting profiler, and a few other systems, we preallocate and/or "pool" (see e.g. boost::pool) allocs using a provided Allocator -- usually for std::set or std::map, but the principle is the same for std::list. * **reserve/resize**: for std::vectors, it's very common practice for us to reserve or resize (the difference is important, but both can help avoid future allocs) ahead of time. Mostly we do these two things to avoid fragmentation, decrease allocator overhead, eliminate the copy-on-grow penalty, etc. But sometimes (especially with e.g. the instrumenting profiler) we want to absolutely avoid allocation during an interrupt handler. Usually, however, we avoid issues with interrupts and allocations in other manners: * **get in/get out**: try to avoid doing anything other than setting flags or trivial copies during interrupts; some times a static (or preallocated) buffer is a far better solution than a STL container. Holding interrupts for too long is usually a recipe for disaster. * **disable interrupts during alloc/free**: interrupts are queued up while we're allocating/freeing, instead of being dispatched immediately -- it's a feature of the CPU we're working with. Combined with a policy of selectively increasing the scope of that disabling/queuing (around e.g. std::list manipulation), we can sometimes get away with a interrupt-handler-as-producer, everything-else-as-consumer model, without overriding the allocator. If we're in the middle of consuming something from a std::list (e.g. a message received from the network hardware), interrupts are queued for as short a period as possible while pop off a copy of what we're about to process. Note that lock-free data structures could be an alternative to the second bullet here, we haven't set up and done profiling to see if it would help. Designing your own is tricky business anyway. Paranoia is the better part of valor for interrupt handlers: if you're not certain what you're doing will work, it's sometimes much better to approach the issue in an entirely different manner.
STL containers like `std::list` and `std::vector` have constructors accepting an `Allocator` type. By supplying your own allocator instead of using the default you are able to control how the container allocates memory. This option is rarely used, but using your own allocator in a real time environment is a good example of where this feature is useful (and proves that the designers of STL did a very good job). The requirements for you custom allocator type is described in 20.1.6 in the [C++ standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf)
std::list, std::vector methods and malloc()
[ "", "c++", "stl", "" ]
I am using aspx and c# for a setting a authentication cookie for a login. ``` FormsAuthentication.SetAuthCookie(UserName, True) ``` I want to store more information in the same cookie. Can I add values to this authentication cookie or do I have to use a second http cookie? Basically I'm looking for away to store the User's `Id` so I may be able to access the database using the users table row key Thanks, Eden
You can add user data to the FormsAuthenticationTicket, then generate the cookie yourself. There's an example in the [the MSDN documentation for FormsAuthenticationTicket](http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx). **EDIT** Note that when creating the ticket, you need to set the timeout, which in general you will want to be the same as the value configured in web.config. Unfortunately, in the Framework 3.5 or earlier, the `FormsAuthentication` class does not expose this timeout publicly. For a workaround, use one of the techniques described in the response to [this connect feedback item](http://connect.microsoft.com/VisualStudio/feedback/details/102290/expose-forms-authentication-timeout-as-a-public-static-property). **UPDATE** > That Connect feedback item is no longer there, sadly. Wish you had briefly described what the techniques were. Yes, it's a pity Microsoft has discarded historical Connect items. IIRC, the two techniques they suggested were: 1. Use WebConfigurationManager to read the relevant configuration section and get the timeout value. 2. Create a cookie using `FormsAuthentication.GetAuthCookie`, decrypt it using `FormsAuthentication.Decrypt` and inspect the generated `FormsAuthenticationTicket`. Or upgrade to .NET 4.x where there is a `FormsAuthentication.Timeout` property. See [this question](https://stackoverflow.com/questions/9600122/formsauthentication-timeout-totalminutes-in-net-3-5/9600552#9600552) for more info
You can put whatever you want in the auth cookie as long as it's useful to you. That said, if you're putting sensitive information you should, at the very least, encrypt it, but I'd recommend against putting sensitive information there. You can do something like: ``` Forms.SetAuthCookie (UserName + "|" + UserId, true); ``` Then, whenever you need the username or the user id, it is there. Just load the cookie and parse out the values you need. Again, **I'd advise against doing this, especially as I have it presented above**. That said, it is possible. You should create accessor methods to pull the data back out: ``` public int CurrentUserId { get { int userId = 0; if (HttpContext.Current.Request.IsAuthenticated) { userId = Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('|')[1]); } return userId; } } public string CurrentUserName { get { string userName = string.Empty; if (HttpContext.Current.Request.IsAuthenticated) { userName = HttpContext.Current.User.Identity.Name.Split('|')[0]; } return userName; } } ```
Storing more information using FormsAuthentication.SetAuthCookie
[ "", "c#", "asp.net", "asp.net-mvc", "forms-authentication", "" ]
I'll start by saying that I am very, very new to Python. I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time. Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding something in python. I've come up with that : ``` #!/usr/bin/python import sys, os #Path to mencoder mencoder = "C:\Program Files\MPlayer-1.0rc2\mencoder.exe" infile = "holidays.avi" outfile = "holidays (part1).avi" startTime = "00:48:00" length = "00:00:15" commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s" os.system(commande % (mencoder, infile, startTime, length, outfile)) #Pause raw_input() ``` But that doesn't work, windows complains that "C:\Program" is not recognized command. I've trying putting some "\"" here and there, but that didn't help.
Python have two types of quotes, " and ' and they are completely equal. So easiest way to get quotes in a string is to say '"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"'. Using the raw prefix (ie r'"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"') is a good idea, but that is not the error here, as none of the backslashes are followed by a letter that is an escape code. So your original string would not change at all by having an r in front of it.
use two quotes instead of one if you are doing on windows. ``` "\\" ```
Using Python to call Mencoder with some arguments
[ "", "python", "windows", "mencoder", "" ]
I'm wondering if it's possible if you have, for example, a `vector<string>` and a `vector<double>` with corresponding pairs, to sort the `vector<string>` alphabetically while keeping the pairs matched up. I know this can be done by creating a class that holds both values and just sorting that, but I'd rather keep two separate vectors. Any ideas? Final Code: ``` #include "std_lib_facilities.h" struct Name_pairs { vector<string>names; vector<double>ages; void quicksort(vector<string>& num, vector<double>& num2, int top, int bottom); int divide(vector<string>& array, vector<double>& array2, int top, int bottom); bool test(); string read_names(); double read_ages(); void print(); }; string Name_pairs::read_names() { string name; cout << "Enter name: "; cin >> name; names.push_back(name); return name; } double Name_pairs::read_ages() { double age; cout << "Enter corresponding age: "; cin >> age; ages.push_back(age); cout << endl; return age; } int Name_pairs::divide(vector<string>& array, vector<double>& array2, int top, int bottom) { string x = array[top]; int i = top-1; int j = bottom+1; string temp; double temp2; do{ do { j--; }while(x<array[j]); do { i++; }while(x>array[i]); if(i<j) { temp = array[i]; temp2 = array2[i]; array[i] = array[j]; array2[i] = array2[j]; array[j] = temp; array2[j] = temp2; } }while(i<j); return j; } void Name_pairs::quicksort(vector<string>& num, vector<double>& num2, int top, int bottom) // top is subscript of beginning of vector { int middle; if(top < bottom) { middle = divide(num, num2, top, bottom); quicksort(num, num2, top, middle); quicksort(num, num2, middle+1, bottom); } return; } void Name_pairs::print() { for(int i = 0; i < (names.size()-1) && i < (ages.size()-1); ++i) cout << names[i] << " , " << ages[i] << endl; } int main(){ Name_pairs np; cout << "Enter names and ages. Use 0 to cancel.\n"; bool finished = false; while(!finished){ finished = "0" == np.read_names(); finished = 0 == np.read_ages();} np.quicksort(np.names, np.ages, 0, (np.names.size()-2)); np.print(); keep_window_open();} ```
If you intend to use std::sort, you will need to use a datastructure like a pair. You can, of course, manually sort the vectors, and essentially reimplement std::sort. This question really depends on a great number of other questions, such as: * How many items will be in the vectors? * How critical is performance? * Do you REALLY want to implement your own sort algorithm? Implementing a quicksort should be fairly painless, and will allow you to avoid moving the data around.
If you manually sort them yourself, you can just swap the corresponding items in the double array along with the items in the string array that you would normally do. Or, you could have a third array: ``` vector<unsigned int> indices; ``` That just indexes into the string/double array, and sort that array instead (swapping based on the values in the string array).
Sorting with two vectors
[ "", "c++", "sorting", "" ]
When packaging a Python package with a setup.py that uses the setuptools: ``` from setuptools import setup ... ``` the source distribution created by: ``` python setup.py sdist ``` not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include. My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory? The best I have managed so far is an ugly monkey-patch: ``` from setuptools.command import sdist del sdist.finders[:] ``` But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?
Simple solution, do not use setuptools for creating the source distribution, downgrade to distutils for that command: ``` from distutils.command.sdist import sdist from setuptools import setup setup( # ... all the usual setup arguments ... cmdclass = {'sdist': sdist}, ) ```
I know you know much of this, Brandon, but I'll try to give as a complete answer as I can (although I'm no setuptools gury) for the benefit of others. The problem here is that setuptools itself involves quite a lot of black magick, including using an entry point called setuptools.file\_finders where you can add plugins to find files to include. I am, however, at a complete loss as to how REMOVE plugins from it... * Quick workaround: svn export your package to a temporary directory and run the setup.py from there. That means you have no svn, so the svn finder finds no files to include. :) * Longer workaround: Do you really need setuptools? Setuptools have a lot of features, so the answer is likely yes, but mainly those features are depdenencies (so your dependencies get installed by easy\_install), namespace packages (foo.bar), and entry points. Namespace packages can actually be created without setuptools as well. But if you use none of these you might actually get away with just using distutils. * Ugly workaround: The monkeypatch you gave to sdist in your question, which simply makes the plugin not have any finders, and exit quickly. So as you see, this answer, although as complete as I can make it, is still embarrassingly incomplete. I can't actually answer your question, though I think the answer is "You can't".
How can I make setuptools ignore subversion inventory?
[ "", "python", "packaging", "setuptools", "egg", "" ]
``` class B{ private: void DoSomething(); } class W{ private: class D: public B{ } D d; } ``` Can I call private member function in base class of D in the scope of class W?
Nope. You can never call a private member function from anywhere except the class that owns it. If you want derived classes to be able to access it, declare it protected instead. You can also declare D to be a 'friend' of class B; that would allow D to access B.DoSomething(). However, this approach is usually frowned upon.
The function DoSomething can be accessed outside the class only if it is declared as public or private. Besides as mentioned above by Aric, the inherited class can become a friend to achieve the same. The alternative approach would be to declare/define the function as virtual and do not define the virtual definition for the sub/inherited class. Doing this, will call the function definition for the base class.
Question about inheritance
[ "", "c++", "" ]
because obj, the playingCard object is created inside a nested for loop does that mean after the second for loop completes, obj gets deallocated from the stack each time? and a small side question, does a compiler use the stack (similar to recursion) to keep track of loops and nested loops? ``` ``` for(int c = 0;c<nElems;c++) { for(int z = c + 1;z<nElems;z++) { playingCard obj; } }
It gets constructed and deconstructed every iteration. However, on the stack, the concept of allocation is (for at least VS and GCC) more hazy. Since the stack is a contiguous block of memory, premanaged by the compiler, there's no real concept of allocating and deallocating in the way that there is for heap allocations (new/delete or malloc/free). The compiler uses the memory it needs on the stack, and simply rolls back the pointer later on.
The scope of the object is in with-in the enclosing braces [ whether it is a function or loop brace ]. so, as soon as the scope ends, the destructor of the object gets called and the object gets deallocated. Coming to your second question, depends on the compiler to maintain its own strategy to handle the loops and keep track of the objects.
variable allocation in a nested loop question
[ "", "c++", "loops", "stack", "" ]
In my C++ code I don't use the declarations `using namespace std;` or `using namespace boost;`. This makes my code longer and means more typing. I was thinking about starting to use the "using" declarations, but I remember some people arguing against that. What is the recommended practice? std and boost are so common there should be no much harm in that?
I use `using namespace` only in C++ files, not in headers. Besides, using hole namespace not needed in most of times. For instance, you could write `using boost::shared_ptr` or `using std::tr1::shared_ptr` to easily switch between `shared_ptr` implementations. Sample: ``` #include <iostream> using std::cout; int main() { cout << "test" << std::endl; return 0; } ```
`Using namespace ...` was not invented just for fun. If you have a good reason to use it, then do so (and the frequent use of stuff from these namespaces is the exact good reason). Don't listen to fanatics who tell you everything they don't want to do for obscure reasons themselves is evil. However, a good source for reasoning in these regards is C++ FAQ lite: <http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5> I have read it and still decided to use it like you want to. Now you can make your own informed decision :-)
Should I use std:: and boost:: prefixes everywhere?
[ "", "c++", "" ]
I was working on a demo method and found something strange(at least to me :-)) ``` enter code here class Program { public void AnotherSwap<T>(T a, T b) { T temp; temp = a; a = b; b = temp; Console.WriteLine(a); Console.WriteLine(b); } public void swap<T>(T a, T b) where T : MyInt // Passing without ref { object temp; temp = a.MyProperty; a.MyProperty = b.MyProperty; b.MyProperty = (int)temp; Console.WriteLine(a.MyProperty); Console.WriteLine(b.MyProperty); } static void Main(string[] args) { Program p = new Program(); MyInt a = new MyInt() { MyProperty = 10 }; MyInt b = new MyInt() { MyProperty = 20 }; p.swap<MyInt>(a, b); Console.WriteLine(a.MyProperty); // changed values get reflected Console.WriteLine(b.MyProperty); // changed values get reflected Console.WriteLine("Another Swap"); object x = 10; object y = 20; p.AnotherSwap(x, y); Console.WriteLine(x); // changed values are not getting reflected Console.WriteLine(y); // changed values are not getting reflected Console.ReadKey(); } public class MyInt { public int MyProperty { get; set; } } } ``` Here when I am calling the swap() , though I haven't mentioned ref , the changed values are automatically getting reflected (as in p.swap(a, b); a and b are instance of Myint and thus will by default work as ref..as per my understanding.) But same should happen with Anotherswap() here also I am passing object x,y but now the values are not getting reflected in Main() .i.e. now its working as a value type. Can somebody explain where my understanding is going wrong. Let me know if u guys want more info.
When MyInt type is cast as Object, it gets cast as a val type. Object cannot be treated like a reference since its representing both val and ref, it must be explicitly passed by ref. int can be cast as an object, and its still treated as a val. string can be cast as object, and its treated as a val. Even though normally it would be a ref type. If you did the AnotherSwap and passed T in as MyInt, you would get the same results as before. If you called the original swap algorithm with objects, you would get the same output as the latter.
Your question is misleading, and the answer is actually simpler than that: In your Swap function, you are swapping the values of the MyProperty properties in those classes, not the actual classes themselves. This would be easily proved if you had another property in the MyInt class called "Name" or something. After the call to Swap, you would see that the Name property remained unchanged. The reason that in AnotherSwap nothing interesting is happening is because you aren't passing the types by ref at all, so the assignments that you perform to the object's pointer inside the function don't modify the original objects' pointers from the caller's perspective. Something else to consider is that when you're turning 10 into an object, you're actually boxing the object, and that's something else you need to keep in mind. When writing generics that you want to behave differently for reference versus value types, I always just use "where T : class" for reference types and "where T : struct" for value types. The names of the two functions cannot be the same though.
ref type and value type in Generic
[ "", "c#", "generics", "" ]
I want to be able to download a URL in C++. Something as simple as: ``` std::string s; s=download("http://www.example.com/myfile.html"); ``` Ideally, this would include URLs like: * <ftp://example.com/myfile.dat> * file:///usr/home/myfile.dat * <https://example.com/myfile.html> I was using asio in Boost, but it didn't really seem to have the code for handling protocols like ftp and https. Now I discovered QT has more what I need (<http://doc.trolltech.com/2.3/network.html>). It's tempting to make the switch to Qt, but it seems a bit heavy and intersects a lot of Boost functionality. Is it worth learning yet another API (Qt) or can Boost do more than I think?
Not a direct answer, but you might like to consider [libCURL](http://curl.haxx.se/), which is almost exactly what you describe. There are sample applications [here](http://curl.haxx.se/libcurl/c/example.html), and in particular [this](http://curl.haxx.se/libcurl/c/simple.html) demonstrates how simple usage can be.
You can use [URLDownloadToFile](https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775123(v=vs.85)). ``` #include <Urlmon.h> HANDLE hr; hr=URLDownloadToFile(NULL, L"http://www.example.com/myfile.html",L"mylocalfile.html",BINDF_GETNEWESTVERSION,NULL); ``` According to [MSDN](https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775130(v=vs.85)), BINDF\_GETNEWESTVERSION - is a "Value that indicates that the bind operation retrieves the newest version of the data or object available. In URL monikers, this flag maps to the WinInet flag, INTERNET\_FLAG\_RELOAD, which forces a download of the requested resource".
Download a URL in C++
[ "", "c++", "sockets", "" ]
Is there a way to make a variable non-inheritable in python? Like in the following example: B is a subclass of A, but I want it to have its own SIZE value. Could I get an Error to be raised (on \_\_init\_\_ or on getsize()) if B doesn't override SIZE? ``` class A: SIZE = 5 def getsize(self): return self.SIZE class B(A): pass ``` **Edit**: ... while inheriting the getsize() method...?
If you want to make *absolutely* sure that subclasses of `A` override `SIZE`, you could use a metaclass for `A` that will raise an error when a subclass does not override it (note that `A` is a new-style class here): ``` class ClassWithSize(type): def __init__(cls, name, bases, attrs): if 'SIZE' not in attrs: raise NotImplementedError('The "%s" class does not implement a "SIZE" attribute' % name) super(ClassWithSize, cls).__init__(name, bases, attrs) class A(object): __metaclass__ = ClassWithSize SIZE = 5 def getsize(self): return self.SIZE class B(A): SIZE = 6 class C(A): pass ``` When you put the above in a module and attempt to import it, an exception will be raised when the import reaches the `C` class implementation.
Use a double-underscore prefix: (Double-underscore solution deleted after Emma's clarification) OK, you can do it like this: ``` class A: SIZE = 5 def __init__(self): if self.__class__ != A: del self.SIZE def getsize(self): return self.SIZE class B(A): pass a = A() print a.getsize() # Prints 5 b = B() print b.getsize() # AttributeError: B instance has no attribute 'SIZE' ```
Making a variable non-inheritable in python
[ "", "python", "inheritance", "" ]
I understand SetCurrentDirectory shouldn't be used in a multithreaded application since the current directory is shared between all threads in the process. What is the best approach to setting the directory with this in mind. It can mostly be avoided setting the directory by including the full pathname when opening files instead of first navigating to them with SetCurrentDirectory, but is this the only solution?
I've encountered this problem before. Any object that needs the concept of a current directory to support relative paths or searching (e.g. a build tool) has a member property that it maintains with its "current" path, then build the full path to open/create/search. The initial value for CurrentPath can be retrieved once during the application's load phase, e.g. main(), WinMain(), DllInit(), etc. via GetCurrentDirectory and stored in a global. After that the Win32 version is ignored. The OPENFILENAME structure has an initial directory member, so file open/save dialogs don't have to use the Win32 current directory.
Each process has a single current directory, so if you want each thread in your process use different current directory I think you should specify the full path in each.
SetCurrentDirectory in multi-threaded application
[ "", "c++", "windows", "multithreading", "winapi", "visual-c++", "" ]
I'm using the Google Map API to retrieve city + state/region information from a postal code lookup. The issue is that in some cases a postal code lookup won't retrieve a city name. An example is 92625 (U.S). ``` var g = new GClientGeocoder(); g.setBaseCountryCode('US'); g.getLocations('92625', function(response){ if (response) { var place = response.Placemark[0]; var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName; var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; GLog.write("City = "+city+" : State/Region = "+state+" : Country = " + g.getBaseCountryCode()); } }); ``` In certain cases, as mentioned above, there won't be a city name in the result so there will be an undefined error for city, because the key Locality does not exist. This error prevents the rest of the script from running. I was able to remedy it by... ``` if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null) var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName; else var city = ''; ``` ...but this has me paranoid about a similar error for other keys. Eg: If AdministrativeArea is undefined the above IF statement would also cause an undefined error. So should I be checking to see if every Key/Node exists? Seems to be a messy approach because some of these keys are 5+ levels deep...is there an easier way to go about it, maybe some JQuery method I'm not familiar with?
Alternatively, you could make a function, that gives you defaults: ``` function valueOrDefault(val, def) { if (def == undefined) def = ""; return val == undefined ? def : val; } ``` And then use it like this: ``` var place = response.Placemark[0]; var state = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName); var city = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName); ``` Personally, I think it's a little nicer to write, than p00ya's proposal, although it's a little hacky fiddling around in undefined objects ... one could maybe change it to this: ``` function drill(p, a) { a = a.split(".");//add this for (i in a) { var key = a[i]; if (p[key] == null) return ''; p = p[key]; } return p; } var obj = {foo:{bar:{baz:"quux"}}}; var s = drill(obj, "foo.bar.baz"));//and you can use a simple property chain ```
You could use a function that "drills" down through all those nesting levels, defaulting to the empty string if it can't get that far. ``` function drill(p, a) { for (i in a) { var key = a[i]; if (p[key] == null) return ''; p = p[key]; } return p; } var obj = {foo:{bar:{baz:"quux"}}}; var s = drill(obj, ["foo", "bar", "baz"])); ```
Check if JSON keys/nodes exist
[ "", "javascript", "json", "google-maps", "" ]
As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge? I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django. Thanks,
You want to do that with out any client side code (javascript and ajax are just examples) and with out reloading your page (or at least part of it)? If that is your question, then the answer unfortunately is you can't. You need to either have client side code or reload your page. Think about it, once the client get's the page it will not change unless * The client requests the same page from the server and the server returns and updated one * the page has some client side code (eg: javascript) that updates the page.
You definitely want to use AJAX. Which means the client will need to run some javascript code. If you don't want to learn javascript you can always try something like [pyjamas](http://pyjs.org/). You can check out an example of it's HttpRequest [here](http://pyjs.org/book/output/Bookreader.html#Rest%20of%20the%20World) But I always feel that using straight javascript via a library (like jQuery) is easier to understand than trying to force one language into another one.
creating non-reloading dynamic webapps using Django
[ "", "python", "ajax", "django", "" ]
What is the best open-source library to manage X10 devices from Java?
Check out the [Java X10 Project](http://www.agaveblue.org/projects/x10/). You might also want to take a look at [HomeRun](http://homerun.sourceforge.net/)
We are working on Freedom, an open source building automation framework developed by University of Trento, DISI Department (Italy) extensible through plugins (http://freedom.disi.unitn.it/). You can use Freedom as backend and develop your own plugins over it without starting from scratch. It's a young project but we like contributors :)
Managing X10 devices from Java
[ "", "java", "x10", "" ]
What is the best way to compare objects in JavaScript? Example: ``` var user1 = {name : "nerd", org: "dev"}; var user2 = {name : "nerd", org: "dev"}; var eq = user1 == user2; alert(eq); // gives false ``` I know that **two objects are equal if they refer to the exact same object**, but is there a way to check if they have the same attributes' values? The following way works for me, but is it the only possibility? ``` var eq = Object.toJSON(user1) == Object.toJSON(user2); alert(eq); // gives true ```
Unfortunately there is no perfect way, unless you use `_proto_` recursively and access all non-enumerable properties, but this works in Firefox only. So the best I can do is to guess usage scenarios. --- ## **1) Fast and limited.** Works when you have simple JSON-style objects without methods and DOM nodes inside: ``` JSON.stringify(obj1) === JSON.stringify(obj2) ``` The ORDER of the properties IS IMPORTANT, so this method will return false for following objects: ``` x = {a: 1, b: 2}; y = {b: 2, a: 1}; ``` --- ## **2) Slow and more generic.** Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors. This is almost correct algorithm: ``` function deepCompare () { var i, l, leftChain, rightChain; function compare2Objects (x, y) { var p; // remember that NaN === NaN returns false // and isNaN(undefined) returns true if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') { return true; } // Compare primitives and functions. // Check if both arguments link to the same object. // Especially useful on the step where we compare prototypes if (x === y) { return true; } // Works in case when functions are created in constructor. // Comparing dates is a common scenario. Another built-ins? // We can even handle functions passed across iframes if ((typeof x === 'function' && typeof y === 'function') || (x instanceof Date && y instanceof Date) || (x instanceof RegExp && y instanceof RegExp) || (x instanceof String && y instanceof String) || (x instanceof Number && y instanceof Number)) { return x.toString() === y.toString(); } // At last checking prototypes as good as we can if (!(x instanceof Object && y instanceof Object)) { return false; } if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) { return false; } if (x.constructor !== y.constructor) { return false; } if (x.prototype !== y.prototype) { return false; } // Check for infinitive linking loops if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) { return false; } // Quick checking of one object being a subset of another. // todo: cache the structure of arguments[0] for performance for (p in y) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } } for (p in x) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } switch (typeof (x[p])) { case 'object': case 'function': leftChain.push(x); rightChain.push(y); if (!compare2Objects (x[p], y[p])) { return false; } leftChain.pop(); rightChain.pop(); break; default: if (x[p] !== y[p]) { return false; } break; } } return true; } if (arguments.length < 1) { return true; //Die silently? Don't know how to handle such case, please help... // throw "Need two or more arguments to compare"; } for (i = 1, l = arguments.length; i < l; i++) { leftChain = []; //Todo: this can be cached rightChain = []; if (!compare2Objects(arguments[0], arguments[i])) { return false; } } return true; } ``` Known issues (well, they have very low priority, probably you'll never notice them): * objects with different prototype structure but same projection * functions may have identical text but refer to different closures **Tests:** passes tests are from *[How to determine equality for two JavaScript objects?](https://stackoverflow.com/a/16788517/139361)*.
Here is my **ES3** commented solution (gory details after the code): ``` function object_equals( x, y ) { if ( x === y ) return true; // if both x and y are null or undefined and exactly the same if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false; // if they are not strictly equal, they both need to be Objects if ( x.constructor !== y.constructor ) return false; // they must have the exact same prototype chain, the closest we can do is // test there constructor. for ( var p in x ) { if ( ! x.hasOwnProperty( p ) ) continue; // other properties were tested using x.constructor === y.constructor if ( ! y.hasOwnProperty( p ) ) return false; // allows to compare x[ p ] and y[ p ] when set to undefined if ( x[ p ] === y[ p ] ) continue; // if they have the same strict value or identity then they are equal if ( typeof( x[ p ] ) !== "object" ) return false; // Numbers, Strings, Functions, Booleans must be strictly equal if ( ! object_equals( x[ p ], y[ p ] ) ) return false; // Objects and Arrays must be tested recursively } for ( p in y ) if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false; // allows x[ p ] to be set to undefined return true; } ``` In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both ***null*** and ***undefined*** properties and objects have ***prototypes chains*** that can lead to very different behaviors if not checked. First I have chosen to not extend ***Object.prototype***, mostly because ***null*** could not be one of the objects of the comparison and that I believe that ***null*** should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of ***Object.prototype*** regarding possible side effects on other's code. Special care must taken to deal the possibility that JavaScript allows object properties can be set to ***undefined***, i.e. there exists properties which values are set to ***undefined***. The above solution verifies that both objects have the same properties set to ***undefined*** to report equality. This can only be accomplished by checking the existence of properties using ***Object.hasOwnProperty( property\_name )***. Also note that ***JSON.stringify()*** removes properties that are set to ***undefined***, and that therefore comparisons using this form will ignore properties set to the value ***undefined***. Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object. The two objects should have the same ***prototype chain***, not just the same properties. This can only be tested cross-browser by comparing the ***constructor*** of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using ***Object.getPrototypeOf()***. Some web browsers also offer a **\_\_proto\_\_** property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available. The use of strict comparisons is paramount here because ***2*** should not be considered equal to ***"2.0000"***, nor ***false*** should be considered equal to ***null***, ***undefined***, or ***0***. Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the ***typeof*** these properties. The speed boost could be significant on large objects with lots of scalar properties. No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the ***undefined*** value. Overall this code handles most corner cases in only 16 lines of code (without comments). --- **Update (8/13/2015)**. I have implemented a better version, as the function [value\_equals()](https://github.com/ReactiveSets/toubkal/blob/master/lib/util/value_equals.js) that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than [100 automated tests](https://github.com/ReactiveSets/toubkal/blob/master/test/src/value_equals.coffee) as part of the [Toubkal](https://github.com/ReactiveSets/toubkal) project test suite.
Object comparison in JavaScript
[ "", "javascript", "object", "comparison", "object-comparison", "" ]
In C++, can you have a templated operator on a class? Like so: ``` class MyClass { public: template<class T> T operator()() { /* return some T */ }; } ``` This actually seems to compile just fine, but the confusion comes in how one would use it: ``` MyClass c; int i = c<int>(); // This doesn't work int i = (int)c(); // Neither does this* ``` The fact that it compiles at all suggests to me that it's doable, I'm just at a loss for how to use it! Any suggestions, or is this method of use a non-starter?
You need to specify `T`. ``` int i = c.operator()<int>(); ``` Unfortunately, you can't use the function call syntax directly in this case. Edit: Oh, and you're missing `public:` at the beginning of the class definition.
You're basically right. It is legal to define templated operators, but they can't be called directly with explicit template arguments. If you have this operator: ``` template <typename T> T operator()(); ``` as in your example, it can only be called like this: ``` int i = c.operator()<int>(); ``` Of course, if the template argument could be deduced from the arguments, you could still call it the normal way: ``` template <typename T> T operator()(T value); c(42); // would call operator()<int> ``` An alternative could be to make the argument a reference, and store the output there, instead of returning it: ``` template <typename T> void operator()(T& value); ``` So instead of this: ``` int r = c.operator()<int>(); ``` you could do ``` int r; c(r); ``` Or perhaps you should just define a simple `get<T>()` function instead of using the operator.
Function template with an operator
[ "", "c++", "templates", "operator-overloading", "" ]
I have an array of JavaScript objects: ``` var objs = [ { first_nom: 'Laszlo', last_nom: 'Jamf' }, { first_nom: 'Pig', last_nom: 'Bodine' }, { first_nom: 'Pirate', last_nom: 'Prentice' } ]; ``` How can I sort them by the value of `last_nom` in JavaScript? I know about `sort(a,b)`, but that only seems to work on strings and numbers. Do I need to add a `toString()` method to my objects?
It's easy enough to write your own comparison function: ``` function compare( a, b ) { if ( a.last_nom < b.last_nom ){ return -1; } if ( a.last_nom > b.last_nom ){ return 1; } return 0; } objs.sort( compare ); ``` Or inline ([c/o Marco Demaio](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value/16174180#comment2298229_1129270)): ``` objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0)) ``` Or simplified for numeric ([c/o Andre Figueiredo](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value/16174180#comment31549267_1129270)): ``` objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort ```
You can also create a dynamic sort function that sorts objects by their value that you pass: ``` function dynamicSort(property) { var sortOrder = 1; if(property[0] === "-") { sortOrder = -1; property = property.substr(1); } return function (a,b) { /* next line works with strings and numbers, * and you may want to customize it to your needs */ var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0; return result * sortOrder; } } ``` So you can have an array of objects like this: ``` var People = [ {Name: "Name", Surname: "Surname"}, {Name:"AAA", Surname:"ZZZ"}, {Name: "Name", Surname: "AAA"} ]; ``` ...and it will work when you do: ``` People.sort(dynamicSort("Name")); People.sort(dynamicSort("Surname")); People.sort(dynamicSort("-Surname")); ``` Actually this already answers the question. Below part is written because many people contacted me, complaining that [it doesn't work with multiple parameters](https://stackoverflow.com/questions/11379361). ## Multiple Parameters You can use the function below to generate sort functions with multiple sort parameters. ``` function dynamicSortMultiple() { /* * save the arguments object as it will be overwritten * note that arguments object is an array-like object * consisting of the names of the properties to sort by */ var props = arguments; return function (obj1, obj2) { var i = 0, result = 0, numberOfProperties = props.length; /* try getting a different result from 0 (equal) * as long as we have extra properties to compare */ while(result === 0 && i < numberOfProperties) { result = dynamicSort(props[i])(obj1, obj2); i++; } return result; } } ``` Which would enable you to do something like this: ``` People.sort(dynamicSortMultiple("Name", "-Surname")); ``` ### Subclassing Array For the lucky among us who can use ES6, which allows extending the native objects: ``` class MyArray extends Array { sortBy(...args) { return this.sort(dynamicSortMultiple(...args)); } } ``` That would enable this: ``` MyArray.from(People).sortBy("Name", "-Surname"); ```
Sort array of objects by string property value
[ "", "javascript", "arrays", "sorting", "comparison", "array-of-dict", "" ]
When printing a report, the user **sometime** have the following error: ``` CrystalDecisions.CrystalReports.Engine.LogOnException: Error in File C:\DOCUME~1\carolec\LOCALS~1\Temp\temp_b117cc2e-c184-4556-a493-e04e6d4126fb {388C2B55-114E-4087-A22D-9289902AFDEB}.rpt: Unable to connect: incorrect log on parameters. ---> System.Runtime.InteropServices.COMException (0x8004100F): Error in File C:\DOCUME~1\carolec\LOCALS~1\Temp\temp_b117cc2e-c184-4556-a493-e04e6d4126fb {388C2B55-114E-4087-A22D-9289902AFDEB}.rpt: Unable to connect: incorrect log on parameters. à CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.GetLastPageNumber(RequestContext pRequestContext) à CrystalDecisions.ReportSource.EromReportSourceBase.GetLastPageNumber(ReportPageRequestContext reqContext) --- Fin de la trace de la pile d'exception interne --- à CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e) à CrystalDecisions.ReportSource.EromReportSourceBase.GetLastPageNumber(ReportPageRequestContext reqContext) à CrystalDecisions.CrystalReports.Engine.FormatEngine.PrintToPrinter(Int32 nCopies, Boolean collated, Int32 startPageN, Int32 endPageN) à CrystalDecisions.CrystalReports.Engine.ReportDocument.PrintToPrinter(Int32 nCopies, Boolean collated, Int32 startPageN, Int32 endPageN) ``` Any ideas on a solution? Configuration: C# (2008), WinForm, Crystal Report 10, SQL Server 2008 Express (local)
Haven't used Crystal Reports for a bit, but generally an error along the lines of "LogOn Exception" may actually have nothing to do with security at all, Crystal Report errors can be a bit random. Its possible it may be an error related to memory issues. Or... It might be report specific, a sub-report maybe trying to logon using credentials stored within the report, rather than the credentials you've passed into it via the code; You need to loop through all sub-reports rather than just the main report setting the login information. I remember having this particular error when I used a workaround to install a dynamic logo for a report (that got pulled from a binary field within another database table) except there was a slight error in which it pulled the logo data for each row of data; After a certain amounts of rows returned it died resulting in a similar error.
For anyone having the same problem, also check if your report's Datasource provider is "SQL Native Client". If yes, this wont work in your Production server which doesn't have SQL client installed. It has to be "SQLOLEDB" for it work in machines where there is no SQL client installed. This was the reason why my report worked on my test server(which had SQL server client) and did not work in my production server
Crystal Report: Unable to connect incorrect log on parameters
[ "", "c#", "winforms", "crystal-reports", "sql-server-express", "" ]
How can I change the CommandTimeout in SQL Management Studio?
Changing Command Execute Timeout in **Management Studio**: Click on Tools -> Options Select **Query Execution** from tree on left side and enter command timeout in "*Execute Timeout*" control. Changing Command Timeout in **Server**: In the object browser tree right click on the server which give you timeout and select "*Properties*" from context menu. Now in "*Server Properties -.....*" dialog click on "**Connections**" page in "Select a Page" list (on left side). On the right side you will get property ``` Remote query timeout (in seconds, 0 = no timeout): [up/down control] ``` you can set the value in up/down control.
If you are getting a timeout while on the table designer, change the "Transaction time-out after" value under Tools --> Options --> Designers --> Table and Database Designers This will get rid of this message: **"Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."** ![enter image description here](https://i.stack.imgur.com/rlzXg.png)
Changing the CommandTimeout in SQL Management studio
[ "", "sql", "ssms", "timeoutexception", "" ]
I just realized something crazy, which I assumed to be completely impossible : when deserializing an object, the **DataContractSerializer doesn't call the constructor** ! Take this class, for instance : ``` [DataContract] public class Book { public Book() { // breakpoint here } [DataMember(Order = 0)] public string Title { get; set; } [DataMember(Order = 1)] public string Author { get; set; } [DataMember(Order = 2)] public string Summary { get; set; } } ``` When I deserialize an object of that class, the breakpoint is not hit. I have absolutely no idea how it is possible, since it is the only constructor for this object ! I assumed that perhaps an additional constructor was generated by the compiler because of the `DataContract` attribute, but I couldn't find it through reflection... So, what I'd like to know is this : how could an instance of my class be created without the constructor being called ?? *NOTE: I know that I can use the `OnDeserializing` attribute to initialize my object when deserialization begins, this is not the subject of my question.*
`DataContractSerializer` (like `BinaryFormatter`) doesn't use **any** constructor. It creates the object as empty memory. For example: ``` Type type = typeof(Customer); object obj = System.Runtime.Serialization. FormatterServices.GetUninitializedObject(type); ``` The assumption is that the deserialization process (or callbacks if necessary) will fully initialize it.
There are some scenario's that wouldn’t be possible without this behavior. Think of the following: 1) You have an object that has one constructor that sets the new instance to an "initialized" state. Then some methods are called on that instance, that bring it in a "processed" state. You don’t want to create new objects having the "processed" state, but you still want de serialize / deserialize the instance. 2) You created a class with a private constructor and some static properties to control a small set of allowed constructor parameters. Now you can still serialize / deserialize them. XmlSerializer has the behavior you expected. I have had a some problems with the XmlSerializer because it DOES need a default constructor. Related to that, sometimes it makes sense to have private property setters. But the XmlSerializer also needs public getter and setter on properties in order to serialize / deserialize. I think of the DataContractSerializer / BinaryFormatter behavior like suspending the state of an instance during serialization and resuming during deserialization. In other words, the instances are not “constructed” but “restored” to an earlier state. As you already mentioned, the [OnDeserializing] attribute makes it possible to keep non serialized data in sync.
DataContractSerializer doesn't call my constructor?
[ "", "c#", ".net", "constructor", "serialization", "datacontractserializer", "" ]
I need to find the total size of a drive in Java 5 (or 1.5, whatever). I know that Java 6 has a new method in java.io.File, but I need it to work in Java 5. Apache Commons IO has org.apache.commons.io.FileSystemUtils to provide the *free* disk space, but not the total disk space. I realize this is OS dependant and will need to depend on messy command line invocation. I'm fine with it working on "most" systems, i.e. windows/linux/macosx. Preferably I'd like to use an existing library rather than write my own variants. Any thoughts? Thanks.
Update: I apologise for misreading the question, I recommend copying the FileSystemUtils approach, but modifying the commands it runs slightly. In dos you can get the free and total bytes with the fsutil command: ``` fsutil volume diskfree [drive letter] ``` on my box this gives the following results: ``` Total # of free bytes : 41707524096 Total # of bytes : 80023715840 Total # of avail free bytes : 41707524096 ``` On Unix, the command is still "df -k", you're just interested in the "1024-blocks" column to the left of "Free" (example from Wikipedia below). You obviously need to multiply the result by 1024. ``` Filesystem 1024-blocks Free %Used Iused %Iused Mounted on /dev/hd4 32768 16016 52% 2271 14% / /dev/hd2 4587520 1889420 59% 37791 4% /usr /dev/hd9var 65536 12032 82% 518 4% /var /dev/hd3 819200 637832 23% 1829 1% /tmp /dev/hd1 524288 395848 25% 421 1% /home /proc - - - - - /proc /dev/hd10opt 65536 26004 61% 654 4% /opt ``` Assuming you copy FileSystemUtils to implement "totalSpaceKB()" to delegate to an equivalent OS-specific method. The implementation for Windows would be something like this (note the use of "Find" to trim the output from fsutil to just get the total size): ``` long totalSpaceWindows(String path) throws IOException { path = FilenameUtils.normalize(path); if (path.length() > 2 && path.charAt(1) == ':') { path = path.substring(0, 2); // seems to make it work } // build and run the 'fsutil' command String[] cmdAttribs = new String[] { "cmd.exe", "/C", "fsutil volume diskfree " + path + " | Find \"Total # of bytes\"" }; // read in the output of the command to an ArrayList List lines = performCommand(cmdAttribs, Integer.MAX_VALUE); //because we used Find, we expect the first line to be "Total # of bytes", //you might want to add some checking to be sure if (lines.size() > 0) { String line = (String) lines.get(0); String bytes = line.split(":")[1].trim(); return Long.parseLong(bytes); } // all lines are blank throw new IOException( "Command line 'fsutil volume diskfree' did not return + "any info for path '" + path + "'"); } ``` The implementation for Unix would be the same as freeSpaceUnix(), but remove the two calls to tok.nextToken() at the end of the method ``` /** comment these two lines so the token received is the total size */ tok.nextToken(); // Ignore 1K-blocks tok.nextToken(); // Ignore Used /** this will now be the total size */ String freeSpace = tok.nextToken(); return parseBytes(freeSpace, path); } ``` The implementations for other platforms would be similar. Hope this helps and apologies agian for misreading the problem. --- **Original answer (gets free bytes, not total).** Prior to Java 6 there isn't an elegant way to do this, (see the [bug](https://bugs.java.com/bugdatabase/view_bug?bug_id=4057701)). Rather than rolling your own, I'd recommend using a library to do the platform-specific processing for you. [Apache commons-io](http://commons.apache.org/io/) has a [FileSystemUtils](http://commons.apache.org/io/api-release/index.html?org/apache/commons/io/FileSystemUtils.html) type that provides a static method freeSpaceKb(). It works on Windows and and some Unix implementations (see quote from Javadoc below) From the Javadoc: > public static long freeSpaceKb(String path) > throws IOException > Returns the free space on a drive or volume in kilobytes by invoking the command line. > FileSystemUtils.freeSpaceKb("C:"); // Windows > FileSystemUtils.freeSpaceKb("/volume"); // \*nix > The free space is calculated via the command line. It uses 'dir /-c' on Windows, 'df -kP' on AIX/HP-UX and 'df -k' on other Unix. > In order to work, you must be running Windows, or have a implementation of Unix df that supports GNU format when passed -k (or -kP). If you are going to rely on this code, please check that it works on your OS by running some simple tests to compare the command line with the output from this class. If your operating system isn't supported, please raise a JIRA call detailing the exact result from df -k and as much other detail as possible, thanks.
**Note:** This solution is recommended only as a **last ditch attempt** I do not know if this exists in any API/library. However, as a **last ditch attempt** I would probably create an Ant script or use Ant task implementations to execute an OS command appropriate to the platform and then parse the output stream. Why Ant? - because it provides: * Good platform identification (see [os condition](http://ant.apache.org/manual/Tasks/conditions.html)) * Platform independent [command execution](http://ant.apache.org/manual/Tasks/exec.html) * Ability to parse output from command execution programmatically - by writing the output to a property and then accessing this from the Ant [project](http://www.jajakarta.org/ant/ant-1.6.1/docs/ja/manual/api/org/apache/tools/ant/Project.html) object. Yes, this is a little messy, but you could execute said target using the Ant API and then wrap it all up with your own interface. This still wouldn't necessarily cover all possible systems - only those that Ant can identify. Additionally it is still a fair bit of work, you'll need to work out the correct commands and parsing strategies for all of your target platforms. Again - **last ditch attempt** - so wait for other answers and continue your search for other libraries and API offerings.
Portable way of finding total disk size in Java (pre java 6)
[ "", "java", "" ]
In my application comes with an uninstaller. Everything is working fine, except that I can't find no way to delete the uninstaller.exe file when it's all done. I tried to copy the current assembly exe into a temp directory, but the file-handle of the original file is still locked. Any ideas?
You will need to PInvoke to do this. [MoveFileEx](http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) has the ability to schedule deleting the file on next reboot. > If dwFlags specifies MOVEFILE\_DELAY\_UNTIL\_REBOOT and lpNewFileName is NULL, MoveFileEx registers the lpExistingFileName file to be deleted when the system restarts. Something like: ``` [return: MarshalAs (UnmanagedType.Bool)] [DllImport ("kernel32", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool MoveFileEx (string lpExistingFileName, string lpNewFileName, int dwFlags); public static bool ScheduleDelete (string fileFullName) { if (!File.Exists (fileFullName)) throw new InvalidOperationException ("File does not exist."); return MoveFileEx (fileFullName, null, 0x04); //MOVEFILE_DELAY_UNTIL_REBOOT = 0x04 } ```
It would be interesting if you posted some code of how you exactly copy the uninstaller.exe and change execution to that specific executable. I think [unloading the application domain](http://msdn.microsoft.com/en-us/library/c5b8a8f9(VS.80).aspx) will free the file-handle.
Delete currently loaded assembly
[ "", "c#", "file-io", "filehandle", "" ]
I have the following bit of code in a method called by clicking the send button, or pressing enter in the message text field in a piece of code. ``` // In class ChatWindow private void messageTextAreaKeyPressed(java.awt.event.KeyEvent evt) { // Event handler created by Netbeans GUI designer to call this method. if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { sendMessage(); } } public void sendMessage() { String currentMessage = messageTextArea.getText(); addMessage("You", currentMessage); app.sendMessage(currentMessage, 1); messageTextArea.setText(""); } ``` The last bit of code blanks the text area. However, after a message is sent by pressing the enter button, rather than being empty, the text box contains a newline. My guess is that after my event handler runs, THEN the newline character is being added. How to I stop the newline being added?
try adding `evt.consume()` after your call to `sendMessage()` ``` private void messageTextAreaKeyPressed(java.awt.event.KeyEvent evt) { if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { sendMessage(); evt.consume(); } } ```
The default `Action` for the Enter key in a `JTextArea` is to insert a new line as you have seen. So the solution is to replace the default `Action` with a custom `Action`. The benefit of this approach is that this `Action` can also be used by the `JButton` (or `JMenuItem` etc.). An `Action` is basically the same as an `ActionListener`, all you need to do is implement the `actionPerformed()` method. Read up on [Key Bindings](http://tips4java.wordpress.com/2008/10/10/key-bindings/ "Key Bindings") to see how this is done. All Swing components use Key Bindings.
Stopping default behavior of events in Swing
[ "", "java", "user-interface", "swing", "event-handling", "" ]
I am trying to create an XML file, but the XML file needs to be wrapped in nodes... hence, not easy to use append. Any help with this would be great!! My XML consists of 2 different node types: ``` <entry id="1_0"> <title>This is the title</title> <description>This is the description...</description> <subName>Publishers Name</subName> <date>Saturday, June 11th, 2007, 5:46:21 PM</date> <BorF>bug</BorF> </entry> <vote id="1_0">5</vote> ``` And I've a simple testing page using jQuery to send data (currently static) to a PHP file ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script> $(function(){ $("#addVote").click(function() { $.ajax({ type: "POST", url: "saveListData.php", data: 'url=bugs_features_listdata.xml&listData=\n<vote id="1_2">3</vote>', async: false, cache: false, success: function(data, textStatus) { if (window.console) console.log(textStatus); }, complete: function(XMLHttpRequest, textStatus){ if (window.console) console.log(textStatus); } }); }); $("#addEntry").click(function() { $.ajax({ type: "POST", url: "saveListData.php", data: 'url=bugs_features_listdata.xml&listData=\n<entry id="1_1">\n\ \t<title>This is the title 1</title>\n\ \t<description>This is the description...</description>\n\ \t<subName>Publishers Name</subName>\n\ \t<date>Saturday, June 11th, 2007, 5:46:21 PM</date>\n\ \t<BorF>bug</BorF>\n\ </entry>', async: false, cache: false, success: function(data, textStatus) { if (window.console) console.log(textStatus); }, complete: function(XMLHttpRequest, textStatus){ if (window.console) console.log(textStatus); } }); }); }); </script> </head> <body> <a id="addVote" href="#">ADD VOTE</a><br /><br /><a id="addEntry" href="#">ADD ENTRY</a> </body> </html> ``` ...that currently appends it to my XML file, but I need the beginning/ending nodes.
txwinger had the right idea in his comment on your question. You should use one of PHPs many built-in XML manipulation libraries to add the node, then serialize it and save it as a text file. In [SimpleXML](https://www.php.net/manual/en/book.simplexml.php), for instance: ``` $xml = simplexml_load_file('test.xml'); $vote = $xml->addChild('vote', '5'); $vote->addAttribute('id','1_0'); $fp = fopen('test.xml', 'w'); fwrite($fp, $xml->asXML()); fclose($fp); ``` There are [other XML manipulation libraries](https://www.php.net/manual/en/refs.xml.php) that might suit your task better
I would say it depends on the structure of you XML document. If the “rest” is predictable, you could cut that part from your file, append the new data and paste the “rest” back: ``` ⋮ n-1: <node>last node</node> n : </root> ⋮ n-1: <node>last node</node> n : <node>new node</node> n+1: </root> ```
I know PHP's read, write, and append... but can you insert? or remove last line?
[ "", "php", "xml", "insert", "append", "" ]
By default, the hour in a format string for a DateTime transforms 0 into 12. For example, if you have ``` DateTime dt = new DateTime(1999, 1, 1, 0, 0, 0); string s = dt.ToString("h:mm:ss"); ``` the value of s will be "12:0:0", not "0:0:0". Is there a way to get "0:00:00" instead?
Try ``` string s = dt.ToString("H:mm:ss"); ``` Here's the [reference page.](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)
You were close, try using this instead: ``` string s = dt.ToString("H:mm:ss"); ```
How do I format hours in DateTime to return 0 instead of 12?
[ "", "c#", ".net", "datetime", "formatting", "" ]
I want to popuate a listbox with objects of different types. I display the type (humanized) of the object in the listbox. I created a class ListBoxView that overrides the ToString method and returns a string according to the type. I create a List of ListBoxView and databind this to the listbox. ``` public class ListBoxView { private object m_value; public ListBoxView(Object value) { m_value = value; } public override string ToString() { if (m_value is Car) return "Car"; else if (m_value is User) return "Human"; else return "Not defined: " + m_value.GetType().ToString(); } public T Value { get { return m_value; } set { m_value = value; } } } ``` Can this better be solved with generics? Since I'm new to generics I'm having difficulties implementing using it. Thanks **UPDATE** The classes like Human and Car are part of a datamodel I can't change. I need to solve this on the user interface side
One very short solution, but maybe not the best, is to move the logic from your ToString method to the listBox1\_Format event handler. ``` private string FormatForListbox(object m_value) { if (m_value is Car) return "Car"; else if (m_value is User) return "Human"; else return "Not defined: " + m_value.GetType().ToString(); } private void listBox1_Format(object sender, ListControlConvertEventArgs e) { e.Value = FormatForListbox(e.ListItem); } ```
Actually I think I'd just implement `ToString()` on `Car`, `Human` etc and not bother with this class at all. Otherwise you'll have to update this class every time you add a new type. If you're worried about I18n of the type names, then keep this class, but only so you can put the results of `ToString()` through a search on a resource file for the "localised" version of the name.
Designing a generic data class
[ "", "c#", ".net", "" ]
I have the following issue related to iterating over an associative array of strings defined using `std::map`. ``` -- snip -- class something { //... private: std::map<std::string, std::string> table; //... } ``` In the constructor I populate table with pairs of string keys associated to string data. Somewhere else I have a method `toString` that returns a string object that contains all the keys and associated data contained in the table object(as key=data format). ``` std::string something::toString() { std::map<std::string, std::string>::iterator iter; std::string* strToReturn = new std::string(""); for (iter = table.begin(); iter != table.end(); iter++) { strToReturn->append(iter->first()); strToReturn->append('='); strToRetunr->append(iter->second()); //.... } //... } ``` When I'm trying to compile I get the following error: ``` error: "error: no match for call to ‘(std::basic_string<char, std::char_traits<char>, std::allocator<char> >) ()’". ``` Could somebody explain to me what is missing, what I'm doing wrong? I only found some discussion about a similar issue in the case of `hash_map` where the user has to define a hashing function to be able to use `hash_map` with `std::string` objects. Could be something similar also in my case?
Your main problem is that you are calling a method called `first()` in the iterator. What you are meant to do is use the property called `first`: ``` ...append(iter->first) rather than ...append(iter->first()) ``` As a matter of style, you shouldn't be using `new` to create that string. ``` std::string something::toString() { std::map<std::string, std::string>::iterator iter; std::string strToReturn; //This is no longer on the heap for (iter = table.begin(); iter != table.end(); ++iter) { strToReturn.append(iter->first); //Not a method call strToReturn.append("="); strToReturn.append(iter->second); //.... // Make sure you don't modify table here or the iterators will not work as you expect } //... return strToReturn; } ``` **edit:** facildelembrar pointed out (in the comments) that in modern C++ you can now rewrite the loop ``` for (auto& item: table) { ... } ```
1. Don't write a `toString()` method. This is not Java. Implement the stream operator for your class. 2. Prefer using the standard algorithms over writing your own loop. In this situation, `std::for_each()` provides a nice interface to what you want to do. 3. If you must use a loop, but don't intend to change the data, prefer `const_iterator` over `iterator`. That way, if you accidently try and change the values, the compiler will warn you. Then: ``` std::ostream& operator<<(std::ostream& str,something const& data) { data.print(str) return str; } void something::print(std::ostream& str) const { std::for_each(table.begin(),table.end(),PrintData(str)); } ``` Then when you want to print it, just stream the object: ``` int main() { something bob; std::cout << bob; } ``` If you actually need a string representation of the object, you can then use `lexical_cast`. ``` int main() { something bob; std::string rope = boost::lexical_cast<std::string>(bob); } ``` The details that need to be filled in. ``` class somthing { typedef std::map<std::string,std::string> DataMap; struct PrintData { PrintData(std::ostream& str): m_str(str) {} void operator()(DataMap::value_type const& data) const { m_str << data.first << "=" << data.second << "\n"; } private: std::ostream& m_str; }; DataMap table; public: void something::print(std::ostream& str); }; ```
How to iterate over a std::map full of strings in C++
[ "", "c++", "dictionary", "iterator", "std", "stdmap", "" ]
I'm working on a Java application that needs to communicate with a C application. The C application uses shared memory and mmap to communicate, and I need the Java application to have access to the same memory. My first attempt involved using JNI calls to retrieve data from the shared memory, but the overhead of each JNI call killed performance, so I'd like a way to get access to that memory in Java and do the data retrieval on the Java side. The idea I have is that I'd need do the following: 1. Use one JNI call to get the location of the shared memory location I need to attach to 2. Create a new FileChannel() 3. Use that FileChannel to create a MappedByteBuffer using map() Is this the best way to do this? Also, I'm not sure how to actually create the FileChannel to point at the correct memory location.
Look into using `ByteBuffer.allocateDirect`. Apparently these buffers can be passed over the JNI layer to native code which can access the memory directly. See [this page](http://onjava.com/pub/a/onjava/2002/10/02/javanio.html?page=2) (quoted below) for hints. > Now, not only can JNI code discover the address of the native memory space inside of a buffer created with ByteBuffer.allocateDirect() on the Java side, but it can allocate its own memory (with malloc(), for example) and then call back to the JVM to wrap that memory space in a new ByteBuffer object (the JNI method to do this is NewDirectByteBuffer()).
i would write a small C module mmaps the shared memory and used sockets to allow another application to see that memory (e.g. your Java app)
What is the best way to access memory in Java, similar to mmap?
[ "", "java", "memory", "" ]
I'm designing some classes and for some data I want to use fields that are constant. Now, **AS USUAL**, IE does not support the key const so ``` const T = 10; ``` not work. I could create a property via `__defineGetter__` and `__defineSetter__` to mime that but , **AS USUAL**, IE does not support that syntax (IE 8 has `Object.defineProperty` but not work on custom object). Any idea?
"No solution" is really the safest solution. Right now there is not a good mechanism for creating constants in Javascript, but if you establish a convention (ALL CAPS FOR CONSTS) to help identify them and do not overwrite them yourself then your own constants will be safe. If you are writing a public library and you are really worried about someone modifying a value then you can use a private variable only accessible to your own code by controlling scope with a function: ``` (function() { var MY_CONSTANT = 42; alert(MY_CONSTANT); // alerts "42" ...do other stuff in here... })(); alert(MY_CONSTANT); // alerts "undefined" because MY_CONSTANT is out of scope here ``` If a developer can read a value in javascript then that developer can modify that value.
There is a [freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) method in Javascript which can be used to create actual constants. Usage: ``` var consts = {}; // Object to store all constants consts.MY_CONSTANT= 6; Object.freeze(consts); // Make the consts truly read only consts.MY_CONSTANT= 7; // Trying to do this will give error ```
How to create a constant in javascript
[ "", "javascript", "constants", "" ]
I have a table called Stock and another called Listed, within the Stock Table is a Status Code that indicates when something is at the front of the queue of items of stock - I want to be able to find the most recently added item and set this to be the "front of queue" status. For example to get all the items listed and then order them by the one most recently listed I would use this query: ``` SELECT SKU FROM Stock INNER JOIN Listed ON Listed.ListingID = Stock.ListingID WHERE Stock.StatusCode = 2 ORDER BY Listed.ListDate ``` However I want to find all the items in my Stock table which need to be at the front of the queue - ie. have a StatusCode of 1 where those items have no SKU with a StatusCode of 1 e.g. I have a few items with various ProductCodes in the Stock table but can have StatusCodes of 1s and 2s - where the 1 indicates the first item in the queue, and 2 indicates the rest of the items with the same ProductCode. How do I write my query to set all those items which need a StatusCode of 1 where anything with a given ProductCode has nothing with a status code of 1? I want to set the most recently added Stock item listed with a Status Code of 1 as I have to reset them all to 2 as part of a maintainence process and need to restore the "front-of-queue" item. Most Recently Added: ListDate StatusCode: 1 (Front of Queue), 2 (Other Items in Stock of same Product Code) --- Here is some sample Data Stock Table ``` SKU ProductCode StatusCode 1 111111 1 2 111111 2 3 222222 1 4 222222 2 5 333333 2 6 333333 2 ``` Listed Table ``` ListID SKU ListDate 01 1 01/01/2009 02 2 02/01/2009 03 3 03/01/2009 04 4 04/01/2009 05 5 05/01/2009 06 6 06/01/2009 ``` In the Stock Table SKU 6 with the ProductCode 333333 has two items with the same StatusCode, I want to set the one with the most recent ListDate from the Listed Table to StatusCode 1. This would apply to all other cases of this where I need the most recently added item to have this StatusCode
``` UPDATE S1 SET S1.StatusCode = 1 FROM Stock S1 LEFT JOIN Stock S2 ON (S1.ProductCode = S2.ProductCode AND S2.StatusCode = 1) JOIN Listed L1 ON (S1.SKU = L1.SKU) WHERE S2.StatusCode IS NULL AND L1.ListDate = ( SELECT MIN(L2.ListDate) FROM Listed L2 WHERE L1.SKU = L2.SKU ) ``` Sometimes you say you want to "find" such items (that I guess would be a SELECT) and sometimes you say you want to "set" their status code -- I've taken the latter operation because it seems a better match for the problem you describe, whence the UPDATE. Also, it's not clear what you want to do when multiple otherwise-satisfactory items have identical dates and thus it's impossible to uniquely define the latest one; maybe other consraints in your situation make that impossible? Here I'm setting all of their status codes, of course it would also be possible to set none of them or a somewhat arbitrarily chosen one (by ordering on some other criteria?).
This is a variation of `pick-a-winner`... it's `pick-all-losers`. Here's the gist. There are several records with a common value, but one record is special - it is the winner. The rest of the records with that common value are losers. For example, this query picks a winner (per name) from Customers by using the lowest id. It does this by defining what a winner is in the subquery. ``` SELECT * FROM Customers c1 WHERE ( SELECT Min(CustomerID) FROM Customers c2 WHERE c2.Name = c1.Name GROUP BY c2.Name ) = c1.CustomerID ``` Then picking the losers is a simple change: ``` SELECT * FROM Customers c1 WHERE ( SELECT Min(CustomerID) FROM Customers c2 WHERE c2.Name = c1.Name GROUP BY c2.Name ) != c1.CustomerID ```
How to group this query so it behaves correctly?
[ "", "sql", "sql-server", "t-sql", "" ]
How can I check if a file has been created in the last x hours? like 23 hours etc. Using C# 3.0. Note: This must also work if I create the file now, then the file will be seconds old not an hour old yet.
Use: ``` System.IO.File.GetCreationTime(filename); ``` To get the creation time of the file, see [GetCreationTime](http://msdn.microsoft.com/en-us/library/system.io.file.getcreationtime.aspx) for more details and examples. Then you can do something like: ``` public bool IsBelowThreshold(string filename, int hours) { var threshold = DateTime.Now.AddHours(-hours); return System.IO.File.GetCreationTime(filename) <= threshold; } ```
Something like this... ``` FileInfo fileInfo = new FileInfo(@"C:\MyFile.txt"); bool myCheck = fileinfo.CreationTime > DateTime.Now.AddHours(-23); ```
Check If File Created Within Last X Hours
[ "", "c#", "" ]
With javascript event timers, you can relatively easily determine how long it too for the page to render in the browser, especially when using tools like [Jiffy](http://code.google.com/p/jiffy-web/). However, is it possible to capture more granular events such as individual image/object download times using javascript in the page? I am fairly sure this is not possible, but wanted to confirm with the javascript guru's of SO. Thank you in advance.
Sadly, unless you load the images using the javascript image object manually instead of in the markup, I don't believe this is possible. that's why you usually see this functionality in things like firefox plugins
If what you want to time can be put into an event that has a callback, you can check the time before and after. So anything you do with Ajax you can time. What exactly are you trying to time? Can you be more specific?
Can javascript capture image download times in the client?
[ "", "javascript", "" ]
MS Visual Studio editor highlights some non-keyword identifiers as keywords in C++ files. Particularly "event" and "array" are treated as keywords. That's very annoying to me, because they are not C++ keywords. I know how to add my own keywords to the list of syntax-highlighted identifiers, but how to remove existing built-in ones? I'm aware that this may require patching some executable files. So does anyone know how to do this?
It doesn't look like a disable-syntax-coloring feature is exposed in a user-friendly way. The only way I can think of selectively disabling syntax coloring is to create a new syntax coloring plugin for the IDE, and list all of the keywords you want colored. Microsoft gives information in [this article](http://msdn.microsoft.com/en-us/library/bb165041.aspx) on how to accomplish this task. The drawback to this approach is that your IDE will now have two C++ languages and I'm not sure how it will select which plug-in to choose from once it loads a .h or .cpp file. However, [this article](http://msdn.microsoft.com/en-us/library/bb166498.aspx) suggests that you can override the existing C++ plug-ins by rewriting some registry keys.
Thanks to article mentioned by Steve Guidi, I was able to find executable file that contains Colorizer and IScanner classes. It is named vcpkg.dll and located in /Microsoft Visual Studio 8/VC/vcpackages. (I'm using Visual C++ 2005 Express Edition, things may be different in other versions.) The vcpkg.dll contains null-terminated UTF-16 encoded strings. I've opened it with hex editor, and searched for "array". There is only one such string in the file, so I've replaced it with "arrry". (It is important to maintain relative alphabetical order with respect to other keywords.) Then I've searched for "event", it shows up in several places, but there is only one that isn't part of some longer string, so I've replaced this one with "evvvt". After starting Visual Studio, it turned out that "array" and "event" weren't any longer highlighted, but "arrry" and "evvvt" were! Of course this is an ugly hack, and it will void your warranty, and probably goes against Microsoft EULA, but what a relief for the eyes! Anyway, if you want to do it, be careful and remember to backup the file.
Is there a way to prevent a "keyword" from being syntax highlited in MS Visual Studio
[ "", "c++", "visual-c++", "" ]
Does something exist that I can point to my PHP project and it can look at all the files (or just the ones that I specify) and generate a diagram based on the objects and function calls? It would be a good way to verify that my design is actually being implimented :) Background: I'm trying to build a PHP website using OO principles and while, so far, it is working I still have a ways to go and already the complexity is getting out of control. I mean, I understand basically what's going on but (and I don't think I'm alone here) it's really helpful to me if I can visualise the system at once and see the flow so I can optimise, remove unnecessary things and of course, build on the foundations. I could sit down with a pen&paper and draw it (and I have done that for parts) but if there was some program that would generate an image, it would be much simplier. Plus I could do it more often. Thanks :)
[This answer](https://stackoverflow.com/questions/27857/c-c-source-code-visualization/29989#29989) is I think still valid for PHP, but I am not sure if it is totally what you want. I know some of the tools (e.g. Doxygen) work with PHP
[PHPDoc](http://www.phpdoc.org/ "PHPDoc") will create a class tree from your source code, but just in text (well, HTML). Not a pretty graph.
Visualise OO PHP code
[ "", "php", "visualization", "" ]
Using reflection on Java classes to access all field, methods, and so on: **Is there a standardized order of these elements** (which is specified in some standard)? Of course, I **could** check it empirically, but I need to know if it's always the same. **EDIT:** *I waited for the question: What I need the order for ;) Long story short: I have JAXB-annotated classes, and want no represent these classes visually. While the order of XML attributes is neither relevant for the XML standard, nor for JAXB, I want to have a certain order the XML attributes for the visual representation. For example: start comes after end. This hurts one's intuition.*
According to [the documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html): `getFields()` > Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object. **The elements in the array returned are not sorted and are not in any particular order.** This method returns an array of length 0 if the class or interface has no accessible public fields, or if it represents an array class, a primitive type, or void. `getMethods()` > Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces. Array classes return all the (public) member methods inherited from the Object class. **The elements in the array returned are not sorted and are not in any particular order.** This method returns an array of length 0 if this Class object represents a class or interface that has no public member methods, or if this Class object represents a primitive type or void.
A sample for my annotation based idea. ``` public class FiledOrder { @Retention(RetentionPolicy.RUNTIME) public @interface Order { int value(); } public class SomeClass { @Order(value=2) public int field1; @Order(value=1) public int field2; // no annotation public int field3; @Order(value=1) public void start() { } @Order(value=2) public void end() { } } /** * @param args */ public static void main(String[] args) { Field[] fields = SomeClass.class.getFields(); Arrays.sort(fields, new Comparator<Field>() { @Override public int compare(Field o1, Field o2) { Order or1 = o1.getAnnotation(Order.class); Order or2 = o2.getAnnotation(Order.class); // nulls last if (or1 != null && or2 != null) { return or1.value() - or2.value(); } else if (or1 != null && or2 == null) { return -1; } else if (or1 == null && or2 != null) { return 1; } return o1.getName().compareTo(o2.getName()); } }); for (Field f : fields) { System.out.println(f.getName()); } Method[] methods = SomeClass.class.getMethods(); Arrays.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { Order or1 = o1.getAnnotation(Order.class); Order or2 = o2.getAnnotation(Order.class); // nulls last if (or1 != null && or2 != null) { return or1.value() - or2.value(); } else if (or1 != null && or2 == null) { return -1; } else if (or1 == null && or2 != null) { return 1; } return o1.getName().compareTo(o2.getName()); } }); for (Method m : methods) { System.out.println(m.getName()); } } } ```
Java reflection: Is the order of class fields and methods standardized?
[ "", "java", "reflection", "standards-compliance", "" ]
I am trying to get my ZEND application up on my apache server running on UNIX. Initially my host didnot give PDO support ,and i got it enabled by requesting them with a mail.But now I am getting an error saying **The mysql driver is not currently installed** The stack trace is like: ``` An error occurred Application error Exception information: Message: The mysql driver is not currently installed Stack trace: #0 /home/windchim/worminc/library/Zend/Db/Adapter/Abstract.php(770): Zend_Db_Adapter_Pdo_Abstract->_connect() #1 /home/windchim/worminc/library/Zend/Db/Adapter/Abstract.php(840): Zend_Db_Adapter_Abstract->quote('aaditya258', NULL) #2 /home/windchim/worminc/library/Zend/Auth/Adapter/DbTable.php(354): Zend_Db_Adapter_Abstract->quoteInto('`password` = MD...', 'aaditya258') #3 /home/windchim/worminc/library/Zend/Auth/Adapter/DbTable.php(285): Zend_Auth_Adapter_DbTable->_authenticateCreateSelect() #4 /home/windchim/worminc/library/Zend/Auth.php(117): Zend_Auth_Adapter_DbTable->authenticate() #5 /home/windchim/worminc/application/controllers/LoginController.php(117): Zend_Auth->authenticate(Object(Zend_Auth_Adapter_DbTable)) #6 /home/windchim/worminc/library/Zend/Controller/Action.php(503): LoginController->processAction() #7 /home/windchim/worminc/library/Zend/Controller/Dispatcher/Standard.php(285): Zend_Controller_Action->dispatch('processAction') #8 /home/windchim/worminc/library/Zend/Controller/Front.php(934): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #9 /home/windchim/public_html/worm/index.php(47): Zend_Controller_Front->dispatch() #10 {main} ``` How can this be resolved? Please help
PDO, unlike the mysql\_\* functions, supports a number of database engines. To do this it needs a driver library for each one. You have the "core" of PDO installed but not the MySQL driver - just get that installed (called pdo\_mysql) and everything will be OK. Your php.ini should have one of these (windows or linux): ``` extension=php_pdo_mysql.dll extension=php_pdo_mysql.so ```
In php.ini file u just enable following line extension=php\_pdo\_mysql.dll (means remove comments in front of it) then it will be executed Correctly.
MySql driver not installed error for Zend application
[ "", "php", "mysql", "zend-framework", "pdo", "zend-db", "" ]
I'd like to add an "onload" function to my custom Dojo class such that it can call functions that register to for the event - something like myWidget.addOnLoad(...) My class is not a Dijit it's a simple class that uses dojo.declare. Upon creation several functions are called (xhr, etc) to initialize the class and I need the ability to notify other javascript functions that the widget is loaded & ready.
As [jburke already pointed out](https://stackoverflow.com/questions/1119181/how-do-i-add-onload-to-my-dojo-class/1123658#1123658) Dojo makes it easy for you: dojo.connect is all you need. Here's an example: ``` a = { loaded: function() { console.log('[a] loaded'); } } b = { dependentAction: function() { console.log('[b] dependentAction'); } } dojo.connect( a, 'loaded', b, 'dependentAction' ); a.loaded() // prints: // [a] loaded // [b] dependentAction ``` And then just execute `a.loaded()` after you're done with loading `a`.
Have you considered using dojo.publish() to publish a topic when the widget is ready? Or, if the other code has a reference to the widget, you can call an empty function on the widget instance when your widget is loaded (call it "loaded"), and then the other code that has a reference to the instance can dojo.connect to that widget instance's "loaded" method to get notified when the method is called.
How do I add "onload" to my Dojo class?
[ "", "javascript", "dojo", "widget", "onload", "" ]
I need to sanitize some data which will be used in file names. Some of the data contains spaces and ampersand characters. Is there a function which will escape or sanitize data suitable for using in a file name (or path)? I couldn't find one in the 'Filesystem Function' section of the PHP manual. So, assuming I have to write my own function, which characters do I need to escape (or change)?
If you have the opportunity to store the original name in a database I would simply create a file with a random hash (mt\_rand()/md5/sha1). The benefit would be that you don't rely on the underlying OS (characters/path length), the value or the length of the user input and additionally it is really hard to guess/forge a file name. Maybe even a base64 encoding is an option.
For Windows: ``` / \ : * ? " < > | ``` For Unix, technically nothing, but in practice the same list as Windows would be sensible. There's nothing wrong with spaces or ampersands as long as you're prepared to use quotes on command lines when you're manipulating the files. (BTW, I got that list by trying to rename a file on Windows to something including a colon, and copying from the error message.)
Which characters should I escape/sanitize for file names?
[ "", "php", "" ]
In PHP, I'm frequently doing lots of string manipulation. Is it alright to split my code into multiple functions, because if primitive types like strings are passed by value I would be significantly affecting performance.
Only objects are passed by reference. That doesn't mean you'll get a performance boost by changing to references though - PHP uses copy-on-write, so a copy is only made if you modify the variable. Splitting your code into functions won't slow it down from that point of view. There is a small overhead for calling a function, but unless your in a loop calling 10,000s of them it's probably not something you need to worry about.
Objects are passed by reference. Everything else is passed by value unless you explicitly use [pass-by-reference with the & operator](https://www.php.net/manual/en/language.references.pass.php). That being said, PHP also uses [copy-on-write](http://blog.golemon.com/2007/01/youre-being-lied-to.html) to avoid unnecessary copying.
Are primitive data types in PHP passed by reference?
[ "", "php", "performance", "byref", "" ]
Is there any way to convert from DB.Null to decimal in C#? Like ``` Object[] returnvalue = new Object[1]; returnvalue[0] = null; returnvalue[0] = Convert.ToDecimal(returnvalue[returnvalue.Length - 1]); ``` Though CLR is saying that DBNull.Value cannot be type casted. Still I want to know is there any work around? Thanks in advance
How do you expect to cast `null` to anything? It's null, nothing, nada... That said, your best bet would be to check for `DBNull` (or `null` in the above case) and use/return/whatever `default(decimal)` instead, though `null` and `DBNull` both have a significant semantic difference from just a default value; they are the absence of a value, so this is probably not what you want to do.
There is a big difference between `DBNull` and `null`; your example only shows `null`... But in answer; not really... what value whould you give it? You could test and use the default, or use `Nullable<decimal>` (aka `decimal?`): With `null` (not `DBNull`) ``` decimal? valOrNull = (decimal?)returnvalue[0]; ``` or to take `DBNull` into account: ``` object val = returnvalue[0]; decimal? valOrNull = (val == null || val is DBNull) ? (decimal?)null : (decimal?)val; // or convert if it is a string etc ```
any way to convert from DB.Null to decimal in C#
[ "", "c#", "" ]
I am looking for a good and well developed library for geometrical manipulations and evaluations in python, like: * evaluate the intersection between two lines in 2D and 3D (if present) * evaluate the point of intersection between a plane and a line, or the line of intersection between two planes * evaluate the minimum distance between a line and a point * find the orthonormal to a plane passing through a point * rotate, translate, mirror a set of points * find the dihedral angle defined by four points I have a compendium book for all these operations, and I could implement it but unfortunately I have no time, so I would enjoy a library that does it. Most operations are useful for gaming purposes, so I am sure that some of these functionalities can be found in gaming libraries, but I would prefer not to include functionalities (such as graphics) I don't need. Any suggestions ? Thanks
Perhaps take a look at [SymPy](http://sympy.org/en/index.html).
[Shapely](https://pypi.python.org/pypi/Shapely) is a nice python wrapper around the popular [GEOS](http://trac.osgeo.org/geos/) library.
Good geometry library in python?
[ "", "python", "geometry", "" ]
I have a webservice that returns a list of "Clinics" near a certain lat/long. However, in my calling web, I can't compile as an error is occuring on the following code. ``` private static List<Clinic> GetClinicsNearLocation(Coordinate coordinate, int searchDistance) { var wsDental = new ProviderLocation_Dental(); List<Clinic> clinics = wsDental.GetSearchResults( coordinate.Latitude, coordinate.Longitude, searchDistance); return clinics; } ``` The error is "Cannot convert expression type 'com.dev.webservices.Clinic[]' to return type 'System.Collections.Generic.List 'com.dev.services.dev.Clinic'" Any ideas as to why? Here is the web service's method: ``` public List<Clinic> GetSearchResults(string latitude, string longitude, int searchDistance) { var results = Clinic.GetClinicsNearLocation(latitude, longitude, searchDistance); return results; } ```
It seems that the webservice method is defined as follows: ``` Clinic[] GetSearchResults(coordinate.Latitude, coordinate.Longitude, searchDistance); ``` If you want to convert an array to a list you can do the following: ``` List<Clinic> clinics = new List<Clinic>(wsDental.GetSearchResults(coordinate.Latitude, coordinate.Longitude, searchDistance)); ``` or using ToList extension method: ``` List<Clinic> clinics = wsDental.GetSearchResults(coordinate.Latitude, coordinate.Longitude, searchDistance).ToList(); ```
The issue is the service reference in your website. Try this: ``` Right click the service in Service References -> Configure Service Reference -> in the Data Type group -> change the Collection type to System.Collections.Generic.List -> ok ``` Make sure to right click the service reference and Update Service Reference.
Issue using List returned by webservice
[ "", "c#", "asp.net", "web-services", "wsdl", "" ]
I want to achieve something like this in C# 3.5: ``` public void Register<T>() : where T : interface {} ``` I can do it with class or struct, but how to do it with an interface?
C# and the CLR don't support overall interface constraints, although you can constrain it to a particular interface (see other answers). The closest you can get is 'class' and check the type using reflection at runtime I'm afraid. Why would you want an interface constraint in the first place?
If you are asking about adding a constraint to a specific interface, that's straightforward: ``` public void Register<T>( T data ) where T : ISomeInterface ``` If you are asking whether a keyword exists like class or struct to constrain the range of possible types for T, that is not available. **While you can write:** ``` public void Register<T>( T data ) where T : class // (or struct) ``` **you cannot write:** ``` public void Register<T>( T data ) where T : interface ```
How to put an interface constraint on a generic method in C# 3.5?
[ "", "c#", "generics", "interface", "constraints", "" ]
I have a `select()` method in a database class, that has an optional boolean argument `$sum`. This argument is used to say if the method should use `COUNT(*)` or not too. I would like to show a warning, like those normal PHP errors, if I try to access `$class->sum` if the attribute is not set (i.e. when I call `select()` with `$sum == false`. Is there any way to show a warning like this, or I should just echo an error and be happy?
If you want to generate a warning, you should write ``` trigger_error($yourErrorMessage, E_USER_WARNING); ``` [`trigger_error()`](http://php.net/manual/en/function.trigger-error.php) has the `$error_type` parameter for setting the error level (`Notice`, `Warning` or `Fatal error`). The constants are, respectively: ``` E_USER_NOTICE // Notice (default) E_USER_WARNING // Warning E_USER_ERROR // Fatal Error ``` --- Note that `Fatal error` stops the execution of subsequent PHP code, while `Notice` and `Warning` let it continue. From PHP 5.5, you should also consider the [Finally](http://php.net/manual/en/language.exceptions.php) statement.
You could try [`trigger_error()`](http://php.net/manual/en/function.trigger-error.php).
Is there any way to show, or throw, a PHP warning?
[ "", "php", "warnings", "" ]
I have a background thread that handles communication with an external service. Each time the background thread receives a message I'd like to pass it to the UI thread for further processing (displaying to user). Currently I've made a thread safe message queue that is pooled periodically in Timer.Tick and filled in the background thread. But this solution is sub optimal. Do you know how to use message pump to pass events from background thread to ui thread?
There are a few techniques. 1. [`Control.Invoke()`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx) (et al) I've found this winforms technique consistently easy to use, but be aware that there are some subtle rules you need to get right. I've tried to capture a general, working implementation that properly handles the rules in a code segment I've [posted elsewhere on stackoverflow](https://stackoverflow.com/questions/714666/is-it-appropriate-to-extend-control-to-provide-consistently-safe-invoke-begininvo). 2. [`SynchronizationContext`](http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx) I haven't needed to use this technique much, so I can't really say anything meaningful about it. You should know that it exists, however. I believe that it's an effective way to ensure something gets called in a particular thread's context, even if that thread is *not* the ui thread. 3. [`DispatcherObject.Dispatcher`](http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherobject.dispatcher%28VS.85%29.aspx) If you're working with WPF, the WPF controls will generally derive from `DispatcherObject` to supply the Dispatcher object. This is a more feature-rich synchronization technique than the `Control.Invoke()`, but also more complex. Be sure to read the docs carefully.
You can use Control.Invoke and use a delegate. The delegate will be executed on the thread that created the control. <http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx>
Execute a delegate in the ui thread (using message pump)
[ "", "c#", ".net", "multithreading", "thread-safety", "message-queue", "" ]
I am using a System.Threading.ThreadPool to manage a queue of jobs from a service. I have already implemented logging like this... ``` abstract class Global { public static LogFile LogFile = null; } public class LogFile : IDisposable { private StreamWriter sw; public LogFile(string path){} public void WriteEntry(string logText) { lock (sw) { sw.WriteLine(logText); } } } ``` I want to create the log at service startup and use it from my queued worker threads.. something like this... ``` //On Service Start Global.LogFile = new LogFile("log.txt"); //Kick of worker thread ThreadPool.QueueUserWorkItem(objWrkrThread.CallbackMethod, iCount); //Worker thread logs an entry in CallbackMethod() Global.LogFile.WriteEntry("Hello World"); ``` Is this safe? Will calling a method on a static instance of a class inadvertently 'synchronise' or 'block' my threads? Michael
Nothing will 'synchronize' or 'block' unless you write code in your method. It doesn't matter whether it's an instance method or static method. So by default, WriteEntry won't block any calls from your threads but it could very well corrupt file if you don't write the code to handle multiple simultaneous calls. Read more on this topic here: [Are static methods thread safe](https://stackoverflow.com/questions/1090650/are-static-methods-thread-safe)
It's not safe to have multiple threads call WriteEntry at the same time unless it was designed to be safe.
Can I call static methods on a static class instance from a Worker thread?
[ "", "c#", "multithreading", "" ]
Is it possible to have one .NET MVC application, and have it accessible from different domains, in such a way that the content will be domain-dependant? For example, both www(dot)site1(dot)com and www(dot)site2(dot)com will point to my server's IP, and to the same website in IIS. In that website my .NET MVC application will reside. Now, I want the ability to know which site (domain name) triggered the ControllerAction, and act accordingly (for example, display different content for the homepage in the Index action, or allow/prevent access to specific content assigned to a specific site). I would appreciate any help on this. I can accept an extra parameter passed to all controller actions (probably using Routing), but if there's a more elegant solution that would be ideal.
I have written a [blog post](http://blog.lukesampson.com/subdomains-for-a-single-application-with-asp-net-mvc) about how to do this with an example web application for download. It uses an abstract base Controller that is aware of the site it is being called for - by creating controllers that inherit from this base class you have automatic access to the current "site" for the current request. It also allows you to load all your sites from a single database - can save you a bit on hosting fees if you're on a shared host, or if you run your own server you don't have to set up a new database for each site you create.
Well, you can always get the domain from the Request.RawUrl property. As Mercer mentioned, deploying these as two separate web apps would be a better solution though. If that isn't possible, I would try to design something relatively generic that would check the domain and return different Views for each domain.
Different websites on different domains, one .NET MVC application?
[ "", "c#", "asp.net", "asp.net-mvc", "asp.net-mvc-routing", "" ]
I realize that this question has been asked 100times but none that I have found really answers my questions. We have multiple developers in multiple locations working on the same project. Some use Windows, some use Mac, our server is Linux, and each developer uses a different development application (Dreamweaver, Eclipse, etc). Each developer is running some form of Apache/PHP/MYSQL on their own computer with versions identical to our live server. On the server we have the live(bug free) site, and our testing site(Each has its own mysql database). Once everything works as it should on our testing site we copy the modified files to the live site. What we are looking for is * some way to allow the developers to 'check out' the files from the testing site, and then 'check in' after they are done working with them. * We want to be able to log the date/time of the check out and check in. * We would also like to be able to copy selected folders/files to the live site after we have finished testing. The developers have varying degrees of command line knowledge, from none at all to experts. Is there possibly a GUI version of SVN? I should also add that it doesn't have to be a free option, if these requirements come with a pay solution that would be fine as well. Any information would be appreciated.
There are two easy tricks for deployment to your "live" site: 1) Use an SVN client on your "live" site to check out your software. When there are changes to deploy, run the SVN UPDATE command. (be sure to tell your webserver not to serve files in .svn folders!) 2) Have two root folders on your "live" site. When it's time to deploy, SVN EXPORT into the second folder. In your webserver config, change your document root to the second folder and restart your web server. If there's some unforeseen problem in the deployment, just switch back to the first folder. Generally speaking, you'll want developers to do testing of their changes in their local environment only. When it's time to do testing of the full product, treat your "test" server exactly the same way as your "live" server, ideally using the same methods for deployment. And find yourself a script junkie who can automate all the deployment for you, or use something like springloops.com. Eliminating manual deployment processes will probably make you happier in the long run (it's 3 AM, you think you've fixed that last deployment problem, so you go to bed. When you wake up at 12:30 PM and realize that your site has been down all morning ... it happens). For GUIs, use scplugin for Mac OS X, TortoiseSVN for Windows. In Eclipse, use one of the eclipse svn plugins.
Other SVN GUI options for the Mac include [Versions](http://www.versionsapp.com) or [Cornerstone](http://www.zennaware.com) both of which work well. If anyone is using [Coda](http://www.panic.com/coda/) for development it also has SVN support built in. The other aspects of the question have already been answered.
File Checkout/Version Control on PHP site
[ "", "php", "version-control", "" ]
[My last question was about getting the string representation of an object serialized to XML](https://stackoverflow.com/questions/1138414/can-i-serialize-xml-straight-to-a-string-instead-of-a-stream-with-c). One of the responders wrote an extension method to encapsulate the serialization process. My question now is how can I use an Extension Method to return an array of strings, when passed an `IEnumerable<T>` object, where each `string` in the array would be an individually serialized element of the `IEnumerable<T>`. Thanks in advance!
using the code example from your link, you could add another method like this or convert them into array using ToArray() method. ``` public static class XmlTools { public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> inputs) { return inputs.Select(pArg => pArg.ToXmlString()); } } ```
To answer your next several questions... ``` new XElement("people", myPeople.ToXElements()); ``` --- ``` public static class XmlTools { public static XElement ToXElement<T>(this T input) { return XElement.Parse(input.ToXmlString()); } public static IEnumerable<XElement> ToXElements<T>(this IEnumerable<T> input) { foreach (var item in input) yield return input.ToXElement(); } public static IEnumerable<string> ToXmlString<T>(this IEnumerable<T> input) { foreach (var item in input) yield return item.ToXmlString(); } public static string ToXmlString<T>(this T input) { using (var writer = new StringWriter()) { input.ToXml(writer); return writer.ToString(); } } public static void ToXml<T>(this T objectToSerialize, Stream stream) { new XmlSerializer(typeof(T)).Serialize(stream, objectToSerialize); } public static void ToXml<T>(this T objectToSerialize, StringWriter writer) { new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize); } } ```
Extension Method for serializing an IEnumerable<T> object to a string array?
[ "", "c#", "xml-serialization", "" ]
Emacs and Java change propagation Hi, I'm mostly used to code in IDE like Eclipse but I wanted to try emacs. Because I keep hearing about how much better it is than big IDE like Eclipse and Visual Studio. So I was looking at what emacs provides for Java (with the JDEE extension) but it doesn't seem as complete as Eclipse. One of the most important thing I look for in a Java editor is change propagation and error notification. For example if I rename a class, I want to be able to have all the declarations of this class renamed automatically. And if I delete a method, I want to be able to see all the place where this creates errors. I didn't find those things in emacs, and this is a showstopper for me, I can't see how I could work on big projects without those features. So my question is : those features don't exist or is it just me that haven't looked at the right place?
Emacs can be better that Eclipse, but the question is "for what"? Emacs (and VIM) are generally smaller, faster and optimized for text editing and navigation\*. In recent versions Eclipse are quite capable for editing and navigating java code but with different "style". If you are willing to learn Emacs then learn it. You will get experiences on your own and it is very important for a developer (you are the only one can decide what is work for you). But learning Emacs *does not mean to "throw out" Eclipse*, they can co-exist quite well if you use ant or maven-based project building and a source control system. You can for example do all editing in Emacs while for debugging and refactoring use Eclipse. There are some interesting thought [in this thread](https://stackoverflow.com/questions/689544/is-emacs-useful-compared-to-eclipse-programming-java/689621) about Emacs and java development. Also there is an [interesting read](http://mike.hostetlerhome.com/2007/01/23/eclipse-vs-emacs-who-wins/) and conclusions about Emacs and Eclipse from someone who tried both environment. If you are not an expert Eclipse user yet you should look at the powerful editing and navigating features of Eclipse before starting Emacs: * [10 Eclipse navigation shortcuts every java programmer should know](http://rayfd.wordpress.com/2007/05/20/10-eclipse-navigation-shortcuts-every-java-programmer-should-know/) * [Effective Eclipse: shortcut keys](http://eclipse.dzone.com/news/effective-eclipse-shortcut-key) * [Effective Eclipse: custom templates](http://eclipse.dzone.com/news/effective-eclipse-custom-templ) * [Effective Eclipse: fix it quickly](http://java.dzone.com/news/effective-eclipse-fix-it-quick) Back to the question: there is an Emacs extension called [Xrefactory for Java](http://www.xref.sk/xrefactory-java/main.html) but it does not support Java 1.5 features so it is useful only if you use Java 1.4 or older. (\*) *of course they are much more, I know :)*
Emacs is an incredible editor, with good support for developing in C. For developing in Java there is much better support in one of the Java IDE's which has deep knowledge about the programs being edited. You probably want something like Eclipse, JDeveloper or Netbeans. In my opinion you will not be satisified with developing Java with Emacs, and you should use another tool.
Emacs and Java change propagation and errors notification
[ "", "java", "emacs", "refactoring", "" ]
I am reading html in with HtmlAgilityPack, editing it, then outputting it to a StreamWriter. The HtmlAgilityPack Encoding is Latin1, and the StreamWriter is UnicdeEncoding. I am losing some characters in the conversion, and I do not want to be. I don't seem to be able to change the Encoding of a StreamWriter. What is the best around this problem?
If the web page is really Latin-1 (ISO-8859-1), it can't have any curly quotes in it; Latin-1 has no mappings for those characters. If you can see curly quotes when you open the page in your browser, they could be in the form of HTML entities (`&ldquo;` and `&rdquo;` or `&#8220;` and `&#8221;`). But I suspect the page's encoding is really windows-1252 despite what the headers and embedded declarations say. windows-1252 is identical to Latin-1 except that it replaces the control characters in the `\x80..\x9F` range (decimal `128..159`) with more useful (or at least prettier) printing characters. If HtmlAgilityPack is taking the page at its word and decoding it as ISO-8859-1, it will convert `\x93` to the control character `\u0093`, which will look like garbage if you can get it to display at all. The browser, meanwhile, will convert it to `\u201C`, the Unicode code point for the Left Double Quotation Mark. I'm not familiar with HtmlAgilityPack and I can't find any docs for it, but I would try to force it to use windows-1252. For example, you could create a windows-1252 (or "ANSI") StreamReader and have HAP use that.
At a guess; write to a `Stream` (not a `string`). If you write to a `string` (inc. `StringWriter`/`StringBuilder`, you are implicitly using .NET's UTF-16 string. If you just want to tweak the **reported** encoding (but use a `string`), then look at Jon's [answer here](https://stackoverflow.com/questions/427725#427737).
Question about Encodings: How can I output from HtmlAgilityPack to a StringWriter and keep the encoding?
[ "", "c#", ".net", "html-agility-pack", "encoding", "" ]
I have several of the same class of element on a page and am attempting to get them all to be the same height even though the content within varies slightly. I've put together a small function that yields results in both Firefox 2+ and Safari 3+ but apparently doesn't even register in IE 7. Here's what I'm using: ``` var tallestcopy = 0; $(".calloutL2Copy").each( function(index) { var tallest = $(this).height(); if (tallest > tallestcopy) { tallestcopy = tallest } }); $(".calloutL2Copy").css("height",tallestcopy); ``` Where the class ".calloutL2Copy" is applied to a div containing some text and the occasional image. I've also tried replacing the last line with: ``` $(".calloutL2Copy").height(tallestcopy); ``` Again, this works in Firefox and Safari but has no effect on the same divs in IE. I've verified that IE is getting the tallest pixel value correct, it's just not applying it to the siblings. Can anyone offer up some advice to get this thing working? UPDATE: Here's a sample of the code from the site where I'm trying to apply this technique. I didn't write the code (and am aware there's a serious case of div-itis), I'm only trying to fix CSS errors. ``` <div id="calloutL2Top"> <div class="calloutL2"> <a href="#"><img class="calloutL2Img" alt="" src="something.jpg" width="217" height="81"></a> <div class="calloutL2Copy"> <h3>Lorem Ipsum</h3> Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div> </div> <div class="calloutL2"> <a href="#"><img class="calloutL2Img" alt="" src="something.jpg" width="217" height="81"></a> <div class="calloutL2Copy"> <h3>Lorem Ipsum</h3> Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </div> </div></div> ``` UPDATE AGAIN: I got the go ahead from the higher powers and I'm going to post the IP of the site directly do the pages in question so you can view firsthand what the problem is: [url removed] What I'm trying to fix are the series of boxes along the bottom of the main content area. Hopefully this is a little more helpful.
I think you need to specify a unit... ``` $(".calloutL2Copy").css("height", tallestcopy + "px"); ``` **EDIT:** I think you are a victim of an IE bug. To fix it, I believe you'll need a clear div as the last child of your floated parent... ``` <div style="clear:both; font-size:1px; height:1px">&nbsp;</div> ``` **EDIT 2:** View the source of your site. The first line needs to be the DOCTYPE, and you have a weird character there. Sup with that?!
Have you tried ``` $(".calloutL2Copy").children().css("height",tallestcopy); ``` This should apply the css style to all the first level children of .calloutL2Copy. Also, how exactly is your HTML nested? Another thing you could try would be to firebug Firefox as the script runs and see exactly what is getting your value. This might help you understand why IE isn't working. (If you have IE8, which has developer tools, you could also look at your HTML after the script and see exactly what has gotten the css and what hasn't).
Problem setting equal heights with jQuery in IE
[ "", "javascript", "jquery", "css", "internet-explorer", "" ]
I need to move caret to end of `contenteditable` node like on Gmail notes widget. I read threads on StackOverflow, but those solutions are based on using inputs and they don't work with `contenteditable` elements.
There is also another problem. The [Nico Burns](https://stackoverflow.com/users/140293/nico-burns)'s solution works if the `contenteditable` div doesn't contain other multilined elements. For instance, if a div contains other divs, and these other divs contain other stuff inside, could occur some problems. In order to solve them, I've arranged the following solution, that is an improvement of the [Nico](https://stackoverflow.com/users/140293/nico-burns)'s one: ``` //Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ (function( cursorManager ) { //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX']; //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript Array.prototype.contains = function(obj) { var i = this.length; while (i--) { if (this[i] === obj) { return true; } } return false; } //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text function canContainText(node) { if(node.nodeType == 1) { //is an element node return !voidNodeTags.contains(node.nodeName); } else { //is not an element node return false; } }; function getLastChildElement(el){ var lc = el.lastChild; while(lc && lc.nodeType != 1) { if(lc.previousSibling) lc = lc.previousSibling; else break; } return lc; } //Based on Nico Burns's answer cursorManager.setEndOfContenteditable = function(contentEditableElement) { while(getLastChildElement(contentEditableElement) && canContainText(getLastChildElement(contentEditableElement))) { contentEditableElement = getLastChildElement(contentEditableElement); } var range,selection; if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+ { range = document.createRange();//Create a range (a range is a like the selection but invisible) range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start selection = window.getSelection();//get the selection object (allows you to change selection) selection.removeAllRanges();//remove any selections already made selection.addRange(range);//make the range you have just created the visible selection } else if(document.selection)//IE 8 and lower { range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible) range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start range.select();//Select the range (make it the visible selection } } }( window.cursorManager = window.cursorManager || {})); ``` Usage: ``` var editableDiv = document.getElementById("my_contentEditableDiv"); cursorManager.setEndOfContenteditable(editableDiv); ``` In this way, the cursor is surely positioned at the end of the last element, eventually nested. **EDIT #1**: In order to be more generic, the while statement should consider also all the other tags which cannot contain text. These elements are named *void elements*, and in [this question](https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text) there are some methods on how to test if an element is void. So, assuming that exists a function called `canContainText` that returns `true` if the argument is not a void element, the following line of code: ``` contentEditableElement.lastChild.tagName.toLowerCase() != 'br' ``` should be replaced with: ``` canContainText(getLastChildElement(contentEditableElement)) ``` **EDIT #2**: The above code is fully updated, with every changes described and discussed
Geowa4's solution will work for a textarea, but not for a contenteditable element. This solution is for moving the caret to the end of a contenteditable element. It should work in all browsers which support contenteditable. ``` function setEndOfContenteditable(contentEditableElement) { var range,selection; if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+ { range = document.createRange();//Create a range (a range is a like the selection but invisible) range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start selection = window.getSelection();//get the selection object (allows you to change selection) selection.removeAllRanges();//remove any selections already made selection.addRange(range);//make the range you have just created the visible selection } else if(document.selection)//IE 8 and lower { range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible) range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start range.select();//Select the range (make it the visible selection } } ``` It can be used by code similar to: ``` elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of setEndOfContenteditable(elem); ```
How to move the cursor to the end of a contenteditable entity
[ "", "javascript", "contenteditable", "cursor-position", "" ]