text
stringlengths
8
267k
meta
dict
Q: Should Local Variable Initialisation Be Mandatory? The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their justification. It's easy to demonstrate in c that redundant initialisation is optimised out: $ less test.c #include <stdio.h> main() { #ifdef INIT_LOC int a = 33; int b; memset(&b,66,sizeof(b)); #else int a; int b; #endif a = 0; b = 0; printf ("a = %i, b = %i\n", a, b); } $ gcc --version gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) [Not Optimised:] $ gcc test.c -S -o no_init.s; gcc test.c -S -D INIT_LOC=1 -o init.s; diff no_in it.s init.s 22a23,28 > movl $33, -4(%ebp) > movl $4, 8(%esp) > movl $66, 4(%esp) > leal -8(%ebp), %eax > movl %eax, (%esp) > call _memset 33a40 > .def _memset; .scl 3; .type 32; .endef [Optimised:] $ gcc test.c -O -S -o no_init.s; gcc test.c -O -S -D INIT_LOC=1 -o init.s; diff no_init.s init.s $ So WRT performance under what circumstances is mandatory variable initialisation NOT a good idea? IF applicable, no need to restrict answers to c/c++ but please be clear about the language/environment (and reproducible evidence much preferred over speculation!) A: If you think that an initialization is redundant, it is. My goal is to write code that is as humanly readable as possible. Unnecessary initialization confuses future reader. C compilers are getting pretty good at catching usage of unitialized variables, so the danger of that is now minimal. Don't forget, by making "fake" initialization, you trade one danger - crashing on using garbage (which leads to a bug that is very easy to find and fix) on another - program taking wrong action based on fake value (which leads to a bug that is very difficult to find). The choice depends on the application. For some, it is critical never to crash. For majority, it is better to catch the bug ASAP. A: This is a great example of Premature optimization is the root of all evil The full quote is: There is no doubt that the grail of efficiency leads to abuse. Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified. This came from Donald Knuth. who are you going to believe...your colleagues or Knuth? I know where my money is... To get back to the original question: "Should we MANDATE initialization?" I would phrase it as so: Variables should be initialize, except in situation where it can be demonstrated there is a significant performance gain to be realized by not initializing. Come armed with hard numbers... A: I'm not sure if it is necessary to "make them mandatory", but I personally think it is always better to initialize variables. If the purpose of the application is to be as tight as possible then C/C++ is open for that purpose. However, I think many of us have been burned a time or two by not initializing a variable and assuming it contains a valid value (e.g. pointer) when it really doesn't. A pointer with an address of zero is much easier to check for than if it has random garbage from the last memory contents at that particular location. I think in most cases, it is no longer a matter of performance but a matter of clarity and safety. A: It should be mostly mandatory. The reason for this has nothing to do with performance but rather the danger of using an unitialized variable. However, there are cases where it simply looks ridiculous. For example, I have seen: struct stat s; s.st_dev = -1; s.st_ino = -1; s.st_mode = S_IRWXU; s.st_nlink = 0; s.st_size = 0; // etc... s.st_st_ctime = -1; if(stat(path, &s) != 0) { // handle error return; } WTF??? Note that we are handling the error right away, so there is no question about what happens if the stat fails. A: Let me tell you a story about a product I worked on in 1992 and later that, for the purposes of this story, we'll call Stackrobat. I was assigned a bug that caused the application to crash on the Mac, but not on Windows, oh and the bug was not reproducible reliably. It took QA the better part of a week to come up with a recipe that worked maybe 1 in 10 times. It was hell tracking down the root cause since the actual crash happened well after the action that did it. Ultimately, I tracked it down by writing a custom code profiler for the compiler. The compiler would quite happily inject calls to global prof_begin() and prof_end() functions and you were free to implement them yourselves. I wrote a profiler that took the return address from the stack, found the stack frame creation instruction, located the block on the stack that represented the locals for the function and coated them with a tasty layer of crap that would cause a bus error if any element was dereferenced. This caught something like a half dozen errors of pointers being used before initialization, including the bug I was looking for. What happened was that most of the time the stack happened to have values that were apparently benign if they were dereferenced. Other times the values would cause the app to shotgun its own heap, taking out the app sometime much later. I spent more than two weeks trying to find this bug. Lesson: initialize your locals. If someone barks performance at you, show them this comment and tell them that you'd rather spend two weeks running profiling code and fixing bottlenecks rather than having to track down bugs like this. Debugging tools and heap checkers have gotten way better since I had to do this, but quite frankly they got better to compensate for bugs from poor practices like this. Unless you're running on a tiny system (embedded, etc), initialization of locals should be nearly free. MOVE/LOAD instructions are very, very fast. Write the code to be solid and maintainable first. Refactor it to be performant second. A: Sometimes you need a variable as a placeholder (e.g. using the ftime functions), so it doesn't make sense to initialize them before calling the initialization function. However it wouldn't be bad, in my opinion, to annotate the fact that you are aware of the pitfalls, something in the way of uninitialized time_t t; time( &t ); A: This pertains to C++ only, but there is a definite distinction between the two methods. Let's assume you have a class MyStuff, and you want to initialize it by another class. You could do something like: // Initialize MyStuff instance y // ... MyStuff x = y; // ... What this actually does is call the copy constructor of x. It's the same as: MyStuff x(y); This is different than this code: MyStuff x; // This calls the MyStuff default constructor. x = y; // This calls the MyStuff assignment operator. Of course, completely different code is called when copy constructing vs. default constructing + assigning. Also, a single call to the copy constructor is likely to be more efficient than construction followed by assignment. A: Short answer: declare the variable as close to first use as possible and initialize to "zero" if you still need to. Long answer: If you declare a variable at the start of a function, and don't use it until later, you should reconsider your placement of the variable to as local a scope as possible. You can then usually assign to it the needed value right away. If you must declare it uninitialized because it gets assigned in a conditional, or passed by reference and assigned to, initializing it to a null-equivalent value is a good idea. The compiler can sometimes save you if you compile under -Wall, as it will warn if you read from a variable before initializing it. However, it fails to warn you if you pass it to a function. If you play it safe and set it to a null-equivalent, you have done no harm if the function you pass it to overwrites it. If, however, the function you pass it to uses the value, you can pretty much be guaranteed failing an assert (if you have one), or at least segfaulting the second you use a null object. Random initialization can do all sorts of bad things, including "work". A: Performance? Nowadays? Maybe back when CPUs ran at 10mhz it did make sense, but today its hardly a problem. Always initialise them. A: In C/C++ I totally agree with you. In Perl when I create a variable it is automatically put to a default value. my ($val1, $val2, $val3, $val4); print $val1, "\n"; print $val1 + 1, "\n"; print $val2 + 2, "\n"; print $val3 = $val3 . 'Hello, SO!', "\n"; print ++$val4 +4, "\n"; They are all set to undef initially. Undef is a false value, and a place holder. Due to the dynamic typing if I add a number to it, it assumes that my variable is a number and replaces undef with the eqivilent false value 0. If i do string operations a false version of a string is an empty string, and that gets automatically substituted. [jeremy@localhost Code]$ ./undef.pl 1 2 Hello, SO! 5 So for Perl at least declare early and don't worry. Especially as most programs have many variables. You use less lines and it looks cleaner without explicit initializing. my($x, $y, $z); :-) my $x = 0; my $y = 0; my $z = 0; A: Always initialize local variables to zero at least. As you saw, there's no real performance it. int i = 0; struct myStruct m = {0}; You're basically adding 1 or 2 assembly instructions, if that. In fact, many C runtimes will do this for you on a "Release" build and you won't be changing a thing. But you should initalize it because you will now have that guarantee. One reason not to initialize has to do with debugging. Some runtimes, eg. MS CRT, will initialize memory with predetermined and documented patterns that you can identify. So when you're pouring through memory, you can see that the memory is indeed uninitialized and that hasn't been used and reset. That can be helpful in debugging. But that's during debugging. A: Yes: always initialize your variables unless you have a very good reason not to. If my code doesn't require a particular initial value, I'll often initialize a variable to a value that will guarantee a blatant error if the code that follows is broken. A: As you've showed with respect to performacne it does not make a difference. The compiler will (in optimized builds) detect if a local variable is written without beeing read from and remove the code unless it has other side-effects. That said: If you initialize stuff with simple statements just to be sure it's initialized it's fine to do so.. I personally don't do it, for a single reason: It tricks the guys who may later maintain your code into thinking that the initialization is required. That little foo = 0; will increase the code-complexity. Other than that it's just a matter of taste. If you unnessesary initialize variables via complex statements it may have a side-effect. For example: float x = sqrt(0); May be optimized by your compiler if you are lucky and work with a clever compiler. With a not so clever compiler it may as well result in a costly and unnessesary function-call because sqrt can - as a side-effect - set the errno variable. If you call functions that you have defined yourself my best bet is, that the compiler always assumes that they may have side-effects and don't optimize them out. That may be different if the function happen to be in the same translation unit or you have whole program optimization turned on. A: Sometimes a variable is used to "collect" the result of a longer block of nested ifs/elses... In those cases I sometimes keep the variable uninitialized, because it should be initialized later by one of the conditional branches. The trick is: if I leave it uninitialized at first and then there's a bug in the long if/else block so the variable is never assigned, I can see that bug in Valgrind :-) which of course requires to frequently run the code (ideally the regular tests) through Valgrind. A: As a simple example, can you determine what this will be initialised to (C/C++)? bool myVar; We had an issue in a product that would sometimes draw an image on screen and sometimes not, usually depending on who's machine it was built with. It turned out that on my machine it was being initialised to false, and on a colleagues machine it was being initialised to true. A: I think it is in most cases a bad idea to initialize variables with an default value, because it simply hides bugs, that are easily found with uninitialized variables. If you forget to get and set the actual value, or delete the get code by accident, you probably never notice it because 0 is in many cases a reasonable value. Mostly it is much easier to trigger those bugs with an value >> 0. For example: void func(int n) { int i = 0; ... // Many lines of code for (;i < n; i++) do_something(i); After some time you are going to add some other stuff. void func(int n) { int i = 0; for (i = 0; i < 3; i++) do_something_else(i); ... // Many lines of code for (;i < n; i++) do_something(i); Now your second loop won't start with 0, but with 3, depending on what the function does it can be very difficult to find, that there is even a bug. A: Just a secondary observation. Initializations are only EASILY optimized on primitive types or when assigned by const functions. a= foo(); a= foo2(); Cannot be easily optimized because foo may have side effects. Also heap allocations before time might result in huge performance hits. Take a code like void foo(int x) { ClassA *instance= new ClassA(); //... do something not "instance" related... if(x>5) { delete instance; return; } //.. do something that uses instance } On that case, simply declare instance just when you will use it, and initialize it only there. And no The compiler Cannot optimize that for you since the constructor may have side effects that code reordering would change. edit: I fail at using the code listing feature :P
{ "language": "en", "url": "https://stackoverflow.com/questions/139686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Does the latest release May 2008 of .NET enterprise library have the updater app block? Does the latest version of the enterprise library (http://msdn.microsoft.com/en-us/library/cc512464.aspx) come with the updater application block? A: Looks like it doesn't: http://msdn.microsoft.com/en-us/library/cc511823.aspx It's now in the 'Archived Application Blocks' section of the MSDN docs. http://msdn.microsoft.com/en-us/library/cc485231.aspx A: No. Microsoft considers the Updater Application Block to be replaced by ClickOnce in .NET 2.0. The Enterprise Library for .NET 1.1 is no longer updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/139700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Indirect Typelib not imported well from Debug dll Using VC2005, I have 3 projects to build: * *libA (contains a typelib, results in libA.dll): IDL has a line library libA { ... *libB (contains a typelib importing libA, results in libB.dll): IDL has a line importlib( "libA " ); *libC (imports libB): one of the source files contains #import <libB.dll> the #import <libB.dll> is handled by the compiler in the following way (according to documentation): * *search directories of %PATH% *search directories of %LIB% *search the "additional include paths" (/I compiler option) When compiling libC, I can see that cl.exe clearly is able to find the libA.dll on the executable path (using Filemon.exe) VC error C4772: #import of typelib with another dependency However, still the libA namespace is not found and all references to libA types are replaced by __missing_type__ (edit) Meanwhile, I found out the problem only appears when using the debug dlls. Anyone seen this problem before? And solved it? A: Are you explicitly setting the project's dependencies? In other words have you set up the solution in the IDE so that project C depends on project B, and project B depends on project A? A: Are you using types defined in libA from libC? If so, I think that you need to directly import libA from libC so that it knows about libA's types. COM doesn't automatically reference the type libraries that are themselves referenced by another type library. A: I don't have an answer for you, but I had this experience several times and I'd like to share what I did. On several unrelated projects, I had your same scenario. I tried for nearly a week in one case to resolve the dependencies, but I eventually had to cut my losses in order to stay on schedule. I ended up using an #include on the .tlh file (performing an import on the DLL will generate these), then using "classic com" api calls to get pointers to the structures within the .tlh files. The code is not as clean to work with as it would be if you could use the wrapper files, but it works. IUnknown *lpUnk; hr = CoCreateInstance(clsID, NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, (void **)&lpUnk); if (FAILED(hr)) throw SomeException; // _Application *app; //Address _Application hr = lpUnk->QueryInterface(__uuidof(_Application), (void **) &app); lpUnk->Release(); if (FAILED(hr)) throw SomeException; // Do stuff with the app object app->Release(); // Then release You can somewhat "de-uglify" this by using the CComPtr wrapper template to do the release reliably from with its destructor when it goes out of scope: CComPtr<IUnknown> lpUnk; hr = CoCreateInstance(clsID, NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, (void **)lpUnk); if (FAILED(hr)) throw SomeException; // CComPtr<_Application> app; //Address _Application hr = lpUnk->QueryInterface(__uuidof(_Application), (void **) &app); if (FAILED(hr)) throw SomeException; // // Do stuff with the app object Note that the _Application pointer is an example of use of one of the structures from a .tlh file. A: Finally Found It! In the Visual Studio project, the A.idl file in LibA had the MkTypeLib Compatible setting ON. This overruled the behaviour inherited from the A project. To make things worse, it was only ON in the Debug configuration. The consequence was that for every typedef [public] tagE enum { cE1, cE2 } eE; This resulted in the tagE not being defined in the resulting typelib. When LibB did it's import( "A.dll" ), all references to tagE were replaced with __missing_type__...
{ "language": "en", "url": "https://stackoverflow.com/questions/139705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP parse_ini_file() - where does it look? if I call php's parse_ini_file("foo.ini"), in what paths does it look for foo.ini ? the include path? the function's documentation doesn't mention it. A: The filename argument for parse_ini_file is a standard php filename, so the same rules will apply as opening a file using fopen. You must either specify an absolute file path ("/path/to/my.ini") or a path relative to your current working directory ("my.ini"). See getcwd for your current working directory. Unlike the default fopen command, if a relative path is specified ("my.ini") parse_ini_file will search include paths after searching your current working directory. I verified this in php 5.2.6. A: I would imagine it only looks in the current working directory - See http://uk3.php.net/manual/en/function.getcwd.php if you want to know what that is. You can always find a path relative to your application by basing it on $_SERVER['DOCUMENT_ROOT'] A: It could depend on your config but mostly it's current directory and then include_path
{ "language": "en", "url": "https://stackoverflow.com/questions/139721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which Javascript Framework is the simplest and most powerful? I've been using various javascript frameworks including mootools, jquery, prototype and scriptaculous and have found them all good, but difficult to extend to more complex ideas. If I am going to knuckle down and learn one, which is the simplest to extend and use whilst staying powerful enough to use in a variety of directions? A: In my opinion, jQuery is exceptionally powerful and simple. It uses CSS selector syntax to pull back elements and only adds two functions to the global namespace: jQuery() and $(), which is an alias for jQuery(). There are a massive number of plugins available for jQuery to let you do things like create slide shows, accordion controls, rich calendars, etc. The book "jQuery In Action" is a phenomenal companion to the online reference material. We used it on my last project to create a fairly rich scheduling tool and we liked it so much, we're encouraging it's adoption throughout our consulting company as the defacto standard for all JavaScript use. You can check out the results at http://www.stanleysteemer.com A: See also (other related questions): * *Comparison of Javascript libraries *What JavaScript library would you choose for a new project and why? *What is the single most useful general purpose javascript library for rich internet apps? *Which JavaScript framework is best for web development? *Which JavaScript library is recommended for neat UI effects? *What is the best lightweight javascript framework? *Any good AJAX framework for Google App Engine apps? A: I propose jQuery. I'll give you some of the major arguments from the presentation that my team put on yesterday for senior management to convince them of that. Reasons: * *Community acceptance. Look at this graph. It shows searches for "prototype", "yui" and "scriptaculous" growing from 2004 to 2008. Then out of nowhere in 2006 searches fro "jquery" shoot up to double the number of the other libraries. The community is actually converging on a single leading product, and it's jQuery. *jQuery is very very succinct and readable. I conducted an experiment in which I took existing code (selected at random) written in YUI, and tried re-writing it in jQuery. It was 1/4 as long in jQuery. That makes it 4 times as easy to write, and 4 times as easy to maintain. *jQuery integrates well with the rest of the web world. The use of CSS syntax as the key for selecting items is a brilliant trick which helps to meld together the highly diseparate worlds of HTML, CSS and JavaScript. *Documentation: jQuery has excellent documentation, with clear specifications and working examples of every method. It has excellent books (I recommend "jQuery in Action".) The only competitor which matches it is YUI. *Active user community: the Google group which is the main community discussion forum for Prototype has nearly 1000 members. The Google group for jQuery has 10 times as many members. And my personal experience is that the community tends to be helpful. *Easy learning curve. jQuery is easy to learn, even for people with experience as a designer, but no experience in coding. *Performance. Check out this, which is published by mootools. It compares the speed of different frameworks. jQuery is not always the VERY fastest, but it is quite good on every test. *Plays well with others: jQuery's noConflict mode and the core library's small size help it to work well in environments that are already using other libraries. *Designed to make JavaScript usable. Looping is a pain in JavaScript; jQuery works with set objects you almost never need to write the loop. JavaScript's greatest strength is that functions are first-class objects; jQuery makes extensive use of this feature. *Plug-ins. jQuery is designed to make it easy to write plugins. And there is an enormous community of people out there writing plugins. Anything you want is probably out there. Check out things like this or this for visual examples. I hope you find this convincing! A: jQuery is my favorite A: Prototype. Is simple, unobtrusive, and makes your javascript code look cleaner than ever. It has a wonderful user group, where you can get your questions answered almost immediately A: Another vote for jQuery. It's small, focussed, and yet very powerful. It's also reasonable well documented, by the (generally awful) standards of JS libraries. It's also very easy to extend, once you get your head around the syntax. A: NOTE: This answer was pre-Angular/Ember/etc. so addresses an outdated issue. I teach this stuff, and really had little choice but to home in on JQuery, since the majority in the industry has already 'chosen' it (not always a good reason, I know), but also because - for students that already know some CSS - the entry point is lower. I've also used Mootools (my second choice), but a colleague convinced my to switch to JQuery with the 'programmability' argument - I find it cleaner to code with and understand. The JQuery community, online documentation, free online books and third-party sites help, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/139723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which syntax is better for return value? I've been doing a massive code review and one pattern I notice all over the place is this: public bool MethodName() { bool returnValue = false; if (expression) { // do something returnValue = MethodCall(); } else { // do something else returnValue = Expression; } return returnValue; } This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct? I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned. A: A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation. The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points. Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns. A: I would have used ternary, to reduce control structures... return expression ? MethodCall() : Expression; A: I suspect I will be in the minority but I like the style presented in the example. It is easy to add a log statement and set a breakpoint, IMO. Plus, when used in a consistent way, it seems easier to "pattern match" than having multiple returns. I'm not sure there is a "correct" answer on this, however. A: Some learning institutes and books advocate the single return practice. Whether it's better or not is subjective. A: That looks like a part of a bad OOP design. Perhaps it should be refactored on the higher level than inside of a single method. Otherwise, I prefer using a ternary operator, like this: return expression ? MethodCall() : Expression; It is shorter and more readable. A: Return from a method right away in any of these situations: * *You've found a boundary condition and need to return a unique or sentinel value: if (node.next = null) return NO_VALUE_FOUND; *A required value/state is false, so the rest of the method does not apply (aka a guard clause). E.g.: if (listeners == null) return null; *The method's purpose is to find and return a specific value, e.g.: if (nodes[i].value == searchValue) return i; *You're in a clause which returns a unique value from the method not used elsewhere in the method: if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount(); Otherwise, it is useful to have only one return statement so that it's easier to add debug logging, resource cleanup and follow the logic. I try to handle all the above 4 cases first, if they apply, then declare a variable named result(s) as late as possible and assign values to that as needed. A: They both accomplish the same task. Some say that a method should only have one entry and one exit point. A: I use this, too. The idea is that resources can be freed in the normal flow of the program. If you jump out of a method at 20 different places, and you need to call cleanUp() before, you'll have to add yet another cleanup method 20 times (or refactor everything) A: I guess that the coder has taken the design of defining an object toReturn at the top of the method (e.g., List<Foo> toReturn = new ArrayList<Foo>();) and then populating it during the method call, and somehow decided to apply it to a boolean return type, which is odd. Could also be a side effect of a coding standard that states that you can't return in the middle of a method body, only at the end. A: Even if no code is executed after the return value is assigned now it does not mean that some code will not have to be added later. It's not the smallest piece of code which could be used but it is very refactoring-friendly. A: Delphi forces this pattern by automatically creating a variable called "Result" which will be of the function's return type. Whatever "Result" is when the function exits, is your return value. So there's no "return" keyword at all. function MethodName : boolean; begin Result := False; if Expression then begin //do something Result := MethodCall; end else begin //do something else Result := Expression; end; //possibly more code end; A: The pattern used is verbose - but it's also easier to debug if you want to know the return value without opening the Registers window and checking EAX.
{ "language": "en", "url": "https://stackoverflow.com/questions/139739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: When to use partial mocks? I'm starting to get comfortable with the idea of fakes, stubs, mocks, and dynamic mocks. But I am still a little iffy in my understanding of when to use partial mocks. It would seem that if you're planning on mocking a service and need to resort to a partial mock then it is a sign of bad design. Is it that partial mocks are mostly for getting legacy code under test coverage? On the flip side of this, say I am testing a class which has a Reset() method. If I have already confirmed in a separate test that the Reset() method works, and I have some functionality of the class that should end with a call to this method, is it poor test design to do a partial mock of the object and run tests against the partial mock, defining an Expectation on the Reset() method. I currently have several tests set up in this manner, is this sort of thing going to get me in trouble later on? A: Its good design, imho. What happens when somebody comes after you and changes your method, removing the call to Reset? (btw, why so much state in your objects?) You might never know they screwed up until you hit production. By mocking it and asserting on that method call, you can assure nobody is going to mess up while maintaining your code. A: In your example it sounds like the Reset method is an implementation detail and by using a partial mock, you are in danger of coupling your test to the implementation of the class. This will make your test more brittle than it needs to be. I also think it makes tests more confusing to have an object having some methods with real implementations and some with stub implementations. It's just one more thing to remember when you come back to a test later. Can you either (a) use state-based testing to assert that the state of the object is as you expect after the real Reset method has been called internally; or (b) use interaction-based testing to verify that the relevant calls to collaborating objects have been made as a result of the real Reset method? You might find Test Smell: Mocking concrete classes from mockobjects.com useful. A: My understanding of partial mock was that it was for mocking abstract classes, with only the abstract methods being mocked, and the existing concrete methods being left as they are? A: One could argue that all mocks are 'partial' in that they do not fully implement an interface. As you are trying to test a very focused piece of functionality, you should only mock those aspects of supporting classes that are necessary to exercise the piece of functionality you are testing. This will allow your test to be decoupled from other tests, which is nice.
{ "language": "en", "url": "https://stackoverflow.com/questions/139752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: CVS: List all files changed between tags (or dates) Is there any way to list all the files that have changed between two tags in CVS? Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases. It would also work if I could find all files that had changed between two dates. A: cvs log -d ">=DATE" -N -S -R > cvs.log A: DLira's method gives a lot of detail, including all the changes. To just get a list of files, this works: cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 | grep "Index:" > diffs A: I suppose this command would help: cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs where RELEASE_1_0 and RELEASE_1_1 are the names of your tags. You can find a little more information on cvs diff command here plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box. Hope it helps ;) A: I prefer using rdiff and -s option cvs rdiff -s -r RELEASE_1_0 -r RELEASE_1_1 module > diffs rdiff does not require a sandbox; -s gives you a summary of the changes. A: To get the list of files between two dates using CVS: cvs diff -N -c -D YYYY-MM-DD -D YYYY-MM-DD | grep "Index:" > diff.out More information on accepted dates for the -D flag: http://docs.freebsd.org/info/cvs/cvs.info.Common_options.html A: To get a list of files that have changed between one version and another using the standard cvs commands: cvs -q log -NSR -rV-1-0-69::V-1-0-70 2>/dev/null >log.txt Or alternatively, to get a list of commit comments just drop the -R: cvs -q log -NS -rV-1-0-69::V-1-0-70 2>/dev/null >log.txt Where you replace V-1-0-69 and V-1-0-70 with the revisions you're comparing. A: The best tool I've found for this is a perl script called cvs2cl.pl. This can generate a change list in several different formats. It has many different options, but I've used the tag-to-tag options like this: cvs2cl.pl --delta dev_release_1_2_3:dev_release_1_6_8 or cvs2cl.pl --delta dev_release_1_2_3:HEAD I have also done comparisons using dates with the same tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/139759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Are there alternatives to CGI (and do I really need one)? I am designing an application that is going to consist of 3-4 services that run as separate processes and are linked by a suitable IPC. The system is going to have a web interface and I want to use whatever webserver is there. The web interface should be accessed under some URL that allows to have other URLs on the same webserver doing totally different things. I'm planning to use the path below that URL to specify what the web interface should do. It has facilities for use by other applications over the net and for humans to interact with in a browser. Off the cuff, I'd work as follows: * *make the webserver fire up a CGI process for every request it receives (like SetHandler in Apache) *let the CGI connect to the IPC *let it get whatever it needs from the backend services *let the CGI return HTML / XML and whatever HTTP Status based on the services' answers Now, what I really want is to avoid the first two steps, or if I can't, avoid the second one, because I'm afraid that I'm wasting performance on unneccesary overhead (the requests coming from other applications might be frequent). PHP, for example, can open persistent connections to a MySQL database that survive the script's runtime and don't need to be recreated next time, though I don't know how they actually do it. Also, as I understand it, the Apache modules are loaded once when the server starts, so that might remove the first step but would tie me to Apache. So, what are good ways to hook a handler for specific URLs into different webservers? I don't want to handle the HTTP, otherwise I might just use a proxy setup to a second server, but it just seems to be so reinventing-the-wheel. If you think, CGI is fine and have examples where it handles large numbers of request of a similar structure, please let me know. A: OK, I overlooked this previously. Explaining my question here brought me onto it: Instead of creating a new process for every request, FastCGI can use a single persistent process which handles many requests over its lifetime. -- Wikipedia: FastCGI A: Even under moderate loads, CGI is a pretty unscalable beast. FastCGI is an option, but you'll probably also find a mod_XXXX package where XXXX is the name of your language. There's a mod for ruby, perl, and python for instance and probably a fair few others.
{ "language": "en", "url": "https://stackoverflow.com/questions/139760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I get the path of the PHP file originally called within an included file? Let's say we have index.php and it is stored in /home/user/public/www and index.php calls the class Foo->bar() from the file inc/app/Foo.class.php. I'd like the bar function in the Foo class to get a hold of the path /home/user/public/www in this instance — I don't want to use a global variable, pass a variable, etc. A: getcwd() gets the current working directory It can be changed for a variety of reasons by 3rd party modules, includes or even your own code by issuing a chdir(). debug_backtrace() as Devon suggested is the answer you're looking for. A: You can use debug_backtrace to look at the calling path and get the file calling this function. A short example: class Foo { function bar() { $trace = debug_backtrace(); echo "calling file was ".$trace[0]['file']."\n"; } } A: Wouldn't this get you the directory of the running script more easily? $dir=dirname($_SERVER["SCRIPT_FILENAME"]) A: Found it. getcwd().
{ "language": "en", "url": "https://stackoverflow.com/questions/139794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sending messages to WCF host process I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost? A: You don't need to inherit from ServiceHost. There are other approaches to your problem. You can pass an instance of the service class, instead of a type to ServiceHost. Thus, you can create the instance before you start the ServiceHost, and add your own event handlers to any events it exposes. Here's some sample code: MyService svc = new MyService(); svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent); ServiceHost host = new ServiceHost(svc); host.Open(); There are some caveats when using this approach, as described in http://msdn.microsoft.com/en-us/library/ms585487.aspx Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen. A: using ... using ... namespace MyWCFNamespace { class Program { static void Main(string[] args){ //instantiate the event receiver Consumer c = new Consumer(); // instantiate the event source WCFService svc = new WCFService(); svc.WCFEvent += new SomeEventHandler(c.ProcessTheRaisedEvent); using(ServiceHost host = new ServiceHost(svc)) { host.Open(); Console.Readline(); } } } public class Consumer() { public void ProcessTheRaisedEvent(object sender, MyEventArgs e) { Console.WriteLine(e.From.toString() + "\t" + e.To.ToString()); } } } namespace MyWCFNamespace { public delegate void SomeEventHandler(object sender,MyEventArgs e) [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class WCFService : IWCFService { public event SomeEventHandler WCFEvent; public void someMethod(Message message) { MyEventArgs e = new MyEventArgs(message); OnWCFEvent(e); } public void OnWCFEvent(MyEventArgs e) { SomeEventHandler handler = WCFEvent; if(handler!=null) { handler(this,e); } } // to do // Implement WCFInterface methods here } public class MyEventArgs:EventArgs { private Message _message; public MyEventArgs(Message message) { this._message=message; } } public class Message { string _from; string _to; public string From {get{return _from;} set {_from=value;}} public string To {get{return _to;} set {_to=value;}} public Message(){} public Message(string from,string to) this._from=from; this._to=to; } } You can define your WCF service with InstanceContextMode = InstanceContextMode.Single. TestService svc = new TestService(); svc.SomeEvent += new MyEventHandler(receivingObject.OnSomeEvent); ServiceHost host = new ServiceHost(svc); host.Open(); [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] // so that a single service instance is created public class TestService : ITestService { public event MyEventHandler SomeEvent; ... ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/139809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Algorithm to score similarness of sets of numbers What is an algorithm to compare multiple sets of numbers against a target set to determine which ones are the most "similar"? One use of this algorithm would be to compare today's hourly weather forecast against historical weather recordings to find a day that had similar weather. The similarity of two sets is a bit subjective, so the algorithm really just needs to diferentiate between good matches and bad matches. We have a lot of historical data, so I would like to try to narrow down the amount of days the users need to look through by automatically throwing out sets that aren't close and trying to put the "best" matches at the top of the list. Edit: Ideally the result of the algorithm would be comparable to results using different data sets. For example using the mean square error as suggested by Niles produces pretty good results, but the numbers generated when comparing the temperature can not be compared to numbers generated with other data such as Wind Speed or Precipitation because the scale of the data is different. Some of the non-weather data being is very large, so the mean square error algorithm generates numbers in the hundreds of thousands compared to the tens or hundreds that is generated by using temperature. A: I think the mean square error metric might work for applications such as weather compares. It's easy to calculate and gives numbers that do make sense. Since your want to compare measurements over time you can just leave out missing values from the calculation. For values that are not time-bound or even unsorted, multi-dimensional scatter data it's a bit more difficult. Choosing a good distance metric becomes part of the art of analysing such data. A: Use the pearson correlation coefficient. I figured out how to calculate it in an SQL query which can be found here: http://vanheusden.com/misc/pearson.php A: In finance they use Beta to measure the correlation of 2 series of numbers. EG, Beta could answer the question "Over the last year, how much would the price of IBM go up on a day that the price of the S&P 500 index went up 5%?" It deals with the percentage of the move, so the 2 series can have different scales. In my example, the Beta is Covariance(IBM, S&P 500) / Variance(S&P 500). Wikipedia has pages explaining Covariance, Variance, and Beta: http://en.wikipedia.org/wiki/Beta_(finance) A: Look at statistical sites. I think you are looking for correlation. A: As an example, I'll assume you're measuring temp, wind, and precip. We'll call these items "features". So valid values might be: * *Temp: -50 to 100F (I'm in Minnesota, USA) *Wind: 0 to 120 Miles/hr (not sure if this is realistic but bear with me) *Precip: 0 to 100 Start by normalizing your data. Temp has a range of 150 units, Wind 120 units, and Precip 100 units. Multiply your wind units by 1.25 and Precip by 1.5 to make them roughly the same "scale" as your temp. You can get fancy here and make rules that weigh one feature as more valuable than others. In this example, wind might have a huge range but usually stays in a smaller range so you want to weigh it less to prevent it from skewing your results. Now, imagine each measurement as a point in multi-dimensional space. This example measures 3d space (temp, wind, precip). The nice thing is, if we add more features, we simply increase the dimensionality of our space but the math stays the same. Anyway, we want to find the historical points that are closest to our current point. The easiest way to do that is Euclidean distance. So measure the distance from our current point to each historical point and keep the closest matches: for each historicalpoint distance = sqrt( pow(currentpoint.temp - historicalpoint.temp, 2) + pow(currentpoint.wind - historicalpoint.wind, 2) + pow(currentpoint.precip - historicalpoint.precip, 2)) if distance is smaller than the largest distance in our match collection add historicalpoint to our match collection remove the match with the largest distance from our match collection next This is a brute-force approach. If you have the time, you could get a lot fancier. Multi-dimensional data can be represented as trees like kd-trees or r-trees. If you have a lot of data, comparing your current observation with every historical observation would be too slow. Trees speed up your search. You might want to take a look at Data Clustering and Nearest Neighbor Search. Cheers. A: Talk to a statistician. Seriously. They do this type of thing for a living. You write that the "similarity of two sets is a bit subjective", but it's not subjective at all-- it's a matter of determining the appropriate criteria for similarity for your problem domain. This is one of those situation where you are much better off speaking to a professional than asking a bunch of programmers. A: First of all, ask yourself if these are sets, or ordered collections. I assume that these are ordered collections with duplicates. The most obvious algorithm is to select a tolerance within which numbers are considered the same, and count the number of slots where the numbers are the same under that measure. A: I do have a solution implemented for this in my application, but I'm looking to see if there is something that is better or more "correct". For each historical day I do the following: function calculate_score(historical_set, forecast_set) { double c = correlation(historical_set, forecast_set); double avg_history = average(historical_set); double avg_forecast = average(forecast_set); double penalty = abs(avg_history - avg_forecast) / avg_forecast return c - penalty; } I then sort all the results from high to low. Since the correlation is a value from -1 to 1 that says whether the numbers fall or rise together, I then "penalize" that with the percentage difference the averages of the two sets of numbers. A: A couple of times, you've mentioned that you don't know the distribution of the data, which is of course true. I mean, tomorrow there could be a day that is 150 degree F, with 2000km/hr winds, but it seems pretty unlikely. I would argue that you have a very good idea of the distribution, since you have a long historical record. Given that, you can put everything in terms of quantiles of the historical distribution, and do something with absolute or squared difference of the quantiles on all measures. This is another normalization method, but one that accounts for the non-linearities in the data. Normalization in any style should make all variables comparable. As example, let's say that a day it's a windy, hot day: that might have a temp quantile of .75, and a wind quantile of .75. The .76 quantile for heat might be 1 degree away, and the one for wind might be 3kmh away. This focus on the empirical distribution is easy to understand as well, and could be more robust than normal estimation (like Mean-square-error). A: Are the two data sets ordered, or not? If ordered, are the indices the same? equally spaced? If the indices are common (temperatures measured on the same days (but different locations), for example, you can regress the first data set against the second, and then test that the slope is equal to 1, and that the intercept is 0. http://stattrek.com/AP-Statistics-4/Test-Slope.aspx?Tutorial=AP Otherwise, you can do two regressions, of the y=values against their indices. http://en.wikipedia.org/wiki/Correlation. You'd still want to compare slopes and intercepts. ==== If unordered, I think you want to look at the cumulative distribution functions http://en.wikipedia.org/wiki/Cumulative_distribution_function One relevant test is Kolmogorov-Smirnov: http://en.wikipedia.org/wiki/Kolmogorov-Smirnov_test You could also look at Student's t-test, http://en.wikipedia.org/wiki/Student%27s_t-test or a Wilcoxon signed-rank test http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test to test equality of means between the two samples. And you could test for equality of variances with a Levene test http://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm Note: it is possible for dissimilar sets of data to have the same mean and variance -- depending on how rigorous you want to be (and how much data you have), you could consider testing for equality of higher moments, as well. A: Maybe you can see your set of numbers as a vector (each number of the set being a componant of the vector). Then you can simply use dot product to compute the similarity of 2 given vectors (i.e. set of numbers). You might need to normalize your vectors. More : Cosine similarity
{ "language": "en", "url": "https://stackoverflow.com/questions/139811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why results of map() and list comprehension are different? The following test fails: #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__main__': import doctest; doctest.testmod() In other words: >>> t = 1, -1 >>> args = [] >>> for i in t: ... args.append(lambda: i) ... >>> map(lambda a: a(), args) [-1, -1] >>> args = [] >>> for i in t: ... args.append((lambda i: lambda: i)(i)) ... >>> map(lambda a: a(), args) [1, -1] >>> args = [] >>> for i in t: ... args.append(lambda i=i: i) ... >>> map(lambda a: a(), args) [1, -1] A: They are different, because the value of i in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in f. By that time, i is bound to the last value if t, which is -1. So basically, this is what the list comprehension does (likewise for the genexp): x = [] i = 1 # 1. from t x.append(lambda: i) i = -1 # 2. from t x.append(lambda: i) Now the lambdas carry around a closure that references i, but i is bound to -1 in both cases, because that is the last value it was assigned to. If you want to make sure that the lambda receives the current value of i, do f(*[lambda u=i: u for i in t]) This way, you force the evaluation of i at the time the closure is created. Edit: There is one difference between generator expressions and list comprehensions: the latter leak the loop variable into the surrounding scope. A: The lambda captures variables, not values, hence the code lambda : i will always return the value i is currently bound to in the closure. By the time it gets called, this value has been set to -1. To get what you want, you'll need to capture the actual binding at the time the lambda is created, by: >>> f(*(lambda i=i: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda i=i: i for i in t]) # -> [-1, -1] [1, -1] A: Expression f = lambda: i is equivalent to: def f(): return i Expression g = lambda i=i: i is equivalent to: def g(i=i): return i i is a free variable in the first case and it is bound to the function parameter in the second case i.e., it is a local variable in that case. Values for default parameters are evaluated at the time of function definition. Generator expression is the nearest enclosing scope (where i is defined) for i name in the lambda expression, therefore i is resolved in that block: f(*(lambda: i for i in (1, -1)) # -> [-1, -1] i is a local variable of the lambda i: ... block, therefore the object it refers to is defined in that block: f(*map(lambda i: lambda: i, (1,-1))) # -> [1, -1]
{ "language": "en", "url": "https://stackoverflow.com/questions/139819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Bare Minimum Configuration for RESTful WCF What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message. A: I discovered that you can add the following to the ServiceHost directive in the *.svc file, and it will automatically setup WebHttpBinding and WebHttpBehavior for you: Factory="System.ServiceModel.Activation.WebServiceHostFactory" Note that the namespace is a little different from what is mentioned elsewhere on the web (such as in this MSDN article). After doing this, I was able to delete the entire section from web.config and everything still worked! A: Ensure that you use a webHttpBinding on your endpoint (and not an httpBinding or wsHttpBinding). Here's my endpoint config... <endpoint address="" binding="webHttpBinding" bindingConfiguration="" contract="WcfCore.ICustomer"> <identity> <dns value="localhost" /> </identity> </endpoint> A: You need to ensure that you have an address for your service host e.g <services> <service name="SomeLib.SomeService"> <host> <baseAddresses> <add baseAddress="http://localhost:8080/somebase"/> </baseAddresses> </host> <!-- And one EndPoint **basicHttpBinding** WILL WORK !!! --> <endpoint address="basic" binding="basicHttpBinding" contract="SomeLib.SomeContract"/> </service> </services> So now, if you are self hosting via a console app for e.g...you can invoke your host via: WebChannelFactory<IServiceContract> factory = new WebChannelFactory<IServiceContract>( new Uri("http://localhost:8080/somebase")); When the console app starts up, the address will be browsable even if its self hosted and you should be able to invoke your actions based on your webget uri templates. This minimum config will let you invoke WCF RestFULLY via selfhosting. If you're hosting in IIS it would essentially work the same way, except the svc file replaces our custom host.
{ "language": "en", "url": "https://stackoverflow.com/questions/139821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Track Data Execution Prevention (DEP) When running one of our software, a tester was faced with the data execution prevention dialog of Windows. We try to reproduce this situation on a developer computer for debugging purposes : with no success. Does anyone know how to find what may cause the DEP protection to kill the application? Is there any existing tools available for this? A: The DEP dialog will typically only show when you try to execute code from a region that you're not marking as executable. This might be caused by 'thunks' in a library you're using, e.g. ATL windowing. This problem is fixed in ATL 8.0. A stack-trashing bug - for example, a buffer overrun - can also cause this problem, by setting the return address to a location that isn't executable. This might not cause an access violation but instead weird behaviour, if DEP is turned off for the process or not available on the hardware. It might also happen if you throw a C++ exception or raise an SEH exception, and your structured exception handlers have been trashed by a buffer overrun. A: Potentially I would think any time you try to write to memory that isn't allocated this would be a possible result. Could be anything along the lines of deleting an object then using it, or writing a string into a buffer which is too small to hold it. A: DEP is influenced by the presence of hardware capability. We recently had a situation where our app ran fine on old machines, but would fail on new ones. It turned out that although DEP was enabled on both the old servers and the new servers, we crashed on the new ones because the hardware detection was better, more aggressive, or something like that. So if your QA can reproduce but the DEV can't, then try it with identical hardware... Although it seems unreasonable that the QA would have a newer/better PC than the dev... I totally believe it! Here are my notes on our recent experience with this: Incompatibilities between Indy 9 and Windows Server 2003?
{ "language": "en", "url": "https://stackoverflow.com/questions/139826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: StringReplace alternatives to improve performance I am using StringReplace to replace &gt and &lt by the char itself in a generated XML like this: StringReplace(xml.Text,'&gt;','>',[rfReplaceAll]) ; StringReplace(xml.Text,'&lt;','<',[rfReplaceAll]) ; The thing is it takes way tooo long to replace every occurence of &gt. Do you purpose any better idea to make it faster? A: If you're using Delphi 2009, this operation is about 3 times faster with TStringBuilder than with ReplaceString. It's Unicode safe, too. I used the text from http://www.CodeGear.com with all occurrences of "<" and ">" changed to "&lt;" and "&gt;" as my starting point. Including string assignments and creating/freeing objects, these took about 25ms and 75ms respectively on my system: function TForm1.TestStringBuilder(const aString: string): string; var sb: TStringBuilder; begin StartTimer; sb := TStringBuilder.Create; sb.Append(aString); sb.Replace('&gt;', '>'); sb.Replace('&lt;', '<'); Result := sb.ToString(); FreeAndNil(sb); StopTimer; end; function TForm1.TestStringReplace(const aString: string): string; begin StartTimer; Result := StringReplace(aString,'&gt;','>',[rfReplaceAll]) ; Result := StringReplace(Result,'&lt;','<',[rfReplaceAll]) ; StopTimer; end; A: Try FastStrings.pas from Peter Morris. A: You should definitely look at the Fastcode project pages: http://fastcode.sourceforge.net/ They ran a challenge for a faster StringReplace (Ansi StringReplace challenge), and the 'winner' was 14 times faster than the Delphi RTL. Several of the fastcode functions have been included within Delphi itself in recent versions (D2007 on, I think), so the performance improvement may vary dramatically depending on which Delphi version you are using. As mentioned before, you should really be looking at a Unicode-based solution if you're serious about processing XML. A: The problem is that you are iterating the entire string size twice (one for replacing &gt; by > and another one to replace &lt; by <). You should iterate with a for and simply check ahead whenever you find a & for a gt; or lt; and do the immediate replace and then skipping 3 characters ((g|l)t;). This way it can do that in proportional time to the size of the string xml.Text. A simple C# example as I do not know Delphi but should do for you to get the general idea. String s = "&lt;xml&gt;test&lt;/xml&gt;"; char[] input = s.ToCharArray(); char[] res = new char[s.Length]; int j = 0; for (int i = 0, count = input.Length; i < count; ++i) { if (input[i] == '&') { if (i < count - 3) { if (input[i + 1] == 'l' || input[i + 1] == 'g') { if (input[i + 2] == 't' && input[i + 3] == ';') { res[j++] = input[i + 1] == 'l' ? '<' : '>'; i += 3; continue; } } } } res[j++] = input[i]; } Console.WriteLine(new string(res, 0, j)); This outputs: <xml>test</xml> A: When you are dealing with a multiline text files, you can get some performance by processing it line by line. This approach reduced time in about 90% to replaces on >1MB xml file. procedure ReplaceMultilineString(xml: TStrings); var i: Integer; line: String; begin for i:=0 to xml.Count-1 do begin line := xml[i]; line := StringReplace(line, '&gt;', '>', [rfReplaceAll]); line := StringReplace(line, '&lt;', '<', [rfReplaceAll]); xml[i] := line; end; end; A: Untested conversion of the C# code written by Jorge Ferreira. function ReplaceLtGt(const s: string): string; var inPtr, outPtr: integer; begin SetLength(Result, Length(s)); inPtr := 1; outPtr := 1; while inPtr <= Length(s) do begin if (s[inPtr] = '&') and ((inPtr + 3) <= Length(s)) and (s[inPtr+1] in ['l', 'g']) and (s[inPtr+2] = 't') and (s[inPtr+3] = ';') then begin if s[inPtr+1] = 'l' then Result[outPtr] := '<' else Result[outPtr] := '>'; Inc(inPtr, 3); end else begin Result[outPtr] := Result[inPtr]; Inc(inPtr); end; Inc(outPtr); end; SetLength(Result, outPtr - 1); end; A: Systools (Turbopower, now open source) has a ReplaceStringAllL function that does all of them in a string. A: it's work like charm so fast trust it Function NewStringReplace(const S, OldPattern, NewPattern: string; Flags: TReplaceFlags): string; var OldPat,Srch: string; // Srch and Oldp can contain uppercase versions of S,OldPattern PatLength,NewPatLength,P,i,PatCount,PrevP: Integer; c,d: pchar; begin PatLength:=Length(OldPattern); if PatLength=0 then begin Result:=S; exit; end; if rfIgnoreCase in Flags then begin Srch:=AnsiUpperCase(S); OldPat:=AnsiUpperCase(OldPattern); end else begin Srch:=S; OldPat:=OldPattern; end; PatLength:=Length(OldPat); if Length(NewPattern)=PatLength then begin //Result length will not change Result:=S; P:=1; repeat P:=PosEx(OldPat,Srch,P); if P>0 then begin for i:=1 to PatLength do Result[P+i-1]:=NewPattern[i]; if not (rfReplaceAll in Flags) then exit; inc(P,PatLength); end; until p=0; end else begin //Different pattern length -> Result length will change //To avoid creating a lot of temporary strings, we count how many //replacements we're going to make. P:=1; PatCount:=0; repeat P:=PosEx(OldPat,Srch,P); if P>0 then begin inc(P,PatLength); inc(PatCount); if not (rfReplaceAll in Flags) then break; end; until p=0; if PatCount=0 then begin Result:=S; exit; end; NewPatLength:=Length(NewPattern); SetLength(Result,Length(S)+PatCount*(NewPatLength-PatLength)); P:=1; PrevP:=0; c:=pchar(Result); d:=pchar(S); repeat P:=PosEx(OldPat,Srch,P); if P>0 then begin for i:=PrevP+1 to P-1 do begin c^:=d^; inc(c); inc(d); end; for i:=1 to NewPatLength do begin c^:=NewPattern[i]; inc(c); end; if not (rfReplaceAll in Flags) then exit; inc(P,PatLength); inc(d,PatLength); PrevP:=P-1; end else begin for i:=PrevP+1 to Length(S) do begin c^:=d^; inc(c); inc(d); end; end; until p=0; end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/139833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I open a window's system menu by code? I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar. This form uses these styles: this.SetStyle( ControlStyles.AllPaintingInWmPaint, true ); this.SetStyle( ControlStyles.UserPaint, true ); this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true ); this.SetStyle( ControlStyles.ResizeRedraw, true ); And has these non-default property values: this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work. A: A borderless window, if I am not mistaken, is flagged such that it offers no system menu, and that it does not appear in the taskbar. The fact that any given window does not have a border and does not appear in the taskbar is the result of the style flags set on the window. These particular Style flags can be set using the GetWindowLong and SetWindowLong API calls. However you have to be careful as certain styles just don't work together. I have written a number of custom controls over the years and I am constantly coaxing windows to become something they weren't originally intended to be. For example I have written my own dropdown control where I needed a window to behave as a popup and not to activate. The following code will do that. Note that the code appears in the OnHandleCreated event handler. This is because the flags need to be changed just after the handle is setup which indicates that Windows has already set what it thinks the flags should be. using System.Runtime.InteropServices; protected override void OnHandleCreated(EventArgs e) { uint dwWindowProperty; User32.SetParent(this.Handle, IntPtr.Zero); dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.EXSTYLE ); dwWindowProperty = dwWindowProperty | (uint)User32.WSEX.TOOLWINDOW | (uint)User32.WSEX.NOACTIVATE; User32.SetWindowLong( this.Handle, User32.GWL.EXSTYLE, dwWindowProperty ); dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.STYLE ); dwWindowProperty = ( dwWindowProperty & ~(uint)User32.WS.CHILD ) | (uint)User32.WS.POPUP; User32.SetWindowLong( this.Handle, User32.GWL.STYLE, dwWindowProperty ); base.OnHandleCreated (e); } //this is a fragment of my User32 library wrapper needed for the previous code segment. class User32 { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); [DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )] public static extern int SetWindowLong( IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong); [DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )] public static extern uint GetWindowLong( IntPtr hWnd, User32.GWL gwlIndex ); [FlagsAttribute] public enum WS: uint { POPUP = 0x80000000, CHILD = 0x40000000, } public enum GWL { STYLE = -16, EXSTYLE = -20 } [FlagsAttribute] public enum WSEX: uint { TOP = 0x0, TOPMOST = 0x8, TOOLWINDOW = 0x80, NOACTIVATE = 0x08000000, } } Unfortunately the SysMenu style cannot be set without using the Caption style, so I can't say if this is a problem in your implementation. You can check out the original style list and the extend style list at these two links: Window Styles CreateWindowEx A: I have the same properties in my application and Right click doesn't work either, so this is not your problem, it appears to be the way windows forms respond when they have no border. If you set your border to the normal value, you will be able to have right click in the taskbar and such. For right click on other controls, you'll need to set the ContextMenuStrip and provide your "menu". But I'm not sure if this works when you have it without border. I have been unable to make it work. A: protected override void WndProc( ref System.Windows.Forms.Message m ) { // RightClickMenu if ( m.Msg == 0x313 ) { this.contextMenuStrip1.Show(this, this.PointToClient(new Point(m.LParam.ToInt32()))); }} This detects rightclick on the applications taskbar "area".. maybe it will help ?
{ "language": "en", "url": "https://stackoverflow.com/questions/139835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a practical example of how they have used attributes on method parameters in .NET? I know it's possible, and I've seen simple examples in the documentation, but are they being used in the wild? I use attributes at the class and method level all the time, but have never used them on method parameters. What are some real-world examples, and the reasons for the usage? I'm not interested in seeing a textbook example, mind you. There are plenty of those out there. I want to see an actual reason why it solved a particular problem for you. EDIT: Let's place aside the discussion about whether or not to use attributes in the first place. I understand some people don't like them because they "dirty" their code. That's for a different discussion! A: (I've left this answer here in case others find it a useful intro to PostSharp, but it doesn't actually answer the question properly! I misread the question as asking about method attributes instead of class attributes. Doh. From what I remember, the generated SOAP classes use parameter attributes. LINQ to SQL uses return attributes and may use parameter attributes too, when it comes to stored procs.) I'm used them with PostSharp, although admittedly only in a quick demo so far (I haven't used PostSharp in production). See my blog post for more details. Oh, and of course NUnit tests specify [Test] all over the place :) Jon A: I haven't used them myself, but Scott Gu's post about ASP.NET MVC Preview 5 shows parameter attributes being used to declare model binders for action methods. The link is at: http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx He notes that the attribute isn't yet available in Preview 5, but should be available in future builds. A: Castle Monorail has been using for many years to databind request parameters. See http://www.castleproject.org/MonoRail/documentation/trunk/integration/ar.html A: Dependency Injection is a very good example scenario. ObjectBuilder (a dependecy injection container, part of the P&P Enterprise Libary, soon to be replaced by Unity), uses them all over the place to attribute what the container should be injecting at runtime. Here's a quick example of the constructor for a controller class that has a state value (injected from whatever state provider is active, usually HttpSession) as well as two service dependencies (a locator and an authorization service): public class ShellController : ControllerBase, IShellController { public ShellController([StateDependency("State")] StateValue<ShuttleState> state, [ServiceDependency] IHttpContextLocatorService contextLocator, [ServiceDependency] IAuthorizationService authService) : base(state, contextLocator, authService) { // code goes here } } A: You can for example create a ValidatorAttribute for every parameter, then before calling the method, you can reflect the parameter attributes and do parameter validation. Then call the method if all ok. A: Unit test frameworks use them extensively: To do anything in nUnit or MSTest, you have to decorate methods with a [TestFixture] or [TestClass] attribute. My favorite? MbUnit's [DataFixture] attribute: lets you seed test cases with specific test data either within the attribute directly or an external resource.
{ "language": "en", "url": "https://stackoverflow.com/questions/139837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Cursor verus while loop - what are the advantages/disadvantages of cursors? Is it a good idea to use while loop instead of a cursor? What are the advantages/disadvantages of cursors? A: Some of these depends on the DBMS, but generally: Pros: * *Outperform loops when it comes to row-by-row processing *Works reasonably well with large datasets Cons: * *Don't scale as well *Use more server resources *Increases load on tempdb *Can cause leaks if used incorrectly (eg. Open without corresponding Close) A: I'm following this bit of advice: [...] which is better: cursors or WHILE loops? Again, it really depends on your situation. I almost always use a cursor to loop through records when necessary. The cursor format is a little more intuitive for me and, since I just use the constructs to loop through the result set once, it makes sense to use the FAST_FORWARD cursor. Remember that the type of cursor you use will have a huge impact on the performance of your looping construct. — Tim Chapman in Comparing cursor vs. WHILE loop performance in SQL Server 2008 The linked article contains simple examples of how to implement each approach. A: I would ask you what you are doing with that cursor/while loop. If you are updating or returning data why don't you use a proper WHERE clause. I know people who would say you should never use cursors.
{ "language": "en", "url": "https://stackoverflow.com/questions/139843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Can Delphi 2009 be installed on the same machine as Delphi 2006 or Delphi 2007? Is there any conflict? A: I am running 2007 and 2009 on the same machine (this machine) just fine. The only problem you might have is if you are compiling components to the same directory - you will just need to rebuild all your DCU's and packages each time, or make version specific packages and directories. A: Install them in their own directories, and make sure you keep package binaries separate, you should be fine. I've got 2009, 2007, 2006, 7 and 5 all on this machine with no issues. A: All new versions of Delphi can always be installed safely /next/ to older version. Each new version should be installed in its own directory. If you are going to install multiple versions, always install the oldest version first, and then work your way to the newest. We work very hard to make sure that all versions of Delphi coexist together. But again, never install one version directly on top of another. A: I have at least 4 Delphi versions on one machine. They do not bite each other. I always install older versions first because i had once problems if i did this the other way round. A: Yes - as Rob said (Robsoft) I have both working here. Delphi has always been very good at co-existing with other versions. Obviously you can only have one version as the default for opening Delphi files. A: Should not conflict. A: I did D2007 on the same machine as D2006 with absolutely no problems (I was shocked, actually). I haven't tried D2009 yet, but it should be ok. This guy had problems though. Hopefully his issues were due to the custom setup he describes in that article. A: A colleague of mine (think he has an account on here as dcraggs now) has got them both running on the same machine just fine, I believe. Certainly would be a huge own-goal from Embarcadero if installing D2009 broke an already-installed D2007, given the way that the components and DCUs are not compatible - I suspect a fair number of people will need to have both around for a while (some of us still need D5 and D7 too!) A: CodeGear stated (don't have a link handy, sorry) that there should be no conflict. I haven't yet installed D2009 on my workhorse PC so I don't know if that is correct. The settings in registry have different path and packages have different names so there really should be no problems. A: I have Delphi 2007 and I have installed 2009 yesterday with no visible problems so far. Both seem to work fine. A: Appears to be no problem. Installed D2009 with TurboDelphi and 2007 and 2, 5 and 7 all on the same Vista machine Both 2007 and 2009 have Jedi JVC and JVCL installed on them. All appear to work fine. Hope that helps. A: .. and if you compile existing packages make sure you give them a new name (e.g. suffix with D12) as each version's BPL directories are in the path. A: Installed D2009 Enterprise on VMWare instance running Vista Business with an existing D2007 Enterprise installation. Perhaps I did something incorrectly, but I began to experience errors in the D2007 IDE, as well as a very strange error, unknown fieldtype, in exe files compiled with D2007. I uninstalled D2009, and the errors have gone away. A: You should always install the older version first. I tried to install 2009 first and then 2007 but the setup of 2007 failed. Uninstalling 2009, and starting with 2007 first fixed the install problems. A: In theory, it's possible, but if you use many third-party (or your own) libraries, it can get hairy pretty fast. I tend toward developing on Virtual machines, for this and other reasons. But, YMMV. A: Should be fine. I have Delphi 7, 2006, 2007, 2009 with 3rd party libs Dev Express and Rem Objects for all (except Dev Express for 2009 - is it out yet?) and all work flawlessly. As others pointed out the versions were installed oldest to newest. A: The installations won't interfere with each other, although the Delphi 2009 and Delphi 2007 projects are not compatible, and can't be shared. A: Moving along with the order of release is a must. Install older first. Uninstalling may get tricky though. How to fix Delphi 2009 data explorer?
{ "language": "en", "url": "https://stackoverflow.com/questions/139844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: WCF customheader or messagebody for context? I'm witting a WCF service for a customer to send part information to our application. We have multiple customers that will have one or many locations, and part information is scoped to each location for the customer. When the customer calls our service they will need to specify the location. Options that we have considered are: 1) Placing a location id(s) in a custom header. All part information would apply to all locations listed. 2) Adding a "context" node to the message body. All part information would apply to all locations listed. 3) Adding a location node in the message body over that would contain the part information. Each location would have it's own list of parts. I'm looking for best practice/standards help in determining how this should be handled. We will have to create other services that will have the customer/location scope as well, and would like to handle this in a consistent manor. A: I would say if it's only one or two operations that need it, make it part of the data contract - sort of like making it a parameter to a method call. If every operation requires it, put it in the header, since it's just as much context as username, roles, tenant, or other authentication information - sort of like something you'd put in a request context (e.g., HttpContext). A: Do you need to use a message contract? I use Data contracts unless I need to stream something back, so everything just ends up in the body. But, even for a message contract I would put that information in the body, I tend to reserve the header for authentication information. A: We plan to send a response with processing summary information and details about any part that could not be processed. The message contract has a collection of parts, and the parts are defined in a data contract. There is also a flag in the message contract to control processing of the parts collection. This may or may not be the right place for this flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/139852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is MEF about UI? If not, why are all examples about GUI composition? The MEF team keep saying it is about plug-in model. So, are we talking about UI plugins? How can we use this stuff in non-UI code? I downloaded the code and the examples are all about GUI. Am I guessing it wrong? A: Ilya MEF is absolutely not only for UI. Nothing about MEF is UI-dependent, which is why it lives in the System.ComponentModel namespace. You can use MEF in desktop apps, web apps, or services. In terms of samples, thank you for the feedback. We do need better samples that illustrate that it is a non-UI based technology. I think the reason alot of the samples have gravitated around UI is that our chief partners like Visual Studio, are using MEF in desktop apps. I'll talk to the team about some non-UI based samples. Thanks Glenn A: Ayende sums up MEF rather nicely here: http://ayende.com/Blog/archive/2008/09/25/the-managed-extensibility-framework.aspx Also the herding code lads had a great interview with Glenn Block, one of the MS MEF guys: http://herdingcode.com/?p=28 http://herdingcode.com/?p=31 A: If you're talking about Microsoft Managed Extensibility Framework then no, it's definitely not just about UI. By doing something visual in the samples you just make it easier for people to understand the concept. You could not make it clearer that an Tetris game with plug-in blocks. A: MEF seems to be more about extending your application's functionality. In our applications we've been looking at MEF for allowing users to use different editions of a rating engine. There's no UI for those modules. It can add UI features, but it's not necessary. A: Prism might be worth noticing. MEF can be used to define components that import / export arbitrary contracts while Prism can be used to define UI regions in a decupled UI app.
{ "language": "en", "url": "https://stackoverflow.com/questions/139853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Setting the thread /proc/PID/cmdline? On Linux/NPTL, threads are created as some kind of process. I can see some of my process have a weird cmdline: cat /proc/5590/cmdline hald-addon-storage: polling /dev/scd0 (every 2 sec) Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging. A: If you want to do this in a portable way, something that will work across multiple Unix variations, there are very few options available. What you have to do is that your caller process must call exec with the argv [0] argument pointing to the name that you would like to see in the process output, and the filename pointing to the actual executable. You can try this behavior from the shell by using: exec -a "This is my cute name" bash That will replace the current bash process with one named "This is my cute name". For doing this in C, you can look at the source code of sendmail or any other piece of software that has been ported extensively and find all the variations that are needed across operating systems to support this. Some operating systems have a setproctitle(3) API, some others allow you to override the contents of argv [0] and show that result. A: argv points to writable strings. Just write stuff to them: #include <string.h> #include <unistd.h> int main(int argc, char** argv) { strcpy(argv[0], "Hello, world!"); sleep(10); return 0; } A: Bah.. the code is not that nice, the trick is to reuse the environ (here argv_buffer) pointer: memset (argv_buffer[0] + len, 0, argv_size - len); argv_buffer[1] = NULL; Any better idea? Is that working for different threads?
{ "language": "en", "url": "https://stackoverflow.com/questions/139859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there an open source java enum of ISO 3166-1 country codes Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time. A: This code gets 242 countries in Sun Java 6: String[] countryCodes = Locale.getISOCountries(); Though the ISO website claims there are 249 ISO 3166-1-alpha-2 code elements, though the javadoc links to the same information. A: There is an easy way to generate this enum with the language name. Execute this code to generate the list of enum fields to paste : /** * This is the code used to generate the enum content */ public static void main(String[] args) { String[] codes = java.util.Locale.getISOLanguages(); for (String isoCode: codes) { Locale locale = new Locale(isoCode); System.out.println(isoCode.toUpperCase() + "(\"" + locale.getDisplayLanguage(locale) + "\"),"); } } A: If anyone is already using the Amazon AWS SDK it includes com.amazonaws.services.route53domains.model.CountryCode. I know this is not ideal but it's an alternative if you already use the AWS SDK. For most cases I would use Takahiko's nv-i18n since, as he mentions, it implements ISO 3166-1. A: Now an implementation of country code (ISO 3166-1 alpha-2/alpha-3/numeric) list as Java enum is available at GitHub under Apache License version 2.0. Example: CountryCode cc = CountryCode.getByCode("JP"); System.out.println("Country name = " + cc.getName()); // "Japan" System.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2()); // "JP" System.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3()); // "JPN" System.out.println("ISO 3166-1 numeric code = " + cc.getNumeric()); // 392 Last Edit 2016-Jun-09 CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode (ISO 639-1), LanguageAlpha3Code (ISO 639-2), LocaleCode, ScriptCode (ISO 15924) and CurrencyCode (ISO 4217) and registered into the Maven Central Repository. Maven <dependency> <groupId>com.neovisionaries</groupId> <artifactId>nv-i18n</artifactId> <version>1.29</version> </dependency> Gradle dependencies { compile 'com.neovisionaries:nv-i18n:1.29' } GitHub https://github.com/TakahikoKawasaki/nv-i18n Javadoc https://takahikokawasaki.github.io/nv-i18n/ OSGi Bundle-SymbolicName: com.neovisionaries.i18n Export-Package: com.neovisionaries.i18n;version="1.28.0" A: Here's how I generated an enum with country code + country name: package countryenum; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; public class CountryEnumGenerator { public static void main(String[] args) { String[] countryCodes = Locale.getISOCountries(); List<Country> list = new ArrayList<Country>(countryCodes.length); for (String cc : countryCodes) { list.add(new Country(cc.toUpperCase(), new Locale("", cc).getDisplayCountry())); } Collections.sort(list); for (Country c : list) { System.out.println("/**" + c.getName() + "*/"); System.out.println(c.getCode() + "(\"" + c.getName() + "\"),"); } } } class Country implements Comparable<Country> { private String code; private String name; public Country(String code, String name) { super(); this.code = code; this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Country o) { return this.name.compareTo(o.name); } } A: If you are already going to rely on Java locale, then I suggest using a simple HashMap instead of creating new classes for countries etc. Here's how I would use it if I were to rely on the Java Localization only: private HashMap<String, String> countries = new HashMap<String, String>(); String[] countryCodes = Locale.getISOCountries(); for (String cc : countryCodes) { // country name , country code map countries.put(new Locale("", cc).getDisplayCountry(), cc.toUpperCase()); } After you fill the map, you can get the ISO code from the country name whenever you need it. Or you can make it a ISO code to Country name map as well, just modify the 'put' method accordingly. A: Not a java enum, but a JSON version of this is available at http://country.io/names.json A: AWS Java SDK has CountryCode. A: There is standard java.util.Locale.IsoCountryCode since Java 9. A: This still does not answer the question. I was also looking for a kind of enumerator for this, and did not find anything. Some examples using hashtable here, but represent the same as the built-in get I would go for a different approach. So I created a script in python to automatically generate the list in Java: #!/usr/bin/python f = open("data.txt", 'r') data = [] cc = {} for l in f: t = l.split('\t') cc = { 'code': str(t[0]).strip(), 'name': str(t[1]).strip() } data.append(cc) f.close() for c in data: print """ /** * Defines the <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a> * for <b><i>%(name)s</i></b>. * <p> * This constant holds the value of <b>{@value}</b>. * * @since 1.0 * */ public static final String %(code)s = \"%(code)s\";""" % c where the data.txt file is a simple copy&paste from Wikipedia table (just remove all extra lines, making sure you have a country code and country name per line). Then just place this into your static class: /** * Holds <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a> * constant values for all countries. * * @since 1.0 * * </p> */ public class CountryCode { /** * Constructor defined as <code>private</code> purposefully to ensure this * class is only used to access its static properties and/or methods. */ private CountryCode() { } /** * Defines the <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a> * for <b><i>Andorra</i></b>. * <p> * This constant holds the value of <b>{@value}</b>. * * @since 1.0 * */ public static final String AD = "AD"; // // and the list goes on! ... // } A: I didn't know about this question till I had just recently open-sourced my Java enum for exactly this purpose! Amazing coincidence! I put the whole source code on my blog with BSD caluse 3 license so I don't think anyone would have any beefs about it. Can be found here. https://subversivebytes.wordpress.com/2013/10/07/java-iso-3166-java-enum/ Hope it is useful and eases development pains. A: I have created an enum, which you address by the english country name. See country-util. On each enum you can call getLocale() to get the Java Locale. From the Locale you can get all the information you are used to, fx the ISO-3166-1 two letter country code. public enum Country{ ANDORRA(new Locale("AD")), AFGHANISTAN(new Locale("AF")), ANTIGUA_AND_BARBUDA(new Locale("AG")), ANGUILLA(new Locale("AI")), //etc ZAMBIA(new Locale("ZM")), ZIMBABWE(new Locale("ZW")); private Locale locale; private Country(Locale locale){ this.locale = locale; } public Locale getLocale(){ return locale; } Pro: * *Light weight *Maps to Java Locales *Addressable by full country name *Enum values are not hardcoded, but generated by a call to Locale.getISOCountries(). That is: Simply recompile the project against the newest java version to get any changes made to the list of countries reflected in the enum. Con: * *Not in Maven repository *Most likely simpler / less expressive than the other solutions, which I don't know. *Created for my own needs / not as such maintained. - You should probably clone the repo. A: I found the IsoCountry list here, it has 2 and 3 char country codes A: To obtain the current device locale in Alpha-3 ISO (XXX) format: fun getCurrentCountryCode(): String? { val tm = context.getSystemService(AppCompatActivity.TELEPHONY_SERVICE) as TelephonyManager val countryCodeValue = tm.networkCountryIso val locale: Locale? = Locale.getAvailableLocales().firstOrNull { it.country.lowercase() == countryCodeValue.lowercase() } return locale?.isO3Country } To obtain the current device language locale (xx-XX) format: fun getCurrentLocale(): String? { return try { val locale = context.resources.configuration.locales[0] return "${locale.language}-${locale.country}" } catch (e: Exception) { e.printStackTrace() null } }
{ "language": "en", "url": "https://stackoverflow.com/questions/139867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "94" }
Q: How do I disable referential integrity in Postgres 8.2? Google results on this one are a bit thin, but suggest that it is not easily possible. My specific problem is that I need to renumber the IDs in two tables that are related to each other such that table B has an "table_a_id" column in it. I can't renumber table A first because then its children in B point to the old IDs. I can't renumber table B first because then they would point to the new IDs before they were created. Now repeat for three or four tables. I don't really want to have to fiddle around with individual relationships when I could just "start transaction; disable ref integrity; sort IDs out; re-enable ref integrity; commit transaction". Mysql and MSSQL both provide this functionality IIRC so I would be surprised if Postgres didn't. Thanks! A: I think you need to make a list of your foreign key constraints, drop them, do your changes, then add the constraints again. Check the documentation for alter table drop constraint and alter table add constraint. A: Here's a Python script that will delete all constraints in a transaction, run some queries, then recreate all those constraints. pg_get_constraintdef makes this super-easy: class no_constraints(object): def __init__(self, connection): self.connection = connection def __enter__(self): self.transaction = self.connection.begin() try: self._drop_constraints() except: self.transaction.rollback() raise def __exit__(self, exc_type, exc_value, traceback): if exc_type is not None: self.transaction.rollback() else: try: self._create_constraints() self.transaction.commit() except: self.transaction.rollback() raise def _drop_constraints(self): self._constraints = self._all_constraints() for schemaname, tablename, name, def_ in self._constraints: self.connection.execute('ALTER TABLE "%s.%s" DROP CONSTRAINT %s' % (schemaname, tablename, name)) def _create_constraints(self): for schemaname, tablename, name, def_ in self._constraints: self.connection.execute('ALTER TABLE "%s.%s" ADD CONSTRAINT %s %s' % (schamename, tablename, name, def_)) def _all_constraints(self): return self.connection.execute(""" SELECT n.nspname AS schemaname, c.relname, conname, pg_get_constraintdef(r.oid, false) as condef FROM pg_constraint r, pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace WHERE r.contype = 'f' and r.conrelid=c.oid """).fetchall() if __name__ == '__main__': # example usage from sqlalchemy import create_engine engine = create_engine('postgresql://user:pass@host/dbname', echo=True) conn = engine.connect() with no_contraints(conn): r = conn.execute("delete from table1") print "%d rows affected" % r.rowcount r = conn.execute("delete from table2") print "%d rows affected" % r.rowcount A: There are two things you can do (these are complementary, not alternatives): * *Create your foreign key constraints as DEFERRABLE. Then, call "SET CONSTRAINTS DEFERRED;", which will cause foreign key constraints not to be checked until the end of the transaction. Note that the default if you don't specify anything is NOT DEFERRABLE (annoyingly). *Call "ALTER TABLE mytable DISABLE TRIGGER ALL;", which prevents any triggers executing while you load data, then "ALTER TABLE mytable ENABLE TRIGGER ALL;" when you're done to re-enable them. A: I found these 2 excellent scripts which generate the sql for dropping the constraints and then recreating them. here they are: For dropping the constraints SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" DROP CONSTRAINT "'||conname||'";' FROM pg_constraint INNER JOIN pg_class ON conrelid=pg_class.oid INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END,contype,nspname,relname,conname For recreating them SELECT 'ALTER TABLE "'||nspname||'"."'||relname||'" ADD CONSTRAINT "'||conname||'" '|| pg_get_constraintdef(pg_constraint.oid)||';' FROM pg_constraint INNER JOIN pg_class ON conrelid=pg_class.oid INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END DESC,contype DESC,nspname DESC,relname DESC,conname DESC; Run these queries and the output will be the sql scripts that you need for dropping and creating the constraints. Once you drop the constraints you can do all you like with the tables. When you are done re-introduce them. A: It does not seem possible. Other suggestions almost always refer to dropping the constraints and recreating them after work is done. However, it seems you can make constraints DEFERRABLE, such that they are not checked until the end of a transaction. See PostgreSQL documentation for CREATE TABLE (search for 'deferrable', it's in the middle of the page). A: If the constraints are DEFERRABLE, this is really easy. Just use a transaction block and set your FK constraints to be deferred at the beginning of the transaction. From http://www.postgresql.org/docs/9.4/static/sql-set-constraints.html: SET CONSTRAINTS sets the behavior of constraint checking within the current transaction. IMMEDIATE constraints are checked at the end of each statement. DEFERRED constraints are not checked until transaction commit. So you could do: BEGIN; SET CONSTRAINTS table_1_parent_id_foreign, table_2_parent_id_foreign, -- etc DEFERRED; -- do all your renumbering COMMIT; Unfortunately, it seems Postgres defaults all constraints to NOT DEFERRABLE, unless DEFERRABLE is explicitly set. (I'm guessing this is for performance reasons, but I'm not certain.) As of Postgres 9.4, it isn't too hard to alter the constraints to make them deferrable if needed: ALTER TABLE table_1 ALTER CONSTRAINT table_1_parent_id_foreign DEFERRABLE; (See http://www.postgresql.org/docs/9.4/static/sql-altertable.html.) I think this approach would be preferable to dropping and recreating your constraints as some have described, or to disabling all (or all user) triggers until the end of the transaction, which requires superuser privileges, as noted in an earlier comment by @clapas. A: I think that an easear solution would be to create "temporary" columns associating where you want them to be. update the values with the foreign keys to the new columns drop the inicial columns rename to the new "temporary" columns to the same names then the inicial ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/139884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Multiple domains for one site: alias or redirect? I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with ServerAlias) or do I Redirect the request? Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used? Common vhost examples will have: ServerName example.net ServerAlias www.example.net Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site? UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load. UPDATE and ANSWER: Thanks Paul for finding the Google link which instructs us to "help your fellow webmasters by not perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&brand=riedell or www.example.com/skates.asp?brand=riedell&color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content." A: SSL certificates can also be an issue (wild card certs mitigate this but are more expensive). So if the cert is only bound to www.example.com, it won't validate for example.com. If this circumstance applies to your case, then carefully handling, redirects and hyperlink references in your html and javascript is very important. A: Redirecting is better, then there is always one, canonical domain for your content. I hear Google penalises multiple domains hosting the same content, but I can't find a source for that at the moment (edit, here's one article, but from 2005, which is ancient history in Internet years!) (not correct, see edit below) Here's some mod-rewrite rules to redirect to a canonical domain: RewriteCond %{HTTP_HOST} !^www\.foobar\.com [NC] RewriteCond %{HTTP_HOST} !^$ RewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent] That checks that the host isn't the canonical domain (www.foobar.com) and checks that a domain has actually been specified, before deciding to redirect the request to the canonical domain. Further Edit: Here's an article straight from the horses mouth - seems it's not as big an issue as you might think. Please read this article CAREFULLY as it distinguishes between duplicate content on the same site (as in "www.example.com/skates.asp?color=black&brand=riedell and www.example.com/skates.asp?brand=riedell&color=black") and specifically says "Don't create multiple pages, subdomains, or domains with substantially duplicate content." A: If they are entirely different domain names, you will want to redirect because otherwise cookies can not be shared between the two. If a user logs into your website at example1.com, they will need to log in again if they visit example2.com. If they are just different subdomains (example.com vs www.example.com) this won't matter. A: Server aliasing can cause problems with CGI session continuity: since cookies are attached to the domain they were served from, CGI scripts have to be carefully written so that they are aware of the aliasing, or all links within and into the site have to be relative, or both - it is much harder to avoid niggly little hard-to-debug problems due to the browser serving you different cookies based on whether the user last entered your site through name.tld or www.name.tld. A: Nowadays I doubt it matters. If you see both entries in google, then you know you're doing it wrong. A: If half the links to your site refer to one URL and half refer to another, each URL is only going to get half the pagerank. Even if Google doesn't penalize your rank for having duplicate content, you're going to suffer.
{ "language": "en", "url": "https://stackoverflow.com/questions/139889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server? This question is not so much programming related as it is deployment related. I find myself conversing a lot with the group in my company whose job it is to maintain our production Windows servers and deploy our code on them. For legal and compliance reasons, I do not have direct visibility or any control over the servers so the only way I can tell which version(s) of .NET are installed on any of them is through directions I give to that group. So far, all of the methods I can think of to tell which version(s) are installed (check for Administrative Tools matching 1.1 or 2.0, check for the entries in the "Add/Remove Programs" list, check for the existence of the directories under c:\Windows\Microsoft.NET) are flawed (I've seen at least one machine with 2.0 but no 2.0 entries under Administrative Tools - and that method tells you nothing about 3.0+, the "Add/Remove Programs" list can get out of sync with reality, and the existence of the directories doesn't necessarily mean anything). Given that I generally need to know these things are in place in advance (discovering that "oops, this one doesn't have all the versions and service packs you need" doesn't really work well with short maintenance windows) and I have to do the checking "by proxy" since I can't get on the servers directly, what's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server? Preferably some intrinsic way to do so using what the framework installs since it will be quicker and not need some sort of utility to be loaded and also a method which will definitely fail if the frameworks are not properly installed but still have files in place (i.e., there's a directory and gacutil.exe is inded there but that version of the framework is not really "installed") EDIT: In the absence of a good foolproof intrinsic way to do this built into the Framework(s), does anyone know of a good, lightweight, no-install-required program that can find this out? I can imagine someone could easily write one but if one already exists, that would be even better. A: http://www.asoft.be/prod_netver.html Use this "good, lightweight, no-install-required program" A: You should open up IE on the server for which you are looking for this info, and go to this site: http://www.hanselman.com/smallestdotnet/ That's all it takes. The site has a script that looks your browser's "UserAgent" and figures out what version (if any) of the .NET Framework you have (or don't have) installed, and displays it automatically (then calculates the total size if you chose to download the .NET Framework). A: The official Microsoft answer on how to do this is in KB article 318785. A: If the machine that you want to check has the .NET SDK installed, you can use a SDK command prompt and run the program CLRVer.exe. A: You can programmatically check the registry and a few other things as per this blog entry. The registry key to look at is [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\...] A: Found answer from here: Check which .NET Framework version is installed Open Command Prompt and copy paste one of the below command lines dir %WINDIR%\Microsoft.Net\Framework\v* or dir %WINDIR%\Microsoft.Net\Framework\v* /O:-N /B A: The Microsoft way is this: MSDN: How to determine Which .NET Framework Versions Are Installed (which directs you to the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\...) If you want foolproof that's another thing. I wouldn't worry about an xcopy of the framework folder. If someone did that I would consider the computer broken. The most foolproof way would be to write a small program that uses each version of .NET and the libraries that you care about and run them. For a no install method, PowerBasic is an excellent tool. It creates small no runtime required exe's. It could automate the checks described in the MS KB article above. A: As per CodeTrawler's answer, the solution is to enter the following into an explorer window: %systemroot%\Microsoft.NET\Framework Then search for: Mscorlib.dll ...and right-click / go to the version tab for each result. A: OneTouch deployment will do all the detection and installation of pre-requisites. It's probably best to go with a pre-made solution than trying to roll your own. Trying to roll your own may lead to problems because whatever thing you key on may change with a hotfix or service pack. Likely Microsoft has some heuristic for determining what version is running. A: The official way to detect .NET 3.0 is described here http://msdn.microsoft.com/en-us/library/aa480198.aspx Flawed, because it requires the caller to have registry access permissions. MSDN also mentions a technique for detecting .NET 3.5 by checking the User Agent string: http://msdn.microsoft.com/en-us/library/bb909885.aspx I think Microsoft should have done a better job than this. A: Also, see the Stack Overflow question How to detect what .NET Framework versions and service packs are installed? which also mentions: There is an official Microsoft answer to this question at the knowledge base article [How to determine which versions and service pack levels of the Microsoft .NET Framework are installed][2] Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1 How to determine which versions of the .NET Framework are installed and whether service packs have been applied. Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... Why would the official Microsoft answer be so misinformed? A: To determine your server's support for .NET Framework 4.5 and later versions (tested through 4.5.2): If you don't have Registry access on the server, but have app publish rights to that server, create an MVC 5 app with a trivial controller, like this: using System.Web.Mvc; namespace DotnetVersionTest.Controllers { public class DefaultController : Controller { public string Index() { return "simple .NET version test..."; } } } Then in your Web.config, walk through the desired .NET Framework versions in the following section, changing the targetFramework values as desired: <system.web> <customErrors mode="Off"/> <compilation debug="true" targetFramework="4.5.2"/> <httpRuntime targetFramework="4.5.2"/> </system.web> Publish each target to your server, then browse to <app deploy URL>/Default. If your server supports the target framework, then the simple string will display from your trivial Controller. If not, you'll receive an error like the following: So in this case, my target server doesn't yet support .NET Framework 4.5.2. A: To get the installed dotnet version, Create a Console app. Add this class Run that using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { public class GetDotNetVersion { public static void Get45PlusFromRegistry() { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey)) { if (ndpKey != null && ndpKey.GetValue("Release") != null) { Console.WriteLine(".NET Framework Version: " + CheckFor45PlusVersion((int)ndpKey.GetValue("Release"))); } else { Console.WriteLine(".NET Framework Version 4.5 or later is not detected."); } } } // Checking the version using >= will enable forward compatibility. private static string CheckFor45PlusVersion(int releaseKey) { if (releaseKey >= 394802) return "4.6.2 or later"; if (releaseKey >= 394254) { return "4.6.1"; } if (releaseKey >= 393295) { return "4.6"; } if ((releaseKey >= 379893)) { return "4.5.2"; } if ((releaseKey >= 378675)) { return "4.5.1"; } if ((releaseKey >= 378389)) { return "4.5"; } // This code should never execute. A non-null release key shoul // that 4.5 or later is installed. return "No 4.5 or later version detected"; } } // Calling the GetDotNetVersion.Get45PlusFromRegistry method produces // output like the following: // .NET Framework Version: 4.6.1 } A: It is probably a nasty way to find versions out, but I was always under the impression that all version got installed to <root>:\WINDOWS\Microsoft.NET\Framework. This provides folders with names such as v2.0.50727 which I believe give detailed version information. A: Well, like Dean said, you can look at the registry and do what he did. To check if he really has CLR .NET Framework installed, you should look for the MSCorEE.dll file in the %SystemRoot%\System32 directory. A: Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers. It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell. bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart) { DWORD dwHandle; DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle); if (dwLen) { LPBYTE lpData = new BYTE[dwLen]; if (lpData) { if (GetFileVersionInfo(filename,0,dwLen,lpData)) { UINT uLen; VS_FIXEDFILEINFO *lpBuffer; VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen); *majorPart = HIWORD(lpBuffer->dwFileVersionMS); *minorPart = LOWORD(lpBuffer->dwFileVersionMS); *buildPart = HIWORD(lpBuffer->dwFileVersionLS); *privatePart = LOWORD(lpBuffer->dwFileVersionLS); delete[] lpData; return true; } } } return false; } int _tmain(int argc,_TCHAR* argv[]) { _TCHAR filename[MAX_PATH]; _TCHAR frameworkroot[MAX_PATH]; if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH)) return 1; _tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*")); WIN32_FIND_DATA FindFileData; HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData); if (hFind == INVALID_HANDLE_VALUE) return 2; do { if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && _tcslen(FindFileData.cAlternateFileName) != 0) { _tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1); filename[_tcslen(frameworkroot)] = 0; _tcscat_s(filename,FindFileData.cFileName); _tcscat_s(filename,_T("\\mscorlib.dll")); WORD majorPart,minorPart,buildPart,privatePart; if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) { _tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart); } } } while (FindNextFile(hFind,&FindFileData) != 0); FindClose(hFind); return 0; } A: If you want to find versions prior to .NET 4.5, use code for a console application. Like this: using System; using System.Security.Permissions; using Microsoft.Win32; namespace findNetVersion { class Program { static void Main(string[] args) { using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\")) { foreach (string versionKeyName in ndpKey.GetSubKeyNames()) { if (versionKeyName.StartsWith("v")) { RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName); string name = (string)versionKey.GetValue("Version", ""); string sp = versionKey.GetValue("SP", "").ToString(); string install = versionKey.GetValue("Install", "").ToString(); if (install == "") //no install info, must be later version Console.WriteLine(versionKeyName + " " + name); else { if (sp != "" && install == "1") { Console.WriteLine(versionKeyName + " " + name + " SP" + sp); } } if (name != "") { continue; } foreach (string subKeyName in versionKey.GetSubKeyNames()) { RegistryKey subKey = versionKey.OpenSubKey(subKeyName); name = (string)subKey.GetValue("Version", ""); if (name != "") sp = subKey.GetValue("SP", "").ToString(); install = subKey.GetValue("Install", "").ToString(); if (install == "") //no install info, ust be later Console.WriteLine(versionKeyName + " " + name); else { if (sp != "" && install == "1") { Console.WriteLine(" " + subKeyName + " " + name + " SP" + sp); } else if (install == "1") { Console.WriteLine(" " + subKeyName + " " + name); } } } } } } } } } Otherwise you can find .NET 4.5 or later by querying like this: private static void Get45or451FromRegistry() { using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) { int releaseKey = (int)ndpKey.GetValue("Release"); { if (releaseKey == 378389) Console.WriteLine("The .NET Framework version 4.5 is installed"); if (releaseKey == 378758) Console.WriteLine("The .NET Framework version 4.5.1 is installed"); } } } Then the console result will tell you which versions are installed and available for use with your deployments. This code come in handy, too because you have them as saved solutions for anytime you want to check it in the future. A: I went into Windows Update & looked at the update history, knowing the server patching is kept up-to-date. I scanned down for .NET updates and it showed me exactly which versions had had updates, which allowed me to conclude which versions were installed. A: I found this one quite useful. here's the source
{ "language": "en", "url": "https://stackoverflow.com/questions/139891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "99" }
Q: Java Multicast Time To Live is always 0 I have a problem with setting the TTL on my Datagram packets. I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0 A: Basically you have to set an special system property telling the JVM to use an IPv4 stack: -Djava.net.preferIPv4Stack=true A: To implement pfranza's fix in Oracle, where you don't have a command line: Set the property java.net.preferIPv4Stack=true in each Oracle session as follows before calling the java code containing the multicast call with the following PL/SQL snippet: ret := dbms_java.set_property('java.net.preferIPv4Stack','true'); If the call is successful it will return NULL.
{ "language": "en", "url": "https://stackoverflow.com/questions/139909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to submit form with data before logging someone out? I'm using the document.form.submit() function for a rather large input form (hundreds of fields, it's an inventory application). I'm calling this after the user has been idle for a certain amount of time and I would like to save any data they've typed. When I try this the page reloads (the action is #) but any new text typed in the fields is not passed in the REQUEST, so I don't get to put it in the DB. Is there some fundamental reason why this happens or is my code just not playing nice together (I'm using the EXTJS grid view to show the form and a library for tracking idle time)? Thanks, Robert A: I guess I put the answer here. What I found was that doing this: setTimeout('frm.submit();', 2000); caused the page to reload but didn't submit the form. When I did this: frm.submit(); The form was submitted and the data was passed. I don't know why the first way didn't work, but I don't need to know that:) A: Might the server be voiding out the input values. Say if your page on the server looks like this: <form action="/page.cgi"> ... <input name="Fieldx" value=""/> </form> I think it'll void out the field. Or this the server action might be setting it indirectly. In JSF, something like this. <input name="Fieldx" value="#{bean.nullProperty}"/> What do you have on the server and what's your browser? A: I would try to catch the HTML post request to see if the input fields are included. If they are then your server has problem. But regarding what you said, I think it's because there's conflict in the way your browser handles JavaScript DOM. This may be the case if you leave out the submit button on your form and it works. A: The submit method of HTMLFormElement objects should just submit the form, as if the user had clicked the submit button. So, if the action attribute of the form is set to #, it would just seem to refresh the page, because it’s sending the form data to the same page. Strange that it still does it when you set the action attribute to another page though. Is the method attribute of the form set to get or post?
{ "language": "en", "url": "https://stackoverflow.com/questions/139921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular expression to match common SQL syntax? I was writing some Unit tests last week for a piece of code that generated some SQL statements. I was trying to figure out a regex to match SELECT, INSERT and UPDATE syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up. I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement. Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them. By the way it's C# RegEx that I'm after. Clarification I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project. A: Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying. A: As far as I know this is beyond regex and your getting close to the dark arts of BnF and compilers. http://savage.net.au/SQL/ Same things happens to people who want to do correct syntax highlighting. You start cramming things into regex and then you end up writing a compiler... A: I had the same problem - an approach that would work for all the more standard sql statements would be to spin up an in-memory Sqlite database and issue the query against it, if you get back a "table does not exist" error, then your query parsed properly. A: SQL is a type-2 grammar, it is too powerful to be described by regular expressions. It's the same as if you decided to generate C# code and then validate it without invoking a compiler. Database engine in general is too complex to be easily stubbed. That said, you may try ANTLR's SQL grammars. A: Off the top of my head: Couldn't you pass the generated SQL to a database and use EXPLAIN on them and catch any exceptions which would indicate poorly formed SQL? A: Have you tried the lazy selectors. Rather than match as much as possible, they match as little as possible which is probably what you need for quotes. A: To validate the queries, just run them with SET NOEXEC ON, that is how Entreprise Manager does it when you parse a query without executing it. Besides if you are using regex to validate sql queries, you can be almost certain that you will miss some corner cases, or that the query is not valid from other reasons, even if it's syntactically correct. A: I suggest creating a database with the same schema, possibly using an embedded sql engine, and passing the sql to that. A: I don't think that you even need to have the schema created to be able to validate the statement, because the system will not try to resolve object_name etc until it has successfully parsed the statement. With Oracle as an example, you would certainly get an error if you did: select * from non_existant_table; In this case, "ORA-00942: table or view does not exist". However if you execute: select * frm non_existant_table; Then you'll get a syntax error, "ORA-00923: FROM keyword not found where expected". It ought to be possible to classify errors into syntax parsing errors that indicate incorrect syntax and errors relating to tables name and permissions etc.. Add to that the problem of different RDBMSs and even different versions allowing different syntaxes and I think you really have to go to the db engine for this task. A: There are ANTLR grammars to parse SQL. It's really a better idea to use an in memory database or a very lightweight database such as sqlite. It seems wasteful to me to test whether the SQL is valid from a parsing standpoint, and much more useful to check the table and column names and the specifics of your query. A: The best way is to validate the parameters used to create the query, rather than the query itself. A function that receives the variables can check the length of the strings, valid numbers, valid emails or whatever. You can use regular expressions to do this validations. A: I am assuming you did something like .\* try instead [^"]* that will keep you from eating the whole line. It still will give false positives on cases where you have \ inside your strings. A: public bool IsValid(string sql) { string pattern = @"SELECT\s.*FROM\s.*WHERE\s.*"; Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase); return rgx.IsMatch(sql); }
{ "language": "en", "url": "https://stackoverflow.com/questions/139926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Is there a buffered version of CComBSTR that makes string concatenation more efficient? I have several projects where I need to append strings to a BSTR/CComBSTR/_bstr_t object (e.g. building a dynamic SQL statement). Is there an out-of-the-box type in the WinAPI to buffer the concatenation (like StringBuilder in .NET), or do I have to write my own? From what I know about the append methods, they perform re-allocation. A: You have to write your own. You can use the SysAllocStringLen, or SysReallocString APIs to get different-sized buffers. They work on an input string, but you can pass NULL to allocate a fixed-size, uninitialised buffer. A: Copy the BSTR into a CString, do all the modifications there and then copy it back into the BSTR/CComBSTR. CString's allocations are faster than SysAllocStringLen.
{ "language": "en", "url": "https://stackoverflow.com/questions/139927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Validation Controls and Javascript Confirm boxes I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed. How can this be accomplished? Ive included a sample of my current code below. sample.aspx <asp:textbox id=foo runat=server /> <asp:requiredfieldvalidator id=val runat=server controltovalidate=foo /> <asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') /> sample.aspx.vb Sub Page_Load() If Page.IsPostback() Then Page.Validate() If Page.IsValid Then 'process page here' End If End If End Sub Thanks for any help. A: This seems to be a very common problem. The workaround: Validate the page first, then call confirm, as shown here and here. This does have the drawback of calling the validation twice - once in your code, and once in the generated code in the submit onclick. How to make this work properly, i.e. Validate the page first (and only once), then show the confirm box, I do not yet know. Edit: Here's a useful suggestion: What ASP.NET does behind the scenes when validation controls exist, is add an autogenerated onClick event for each button. This OnClick event would supercede the custom OnClick event. So to overcome this I did the following: * *add CausesValidation = False *added Validate() and IsValid code to the onClick event behind the page to simulate the now missing autogenerated validation code behind the button. Edit 2: A complete example <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}" CausesValidation="false" /> A: Confirm box in code behind after validation check <asp:Button ID="btnSave" runat="server" OnClientClick="javascript:return ConfirmSubmit()" OnClick="btnSave_Click" Text="Save" /> //---javascript ----- function ConfirmSubmit() { Page_ClientValidate(); if(Page_IsValid) { return confirm('Are you sure?'); } return Page_IsValid; } A: can you not use the EnableClientScript property for the validator control allowing you to carry out the validation on the client side on your submit the validation will then fire?? A: The thing is that the Return Confirm fires prior to the validator's javascript. which all has to do with lifecycles and stuff. If you're wanting to definitely have that behavior, what you'll need to do is change all of your validators to custom validators, roll out your own JS validation routines for the custom validators, and then call the confirm at the end of the validation routine as the final call. if MAY change the sequence of firing, if you add the JS for the return confirm coding to the button in a HIJAX method where it's assigned to the onClick event after the page has been loaded fully into the browser--but I've never utilized that methodology for that capability, so don't quote me there. A: The Validators are fired by a onsubmit handler on the form. if your override form.onsubmit you'll lose the validator firing, though you may be able to manually provide the JS needed. A: What about using the ASP.NET Control Toolkit's ValidatorCallout control? From: http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ValidatorCallout/ValidatorCallout.aspx ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an input field and a validator control as you normally would. Then add the ValidatorCallout and set its TargetControlID property to reference the validator control. I haven't used this one, but it seems to me that it would get you the client side validation that you want. A: You should validate the page on the client itself. function validate() { Page_ClientValidate(); if (Page_IsValid) // do your processing here return Page_IsValid; } This method can be called on the "onClientClick" event of the button and in the code-behind, you can if the page is valid and do the processing if the client-side validation is successful. So, on the click event of the button, you can do - protected void SubmitButton_Click(object sender, EventArgs e) { if (!this.isValid) return; // do the processing here }
{ "language": "en", "url": "https://stackoverflow.com/questions/139948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Need some ASP.NET MVC Routing Help I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help. Basically, i have an URL like /products.aspx?categoryid=foo&productid=bar Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc. But i need to map it to /products/foo/bar. (without "category") Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :) P.S. Sorry for my bad English. A: (your English is just fine, no need to apologize!) You can define a route like this: routes.MapRoute("productsByCategory", "products/{category}/{productid}", new { controller="products", action="findByCategory" }) This will match products/foo/bar and call an action looking like this: public class ProductsController : Controller { ... public ActionResult FindByCategory(string category, string productid) { .... } } does this help? A: You also might consider making a Controller to test out your custom routes... Check out Stephen Walther's blog entry about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/139954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSBuild directory structure limit workarounds Does anyone have a method to overcome the 260 character limit of the MSBuild tool for building Visual Studio projects and solutions from the command line? I'm trying to get the build automated using CruiseControl (CruiseControl.NET isn't an option, so I'm trying to tie it into normal ant scripts) and I keep on running into problems with the length of the paths. To clarify, the problem is in the length of paths of projects referenced in the solution file, as the tool doesn't collapse paths down properly :( I've also tried using DevEnv which sometimes works and sometimes throws an exception, which isn't good for an automated build on a separate machine. So please don't suggest using this as a replacement. And to top it all, the project builds fine when using Visual Studio through the normal IDE. A: I solved similar issue by adjusting CSPROJ-file: <BaseIntermediateOutputPath>$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)\..\..\..\Intermediate\$(AssemblyName)_$(ProjectGuid)\'))</BaseIntermediateOutputPath> As the result during compilation CSC.EXE receives full path instead of relative one. Thanks to harrydev for clue on how CSC.EXE operates with the paths. A: There are two kinds of long path problems relevant to build. One is paths that aren't really too long, but have lots of "..\" in them. Typically, these are references' HintPath values. MSBuild should normalize these paths down to below the max limit, so that they work. The other kind of path is just plain too long. Sorry, but these just won't work. After looking at it a fair bit, the problem is that there just isn't sufficient API support for long paths. The BCL team (see their blog) had similar problems. Only some of the Win32 API's support the \?\ format. Arbitrary build tools, and probably 98% of apps out there, don't; and worse would probably behave badly (think of all the buffers sized for MAX_PATH). We came to the conclusion that until there's a big ecosystem effort to make long paths work, or Windows comes up with some ingenious way to make them work anyway (like the short paths mangling?) long paths just aren't possible for MSBuild to support. Workarounds include subst, as you found; but if your tree just is simply too deep, your only options are to build it in fragments, or to shorten the folder names. Sorry. Dan/MSBuild A: I found the problem to be that when the C# compiler (csc.exe) is called it uses the projects directory path PROJECTDIRECTORY together with the output path OUTPUTPATH by simply appending them as: PROJECTDIRECTORY+OUTPUTPATH However, if the OUTPUTPATH is relative i.e. "..\..\Build\ProjectName\AnyCPU_Debug_Bin\" and the project directory is pretty long then the total length is longer than 259 characters since the path will be: PROJECTPATH+"..\..\Build\ProjectName\AnyCPU_Debug_Bin\" instead of an absolute path. If csc.exe would make an absolute path before calling Win32 functions this would work. Since in our case the absolute path length is less than 160 characters. For some reason the call to csc.exe from visual studio is then different from MSBuild than it is from visual studio. Do not know why. In any case, the problem can be resolved by changing either or both PROJECTDIRECTORY and/or OUTPUTPATH paths. A: It seems that it is limitation of the MSBuild. We had the same problem, and in the end, we had to get paths shortened, because did not find any other solution that worked properly. A: The SUBST command stills seems to exist so remapping the root of your build folder to a drive letter may save some characters if Judah Himango's solution is no good. A: Have you tried DOS paths? Or the \\?\ prefix? The .NET BCL team blog has more info. A: If the path length is 260, then there is warning resolving reference, for 259 or 261 of this error does not occur. I think there is msbuild bug. A: I know there is already an accepted answer, but I had a different problem while using msbuild that gave me the same error output, and led me on a circular wild-goose chase. So, for future googlers, here goes: We have a batch file that calls msbuild, but as the build machine can build for multiple versions of Visual Studio, each batch file calls vcvarsall.bat before it runs msbuild. This has the nasty side effect of stuffing the path completely full of the same thing over and over again. When it fills up, you get the error shown in the question above: The input line is too long. A simple Google search could make you think your paths are suddenly too long for msbuild. In my case, it was as simple as killing the session of cmd.exe and restarting, as this reverted the environment variables to their native state.
{ "language": "en", "url": "https://stackoverflow.com/questions/139964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: SqlParameter Size - negative effects of setting to max size? I have a SqlCommand that I want to call Prepare() on whose CommandType = Text (it cannot be a stored procedure). In order to do this, I need to set the Size attribute on the parameters to be non-zero otherwise an exception is thrown. Are there any negative effects from setting the Size on all parameters to the maximum possible size even if the size of the actual values will never come close to that? Is there a better way to do this? A: I think the only potential negative side effect of doing something like that would be the cost of memory allocation for the parameters. Since you're calling 'Prepare()' I'm guessing you're planning to use the SqlCommand multiple times against the same SqlConnection which suggests a discrete section of code where it's likely to be used (if the connection closes for a prepared command, the command text will have to be re-transmitted to the server on the next usage). If you know the nature of your parameters, it seems like you might have some idea about their potential sizes. If not, then I don't see what alternative you have, really, than to declare a significantly large size for each - large enough to hold most/any potential values. A: This is the way the framework does it if you use the SqlParameter constructor that just takes a parameter name and a value. There might be a slight inefficiency on the client side, but I have never noticed a difference in query performance. A: Given that you are using CommandType = Text, you should be able to set the size programmatically to the actual size of the parameter you are sending. You should only see poorer performance when the size of your data approaches the max size of the data types your are sending. If your parameters are always large relative to the size of the command text, from a network traffic perspective, you'll only see minimal gains in performance by switching to stored procs. A: Please post a sample of your code. You shouldn't need to set the Size attributes on your parameters in order to call .Prepare(). Incidentally, you probably don't really need to call .Prepare(), especially if you're calling .Execute() immediately after.
{ "language": "en", "url": "https://stackoverflow.com/questions/139971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Committing a Directory to Subversion Kind of a newbie question, but I am having problems using SNVKit. I am using SVNKit in an application to commit changes to files. I have it successfully adding the files and folders to the working copy, but I am having problems committing it to the respository. The command I am trying to run is 'commit -m "Test Add" /svnroot/project1/' but I keep getting "svn: '/home/user' is not a working copy" I have a structure similar to this: * */svnroot/ */svnroot/project1/ */svnroot/project1/grouping1/ */svnroot/project1/grouping1/myfilesarehere If I try to commit the file, I get the following message: "'/svnroot/project1/grouping1' is not under version control and is not part of the commit, yet its child is part of the commit." What might I be doing wrong? EDIT: Fixed the directories. A: If you have both a directory and its child added, but neither is not committed, I believe you get this message if you try to commit just the child. You need to commit the parent directory first. A: I got this message and I noticed that I was doing a commit while I was in the sub-directory. When I switched to the root of the tree, it commited w/o issue. A: move your -m "comment" to the end. I would just change directory into your project directory. Then you just type svn commit -m "comment" and svn does the rest. A: I think the problem is that you are committing changes to the actual SVN repository itself instead of doing an import, checking out a copy for yourself, making changes, and then doing a commit from your checked-out working copy after adding any subdirectories. So: import, checkout, make changes, and then finally do an add for each new file or directory and commit -m "message" form the top level. More information in the free online SVN "turtle" book. A: It's not entirely clear because you've inconsistently replaced them, but it looks like you're getting repository paths/URLs confused with working copy paths. If you're adding or committing files, always use the working copy paths. Try playing around with the command-line svn before trying to use SVNKit. A: If you want to commit an entire new directory consider using svn import instead. As it stands right now you may have to revert or some other action clean up the current mess. A: I have it tracked down to a possible bug somewhere. If I don't add a message it works. Time for more digging. Thanks for the pointers. A: Some times, using some Softwares such as eclipse or Versions.app produces this errors. In this case, quit the SVN client and do it on command line. A: You have probably done some refactoring and you are trying to commit 'some.package.YourClass.java', in that case try commiting the directory(package) 'some'. If you want to save yourself from such headache in the future consider switching to GIT instead of svn. Remember svn keeps your changes in a .svn file and tries to puch it to the repository. When you commit it will according to this .svn file push 'your changes'. But what if yo're changes are very complex? svn can't handle it. GIT on the other hand: you retrieve all updates so your project is up-to-date. And when committing it just overwrites the repo, since it knows yours is most recent and no hustle.
{ "language": "en", "url": "https://stackoverflow.com/questions/139972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Do generic interfaces in C# prevent boxing? (.NET vs Mono performance) I have a C# interface with certain method parameters declared as object types. However, the actual type passed around can differ depending on the class implementing the interface: public interface IMyInterface { void MyMethod(object arg); } public class MyClass1 : IMyInterface { public void MyMethod(object arg) { MyObject obj = (MyObject) arg; // do something with obj... } } public class MyClass2 : IMyInterface { public void MyMethod(object arg) { byte[] obj = (byte[]) arg; // do something with obj... } } The problem with MyClass2 is that the conversion of byte[] to and from object is boxing and unboxing, which are computationally expensive operations affecting performance. Would solving this problem with a generic interface avoid boxing/unboxing? public interface IMyInterface<T> { void MyMethod(T arg); } public class MyClass1 : IMyInterface<MyObject> { public void MyMethod(MyObject arg) { // typecast no longer necessary //MyObject obj = (MyObject) arg; // do something with arg... } } public class MyClass2 : IMyInterface<byte[]> { public void MyMethod(byte[] arg) { // typecast no longer necessary //byte[] obj = (byte[]) arg; // do something with arg... } } How is this implemented in .NET vs Mono? Will there be any performance implications on either platform? Thank you! A: I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type. This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient. A: Yes, in .Net (MS not sure about mono) generics are implemented at compile time so there is no boxing or unboxing going on at all. Contrast to java generics which are syntactic sugar that just perform the casts for you in the background (at least it was this way once). The main problem with generics is you can't treat generic containers polymorphically, but that is a bit off your topic :-) A: You will get the same benefits in Mono that you do in .NET. We strongly recommend that you use Mono 1.9 or Mono 2.0 RCx in general, as generics support only matured with 1.9. A: The problem with MyClass2 is that the conversion of byte[] to and from object is boxing and unboxing, which are computationally expensive operations affecting performance. There is no boxing involved with array types, even one with value type elements. An array is a reference type. The overhead on (byte[]) arg is minimal at best. A: I can't speak to Mono, but using a generic interface should solve the boxing/unboxing issue in the MS runtime. A: Given you're using a recent version of mono, 2.0 if you can. Generic interface performance on Mono is very good, on pair with regular interface dispatch. Dispatch of generic virtual methods[1] is terrible on all released versions of mono, it has improved in 1.9 thou. The problem is not that bad as the performance issue with generic virtual methods has been fixed for the next release of mono (2.2), which is scheduled to the end of this year. [1] A generic virtual method is something like: public interface Foo { void Bla<T> (T a, T b); }
{ "language": "en", "url": "https://stackoverflow.com/questions/139979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Advice for someone who wants to start in Business Intelligence? What advice would you have for someone who wants to start in the BI (Business Intelligence) domain? I where and what I should start with: Books, Blogs, WebCasts... What I should pay attention to and what I should stay away from. Are the Microsoft technologies worth while ? A: I found the "project real" from microsoft really helpful while getting into the bi-world. Its a real world bi project, supported by microsoft, to develop and show best practices regarding to all the areas of bi like etl, data warehouse design, cube design, etc. A: Business Objects http://www.businessobjects.com/ are quite a big player in this area and familiarity with their products will also help you break into B.I. roles. For practise data, I would recommend something like the anonomised search records from aol that came out a couple of years back - http://www.techcrunch.com/2006/08/06/aol-proudly-releases-massive-amounts-of-user-search-data/ This is real world size and is an interesting database with some published search sets. A: The MS technology stack is quite good and is by far the most accessible (try to get hold of a copy of Cognos Reportnet for self-learning). Where you will run into trouble (and this is the main barrier to entry for gaining a B.I. skillset) is to actually get experience working with real data. It's quite hard to come up with a realistic toy scenario for this sort of thing. This means that you have to overcome the chicken-and-egg problem that this poses. One option would be to try to get a job as a B.I. developer somewhere like a government department or other place that has trouble recruiting due to salary constraints. Clear evidence of technical skills and a demonstrated interest in the business might get your foot in the door. This will be a bit harder in a recession. However there is still an ongoing skill shortage of good B.I. people. The reason is (IMO) not the lack of technical skills (the technology isn't rocket science). Instead, I think it is the aforementioned chicken-and-egg problem and the fact that the B.I. domain involves customer intimacy to do it well. It lends itself to working in an analyst/programmer mode with direct customer contact (one of the reasons I do this type of work). If you like working in this mode it might be a good line for you to get into. Edit: Someone who's just had a job offer in this space asked whether he should take the job. A: I would stress you to read this book; might seem kind of outdated but the same theory still applies today. It is probably the best starter for general BI. The Data Warehouse Toolkit - Ralph Kimball Regarding Microsoft's BI it is a medium-sized tool that can do the job in your first steps (I have more experience with Cognos though). Haven't used MS tools since 2005 so I can't tell much about it. In case you happen to be interested in Cognos, I have a few videos which can be of help: Cognos Tutorials Good luck with your project. A: Get the Kimball Books (specially this one http://www.amazon.com/The-Data-Warehouse-Toolkit-Dimensional/dp/0471200247) and for starters you may want to start with the MS BI Framework The Microsoft Data Warehouse Toolkit and the SQL Server Enterprise (MS BI Bundle with the database, ETL and reporting), it's easy a readily available, specially if you are a student with the MSDNAA, you can get the enterprise version for free!!! A: For general business intelligence, I found the Kimball Group as a great source for best practices. If you would like to start building your own project, check out GoodData Platform. We have full BI stack Platform as a Service and you can start for free (evaluation period) with access to all resources and learn from Tutorials on our Developer Portal. A: I would say try to find a few classes. Microsoft technologies are worth the time. There are many large companies running on the .Net framework. A: We use this to get a feel of Microstrategy: http://www.teradatauniversitynetwork.com/apply-and-do
{ "language": "en", "url": "https://stackoverflow.com/questions/139988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How do I make my colleagues not despise SVN? Many of my colleagues use SVN in groups of 1-5 people partly working on the specific project. Half of them are inexperienced students. In fact non of us are real software developers with year-long experience. Most of them use Eclipse and subclipse to read and write their contributions to the SVN repositories. Some of them have problems with the difference of: * *checking out (confused with update and merge) *commiting (confused with update) *updating (confused with commit and check out) *merging (is the hardest. Whats a merge? Do i have to merge my code "into the SVN"?) They fear that the SVN might kill their work (they don't call it working branch) if they press the wrong button. They are committing their eclipse .project files to the repository, after adding some arbitrary library dependencies to their java projects. The other colleagues get compilation errors from these comitts and find it hard to resolve these. In general they say: I'd like to work without SVN, I don't like it. It's too complex. Is there a e-learning project like "SVN for kids"? How can I make them like version control? A: A simple "cheatsheet" on the needed procedures, given step-by-step, is the best way. SVN does have some pitfalls that aren't obvious. I've been involved with new people using it, and on occasions they do blow away whole chunks of code from the current revision, etc. Of course, you can always go back and get from previous versions, but SVN is scary and hazardous to new people. Keep that in mind and write very simple but explicit instructions for the needed operations! A: "How can I make them like version control?" Delete their working copies and they'll quickly grasp how useful version control software can be! Seriously, using VCS is something that goes hand-in-hand with being a mature developer. If you don't know why you'd want Subversion, I wouldn't trust them as developers. They may have skill programming, but programming is only a part of the job of being a developer. I do believe that until you've lost code, you'll truly never appreciate VCS. A: * *unlimited undo - no need to worry about lost changes *backup, not your responsibility any more *'time machine' functionality - what did the code look like on last Friday evening? *collaboration *central, "official" version of the source code makes easy to build releases *comparison: someone dared to touch your code, what did he change exactly? *tagging: tag stable versions which are ready for demonstrations, you can keep developing in the code base after The 'merging' only needed when two developers modify the same line in the same source files. It doesn't occur very often in small teams and it takes a couple of minutes to fix. All other changes merged automatically by the version control system. A: If they are mostly students, one selling point is that out here in the "real world" many people take versioning very seriously. If they are afraid of deleting something, demonstrate deleting some crucial file and demonstrate the ability to restore deleted files. Or they might like a different kind of version control all-together suchas git or mercurial. A: In my experience, one of the main reasons why so many people are "afraid" of, or don't like, version control is because they don't understand the underlying concepts and how the system works. This is, unfortunately, also true for many experienced developers. I know people who have used CVS and Subversion for years, but they never create branches or tags, because they don't understand how they work, and therefore see them as "complicated" or "unnecessary". I think it's essential that your co-workers gain a basic understanding of the purpose of version control, the reasons for using it, and the workflow involved in doing so. Personally, I think the first two chapters of the Subversion book provide the best explanation of the involved concepts and the theory behind version control systems in general, so I recommend your co-workers to read those. I do not recommend using an IDE integration to learn using version control. Integrations and plug-ins often hide the "details" of the system from the user, which can be very confusing, especially if you don't know what things looke like "under the hood". I prefer tools like TortoiseSVN, where you perform most operations directly, and manually, without any "magic" behind the scenes. For example, a very common misconception is not understanding the difference between your working copy and the repository on the server. I have often seen that switching to a tool where you operate directly on the file system will help with this situation, because the user is forced to activeley think about what he is doing, and why. As with pretty much everything else in life, using version control is also done best by personal experience—trying and failing, and trying again. This is why I recommend creating sandbox home folders for everyone. Allow them to experiment with the various functions in the system without the fear of destroying anything in the project or losing data. A: First, you need to take a "software-independent" approach at looking at this problem. Don't force them to read the Red Bean book, or try telling them about all the nifty SVN commands. Instead, you should start by trying to teach the proper workflow with version control. In a nutshell, that means: * *Update your view *Make some changes *Test your code *Update again *Solve merge conflicts, if necessary *Commit Note here that I'm excluding the initial check-out process, as you should be there to help them check out their initial view. The above steps is only what SCM-enabled developers should do every day (btw, you should also really emphasize that, or else people that have a fear of merge conflicts will only get worse over time). The key to successful SCM adoption is twofold; first you need to get people used to working with the software doing normal, non-painful things (ie, update/commit). If you don't do this, then the developers will tend to avoid using SCM until you bother them about it and ask why they haven't committed any code in two weeks. Second, you need to teach people how to overcome the common painful scenarios which might cause them to loose their work. It is indeed possible for an SCM system to destroy work, and it usually happens before anything gets committed to the repository with merge conflicts. You should simulate merge conflicts, walk them through resolving them, and then have them do the same on their own. You should explain: * *What the meaning of the .r1, .r2, .mine, and the original file will contain after a conflict *Show how to graphically resolve the conflicts *Now re-compile and test the software again just to make sure *Make a backup of the .mine file, again, just to make sure *Then commit There are many more complex things within SCM, and this should only be explained much later after the basics are well understood. Don't even bother mentioning merging or tagging or anything like that until they have a few weeks of everyday experience under their belts. Otherwise, the complexity and additional risk will make this new tool seem even more "useless" to them. Again, the key here is to emphasize the daily SCM workflow, in a software-neutral manner, and slowly explain the quirks of the particular SCM system as they come up. Merging is the only complicated thing that needs to be explained at first, as it is likely the only painful thing encountered on a daily basis. Everything else should be explained as it comes up. A: Give them a brief talk on svn. tell them what the benifits are and how to use it. I managed to pick up SVN in my first job out of University with not trouble what so ever, though I was using it at a file system level using tortoise SVN. I'm not that smart so if I can pick it up anyone can. A: Run through some scenarios with them on why version control is good. Even better, put them through some toy projects where time pressure makes them commit frequently. In some allow them only to share code through svn, and in others to share it only through shared directories. After that they'll know what it's about. A: You can't really make anyone like it. But if you just start using it yourself and set a good example, the benefits will become apparent. You need to update the server constantly and make sure the server is backed up. That way when there is a crazy bug in the system you will have the logs to show the change that caused the bug. You know what you need to do. Don't let the ignorance of others stop you. A: Version control greatest problem is the conflict resolution. If you really want to play safe, try this workflow: * *Every developer create a branch from the main trunk before starting to code; *A developer implements a feature in his own branch and commit (no need to update, since he is the sole developer in his branch); *A couple of more experienced developers review the code, test and merge the branch revisions to the main trunk; *rinse and repeat Subversion 1.5 new features are really great for this kind of workflow. A: Try this. I found it on an 'SVN for dummies' search and it was described as a 'SVN for Dummies, a guide your grandma can understand' :D A: Here is a decent SVN "cheatsheet" that describes basic usage: http://abbeyworkshop.com/howto/misc/svn01/ A: K make your friends read this. Next learning the cli first on a few pet projects clarifies this greatly. My first go at subclipse about made me hate eclipse. Partially because I had never used subversion before. * *checking out = get a local copy of the code that is in the repository. *Update = makes sure your local copy is up to date with the master copy. aka the server. *commit = add your changes to the master copy *merge = you plus someone else has committed since you checked out. merging allows for you to keep BOTH sets of changes via a little supervised editing. Merging is a neat feature but a bit complex at first go. A: I would suggest them reading at least the basic parts of http://svnbook.red-bean.com/en/1.5/index.html, it is well written with some humor thrown in. It covers using the command line tools, but the concepts are the same no matter what interface you are using (i.e. TortoiseSVN or Subclipse) A: SVN keeps track of all changes since the project start, so there's practically no way to throw away your work just by hitting the "wrong" button. I really think that all significant work should be under version control, even if there's no team (I code alone and I use it). I never really saw the point until I read this little book, try to make them read at least the first 20 pages. There's a good analogy there between subversion and the "undo" button of any editor, that may convince them of using it (it worked with me :) ) A: Send them to: * *http://svnbook.red-bean.com/ *http://www.ericsink.com/scm/source_control.html Impress upon them that they will be denigrated as complete and utter fools by anyone who uses a half decent source control system (i.e. not VSS). A: You need to really sell them on the concepts of version control first so that they understand how svn works. A few things to try are * *Create a sandbox repository for training and experimentation *Try to organise some training sessions/ workshops. If you're not confident in running that your self, try chatting to your local Linux User Group to see if they know someone who can help. *Document your development process including the common subversion usage scenarios. Its also worth pointing out to the students that experience with source control will be a plus for their CVs. On your specific issue of committing .project files you can either set the svn:ignore property on a property or you can set the global-ignores value in each users subversion config file. A: You might want to create aliases for the most dangerous commands (I'm thinking mostly of revert) that would require explicit confirmation before calling the svn command. Also, if they're using Eclipse, they can set up their editor so that it will keep N work copies of the current code. I've saved myself from a couple of stupid version control mistakes with that feature. A: They can always try "the poor man's CVS": have them do a ZIP of their code a moment before they check in/out anything, and store them numbered somewhere in their hard drives. In the end, they'll have a bunch of files like: * *MyProject01.zip *MyProject02.zip *(etc) This shall give them the piece of mind that their "work" will not get "destroyed" in case they do something stupid, and will be cumbersome enough to force them to learn how to use SVN properly (come on, it's not that difficult!). I've personally found this poor man's approach to be far superior to Visual SourceSafe: at a former employer's I was forced to use that monstrosity... after the second time the repository completely broke down, they thanked me for this :D A: If you are developing in windows machines, try to use TortoiseSVN as your subversion client. The interface is really great. I will help them to loose the version control fear. A: Its all about confidence in using something new, and understanding what it is that they're using. Once you've used it, are happy it works, the 'disagreement' disappears. Try a training overview first - here's a project that provides some powerpoint slides to help. Give them the svn book and links to TortoiseSVN to read up on it once they have the overview. Then try a hand-on workshop with a sandbox repo. Then be available to assist for a week or so while they use it for real. this approach works for everything, not just SVN.
{ "language": "en", "url": "https://stackoverflow.com/questions/139989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: prototyping functions in SML I have two functions, f and g, which call each other recursively. Unfortunately, when f calls g, it has not yet been declared, so I get an "unbound variable" error. How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ? A: Use and: fun f x = ... and g x = ... More info here. A: Mutual Recursion. Use and instead of fun between the two functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/139991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to best serialize a java.awt.Image? I have a Serializable object which is supposed to hold a java.awt.Image as its member. How should I go about serializing it? (Edited from a not so clear first version, sorry.) A: javax.swing.ImageIcon, as a part of Swing, does not guarantee to have compatible serialised form between versions. However, you can cheat and look at its readObject and writeObject code - find width and height, grab the pixels with PixelGrabber. I'm not entirely sure that covers the colour model correctly. The obvious alternative is to write a real image format with javax.imageio. A: ImageIcon implements Serializable and it can be used to wrap an Image class http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/ImageIcon.html A: None that I know of. I believe you need to write your own serializer for it to basically save out the width, height and pixel values... Or write it out to the stream as a PNG or something
{ "language": "en", "url": "https://stackoverflow.com/questions/139996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do I change the Status labels in Bugzilla I don't want to change how the Status field works I just want to change the labels to the states that the old system uses. (the old systems consists of spreadsheets and paper :P We are using 3.0 * UNCONFIRMED --> PRELIMARY * NEW --> DESIGN REVIEW * ASSIGNED --> STR1 * RESOLVED --> STR2 * REOPEN * VERIIFED --> BMR * CLOSED --> TCG A: If you log into the bugzilla system as an administrator you'll see on the bottom a link that says "Field Values", click that, on the next page you'll see "Resolution", go there then click on the resolution you'd like to change, A: I think this can be done by modifying the templates look here: http://www.bugzilla.org/docs/2.22/html/cust-templates.html specifically: global/variables.none.tmpl
{ "language": "en", "url": "https://stackoverflow.com/questions/140000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: VBScript: How to utiliize a dictionary object returned from a function? I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary. Here is the relevant part of my function: Function GetSomeStuff() ' ' Get a recordset... ' Dim stuff Set stuff = CreateObject("Scripting.Dictionary") rs.MoveFirst Do Until rs.EOF stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value rs.MoveNext Loop GetSomeStuff = stuff End Function How do I call this function and use the returned dictionary? EDIT: I've tried this: Dim someStuff someStuff = GetSomeStuff and Dim someStuff Set someStuff = GetSomeStuff When I try to access someStuff, I get an error: Microsoft VBScript runtime error: Object required: 'GetSomeStuff' EDIT 2: Trying this in the function: Set GetSomeStuff = stuff Results in this error: Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment. A: Have you tried doing set GetSomeStuff = stuff in the last line of the function? A: I wasn't too sure of what was your problem, so I experimented a bit. It appears that you just missed that to assign a reference to an object, you have to use set, even for a return value: Function GetSomeStuff Dim stuff Set stuff = CreateObject("Scripting.Dictionary") stuff.Add "A", "Anaconda" stuff.Add "B", "Boa" stuff.Add "C", "Cobra" Set GetSomeStuff = stuff End Function Set d = GetSomeStuff Wscript.Echo d.Item("A") Wscript.Echo d.Exists("B") items = d.Items For i = 0 To UBound(items) Wscript.Echo items(i) Next A: Have you tried: Dim returnedStuff Set returnedStuff = GetSomeStuff() Then "For Each" iterating over the dictionary? There's an example of using the Dictionary (albeit for VB6, the gist of it is the same though!) here.
{ "language": "en", "url": "https://stackoverflow.com/questions/140002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Checking ftp return codes from Unix script I am currently creating an overnight job that calls a Unix script which in turn creates and transfers a file using ftp. I would like to check all possible return codes. The man page for ftp doesn't list return codes. Does anyone know where to find a list? Anyone with experience with this? We have other scripts that grep for certain return strings in the log, and they send an email when in error. However, they often miss unanticipated codes. I am then putting the reason into the log and the email. A: The ftp command does not return anything other than zero on most implementations that I've come across. It's much better to process the three digit codes in the log - and if you're sending a binary file, you can check that bytes sent was correct. The three digit codes are called 'series codes' and a list can be found here A: I wrote a script to transfer only one file at a time and in that script use grep to check for the 226 Transfer complete message. If it finds it, grep returns 0. ftp -niv < "$2"_ftp.tmp | grep "^226 " A: Install the ncftp package. It comes with ncftpget and ncftpput which will each attempt to upload/download a single file, and return with a descriptive error code if there is a problem. See the “Diagnostics” section of the man page. A: I think it is easier to run the ftp and check the exit code of ftp if something gone wrong. I did this like the example below: # ... ftp -i -n $HOST 2>&1 1> $FTPLOG << EOF quote USER $USER quote PASS $PASSWD cd $RFOLDER binary put $FOLDER/$FILE.sql.Z $FILE.sql.Z bye EOF # Check the ftp util exit code (0 is ok, every else means an error occurred!) EXITFTP=$? if test $EXITFTP -ne 0; then echo "$D ERROR FTP" >> $LOG; exit 3; fi if (grep "^Not connected." $FTPLOG); then echo "$D ERROR FTP CONNECT" >> $LOG; fi if (grep "No such file" $FTPLOG); then echo "$D ERROR FTP NO SUCH FILE" >> $LOG; fi if (grep "access denied" $FTPLOG ); then echo "$D ERROR FTP ACCESS DENIED" >> $LOG; fi if (grep "^Please login" $FTPLOG ); then echo "$D ERROR FTP LOGIN" >> $LOG; fi Edit: To catch errors I grep the output of the ftp command. But it's truly it's not the best solution. I don't know how familier you are with a Scriptlanguage like Perl, Python or Ruby. They all have a FTP module which you can be used. This enables you to check for errors after each command. Here is a example in Perl: #!/usr/bin/perl -w use Net::FTP; $ftp = Net::FTP->new("example.net") or die "Cannot connect to example.net: $@"; $ftp->login("username", "password") or die "Cannot login ", $ftp->message; $ftp->cwd("/pub") or die "Cannot change working directory ", $ftp->message; $ftp->binary; $ftp->put("foo.bar") or die "Failed to upload ", $ftp->message; $ftp->quit; For this logic to work user need to redirect STDERR as well from ftp command as below ftp -i -n $HOST >$FTPLOG 2>&1 << EOF Below command will always assign 0 (success) as because ftp command wont return success or failure. So user should not depend on it EXITFTP=$? A: lame answer I know, but how about getting the ftp sources and see for yourself A: I like the solution from Anurag, for the bytes transfered problem I have extended the command with grep -v "bytes" ie grep "^530" ftp_out2.txt | grep -v "byte" -instead of 530 you can use all the error codes as Anurag did. A: Here is what I finally went with. Thanks for all the help. All the answers help lead me in the right direction. It may be a little overkill, checking both the result and the log, but it should cover all of the bases. echo "open ftp_ip pwd binary lcd /out cd /in mput datafile.csv quit"|ftp -iv > ftpreturn.log ftpresult=$? bytesindatafile=`wc -c datafile.csv | cut -d " " -f 1` bytestransferred=`grep -e '^[0-9]* bytes sent' ftpreturn.log | cut -d " " -f 1` ftptransfercomplete=`grep -e '226 ' ftpreturn.log | cut -d " " -f 1` echo "-- FTP result code: $ftpresult" >> ftpreturn.log echo "-- bytes in datafile: $bytesindatafile bytes" >> ftpreturn.log echo "-- bytes transferred: $bytestransferred bytes sent" >> ftpreturn.log if [ "$ftpresult" != "0" ] || [ "$bytestransferred" != "$bytesindatafile" ] || ["$ftptransfercomplete" != "226" ] then echo "-- *abend* FTP Error occurred" >> ftpreturn.log mailx -s 'FTP error' `cat email.lst` < ftpreturn.log else echo "-- file sent via ftp successfully" >> ftpreturn.log fi A: You said you wanted to FTP the file there, but you didn't say whether or not regular BSD FTP client was the only way you wanted to get it there. BSD FTP doesn't give you a return code for error conditions necessitating all that parsing, but there are a whole series of other Unix programs that can be used to transfer files by FTP if you or your administrator will install them. I will give you some examples of ways to transfer a file by FTP while still catching all error conditions with little amounts of code. FTPUSER is your ftp user login name FTPPASS is your ftp password FILE is the local file you want to upload without any path info (eg file1.txt, not /whatever/file1.txt or whatever/file1.txt FTPHOST is the remote machine you want to FTP to REMOTEDIR is an ABSOLUTE PATH to the location on the remote machine you want to upload to Here are the examples: curl --user $FTPUSER:$FTPPASS -T $FILE ftp://$FTPHOST/%2f$REMOTEDIR ftp-upload --host $FTPHOST --user $FTPUSER --password $FTPPASS --as $REMOTEDIR/$FILE $FILE tnftp -u ftp://$FTPUSER:$FTPPASS@$FTPHOST/%2f$REMOTEDIR/$FILE $FILE wput $FILE ftp://$FTPUSER:$FTPPASS@$FTPHOST/%2f$REMOTEDIR/$FILE All of these programs will return a nonzero exit code if anything at all goes wrong, along with text that indicates what failed. You can test for this and then do whatever you want with the output, log it, email it, etc as you wished. Please note the following however: * *"%2f" is used in URLs to indicate that the following path is an absolute path on the remote machine. However, if your FTP server chroots you, you won't be able to bypass this. *for the commands above that use an actual URL (ftp://etc) to the server with the user and password embedded in it, the username and password MUST be URL-encoded if it contains special characters. *In some cases you can be flexible with the remote directory being absolute and local file being just the plain filename once you are familiar with the syntax of each program. You might just have to add a local directory environment variable or just hardcode everything. *IF you really, absolutely MUST use regular FTP client, one way you can test for failure is by, inside your script, including first a command that PUTs the file, followed by another that does a GET of the same file returning it under a different name. After FTP exits, simply test for the existence of the downloaded file in your shell script, or even checksum it against the original to make sure it transferred correctly. Yeah that stinks, but in my opinion it is better to have code that is easy to read than do tons of parsing for every possible error condition. BSD FTP is just not all that great. A: Why not just store all output from the command to a log file, then check the return code from the command and, if it's not 0, send the log file in the email?
{ "language": "en", "url": "https://stackoverflow.com/questions/140012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Writing a Domain Specific Language for selecting rows from a table I'm writing a server that I expect to be run by many different people, not all of whom I will have direct contact with. The servers will communicate with each other in a cluster. Part of the server's functionality involves selecting a small subset of rows from a potentially very large table. The exact choice of what rows are selected will need some tuning, and it's important that it's possible for the person running the cluster (eg, myself) to update the selection criteria without getting each and every server administrator to deploy a new version of the server. Simply writing the function in Python isn't really an option, since nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime. What I need are suggestions on the simplest way to implement a Domain Specific Language to achieve this goal. The language needs to be capable of simple expression evaluation, as well as querying table indexes and iterating through the returned rows. Ease of writing and reading the language is secondary to ease of implementing it. I'd also prefer not to have to write an entire query optimiser, so something that explicitly specifies what indexes to query would be ideal. The interface that this will have to compile against will be similar in capabilities to what the App Engine datastore exports: You can query for sequential ranges on any index on the table (eg, less-than, greater-than, range and equality queries), then filter the returned row by any boolean expression. You can also concatenate multiple independent result sets together. I realise this question sounds a lot like I'm asking for SQL. However, I don't want to require that the datastore backing this data be a relational database, and I don't want the overhead of trying to reimplement SQL myself. I'm also dealing with only a single table with a known schema. Finally, no joins will be required. Something much simpler would be far preferable. Edit: Expanded description to clear up some misconceptions. A: Building a DSL to be interpreted by Python. Step 1. Build the run-time classes and objects. These classes will have all the cursor loops and SQL statements and all of that algorithmic processing tucked away in their methods. You'll make heavy use of the Command and Strategy design patterns to build these classes. Most things are a command, options and choices are plug-in strategies. Look at the design for Apache Ant's Task API -- it's a good example. Step 2. Validate that this system of objects actually works. Be sure that the design is simple and complete. You're tests will construct the Command and Strategy objects, and then execute the top-level Command object. The Command objects will do the work. At this point you're largely done. Your run-time is just a configuration of objects created from the above domain. [This isn't as easy as it sounds. It requires some care to define a set of classes that can be instantiated and then "talk among themselves" to do the work of your application.] Note that what you'll have will require nothing more than declarations. What's wrong with procedural? One you start to write a DSL with procedural elements, you find that you need more and more features until you've written Python with different syntax. Not good. Further, procedural language interpreters are simply hard to write. State of execution, and scope of references are simply hard to manage. You can use native Python -- and stop worrying about "getting out of the sandbox". Indeed, that's how you'll unit test everything, using a short Python script to create your objects. Python will be the DSL. ["But wait", you say, "If I simply use Python as the DSL people can execute arbitrary things." Depends on what's on the PYTHONPATH, and sys.path. Look at the site module for ways to control what's available.] A declarative DSL is simplest. It's entirely an exercise in representation. A block of Python that merely sets the values of some variables is nice. That's what Django uses. You can use the ConfigParser as a language for representing your run-time configuration of objects. You can use JSON or YAML as a language for representing your run-time configuration of objects. Ready-made parsers are totally available. You can use XML, too. It's harder to design and parse, but it works fine. People love it. That's how Ant and Maven (and lots of other tools) use declarative syntax to describe procedures. I don't recommend it, because it's a wordy pain in the neck. I recommend simply using Python. Or, you can go off the deep-end and invent your own syntax and write your own parser. A: I think we're going to need a bit more information here. Let me know if any of the following is based on incorrect assumptions. First of all, as you pointed out yourself, there already exists a DSL for selecting rows from arbitrary tables-- it is called "SQL". Since you don't want to reinvent SQL, I'm assuming that you only need to query from a single table with a fixed format. If this is the case, you probably don't need to implement a DSL (although that's certainly one way to go); it may be easier, if you are used to Object Orientation, to create a Filter object. More specifically, a "Filter" collection that would hold one or more SelectionCriterion objects. You can implement these to inherit from one or more base classes representing types of selections (Range, LessThan, ExactMatch, Like, etc.) Once these base classes are in place, you can create column-specific inherited versions which are appropriate to that column. Finally, depending on the complexity of the queries you want to support, you'll want to implement some kind of connective glue to handle AND and OR and NOT linkages between the various criteria. If you feel like it, you can create a simple GUI to load up the collection; I'd look at the filtering in Excel as a model, if you don't have anything else in mind. Finally, it should be trivial to convert the contents of this Collection to the corresponding SQL, and pass that to the database. However: if what you are after is simplicity, and your users understand SQL, you could simply ask them to type in the contents of a WHERE clause, and programmatically build up the rest of the query. From a security perspective, if your code has control over the columns selected and the FROM clause, and your database permissions are set properly, and you do some sanity checking on the string coming in from the users, this would be a relatively safe option. A: "implement a Domain Specific Language" "nobody is going to want to install a server that downloads and executes arbitrary Python code at runtime" I want a DSL but I don't want Python to be that DSL. Okay. How will you execute this DSL? What runtime is acceptable if not Python? What if I have a C program that happens to embed the Python interpreter? Is that acceptable? And -- if Python is not an acceptable runtime -- why does this have a Python tag? A: Why not create a language that when it "compiles" it generates SQL or whatever query language your datastore requires ? You would be basically creating an abstraction over your persistence layer. A: You mentioned Python. Why not use Python? If someone can "type in" an expression in your DSL, they can type in Python. You'll need some rules on structure of the expression, but that's a lot easier than implementing something new. A: You said nobody is going to want to install a server that downloads and executes arbitrary code at runtime. However, that is exactly what your DSL will do (eventually) so there probably isn't that much of a difference. Unless you're doing something very specific with the data then I don't think a DSL will buy you that much and it will frustrate the users who are already versed in SQL. Don't underestimate the size of the task you'll be taking on. To answer your question however, you will need to come up with a grammar for your language, something to parse the text and walk the tree, emitting code or calling an API that you've written (which is why my comment that you're still going to have to ship some code). There are plenty of educational texts on grammars for mathematical expressions you can refer to on the net, that's fairly straight forward. You may have a parser generator tool like ANTLR or Yacc you can use to help you generate the parser (or use a language like Lisp/Scheme and marry the two up). Coming up with a reasonable SQL grammar won't be easy. But google 'BNF SQL' and see what you come up with. Best of luck. A: It really sounds like SQL, but perhaps it's worth to try using SQLite if you want to keep it simple? A: It sounds like you want to create a grammar not a DSL. I'd look into ANTLR which will allow you to create a specific parser that will interpret text and translate to specific commands. ANTLR provides libraries for Python, SQL, Java, C++, C, C# etc. Also, here is a fine example of an ANTLR calculation engine created in C# A: A context-free grammar usually has a tree like structure and functional programs have a tree like structure too. I don't claim the following would solve all of your problems, but it is a good step in the direction if you are sure that you don't want to use something like SQLite3. from functools import partial def select_keys(keys, from_): return ({k : fun(v, row) for k, (v, fun) in keys.items()} for row in from_) def select_where(from_, where): return (row for row in from_ if where(row)) def default_keys_transform(keys, transform=lambda v, row: row[v]): return {k : (k, transform) for k in keys} def select(keys=None, from_=None, where=None): """ SELECT v1 AS k1, 2*v2 AS k2 FROM table WHERE v1 = a AND v2 >= b OR v3 = c translates to select(dict(k1=(v1, lambda v1, r: r[v1]), k2=(v2, lambda v2, r: 2*r[v2]) , from_=table , where= lambda r : r[v1] = a and r[v2] >= b or r[v3] = c) """ assert from_ is not None idfunc = lambda k, t : t select_k = idfunc if keys is None else select_keys if isinstance(keys, list): keys = default_keys_transform(keys) idfunc = lambda t, w : t select_w = idfunc if where is None else select_where return select_k(keys, select_w(from_, where)) How do you make sure that you are not giving users ability to execute arbitrary code. This framework admits all possible functions. Well, you can right a wrapper over it for security that expose a fixed list of function objects that are acceptable. ALLOWED_FUNCS = [ operator.mul, operator.add, ...] # List of allowed funcs def select_secure(keys=None, from_=None, where=None): if keys is not None and isinstance(keys, dict): for v, fun keys.values: assert fun in ALLOWED_FUNCS if where is not None: assert_composition_of_allowed_funcs(where, ALLOWED_FUNCS) return select(keys=keys, from_=from_, where=where) How to write assert_composition_of_allowed_funcs. It is very difficult to do that it in python but easy in lisp. Let us assume that where is a list of functions to be evaluated in a lips like format i.e. where=(operator.add, (operator.getitem, row, v1), 2) or where=(operator.mul, (operator.add, (opreator.getitem, row, v2), 2), 3). This makes it possible to write a apply_lisp function that makes sure that the where function is only made up of ALLOWED_FUNCS or constants like float, int, str. def apply_lisp(where, rowsym, rowval, ALLOWED_FUNCS): assert where[0] in ALLOWED_FUNCS return apply(where[0], [ (apply_lisp(w, rowsym, rowval, ALLOWED_FUNCS) if isinstance(w, tuple) else rowval if w is rowsym else w if isinstance(w, (float, int, str)) else None ) for w in where[1:] ]) Aside, you will also need to check for exact types, because you do not want your types to be overridden. So do not use isinstance, use type in (float, int, str). Oh boy we have run into: Greenspun's Tenth Rule of Programming: any sufficiently complicated C or Fortran program contains an ad hoc informally-specified bug-ridden slow implementation of half of Common Lisp.
{ "language": "en", "url": "https://stackoverflow.com/questions/140026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Possible causes of Java VM EXCEPTION_ACCESS_VIOLATION? When a Java VM crashes with an EXCEPTION_ACCESS_VIOLATION and produces an hs_err_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts? Edit: there is a native component, this is an SWT application on win32. A: Answer found! I had the same error and noticed that others who provided the contents of the pid log file were running 64 bit Windows. Just like me. At the end log file, it included the PATH statement. There I could see C:\Windows\SysWOW64 was incorrectly listed ahead of: %SystemRoot%\system32. Once I corrected it, the exception disappeared. A: Most of the times this is a bug in the VM. But it can be caused by any native code (e.g. JNI calls). The hs_err_pidXXX.log file should contain some information about where the problem happened. You can also check the "Heap" section inside the file. Many of the VM bugs are caused by the garbage collection (expecially in older VMs). This section should show you if the garbage was running at the time of the crash. Also this section shows, if some sections of the heap are filled (the percentage numbers). The VM is also much more likely to crash in a low memory situation than otherwise. A: First thing you should do is upgrade your JVM to the latest you can. Can you repeat the issue? Or does it seem to happen randomly? We recently had a problem where our JVM was crashing all over the place, at random times. Turns out it was a hardware problem. We put the drives in a new server and it completely went away. Bottom line, the JVM should never crash, as the poster above mentioned if your not doing any JNI then my gut is that you have a hardware problem. A: The cause of the problem will be documented in the hs_err* file, if you know what to look for. Take a look, and if it still isn't clear, consider posting the first 5 or 10 lines of the stack trace and other pertinent info (don't post the whole thing, there's tons of info in there that won't help - but you have to figure out which 1% is important :-) ) A: Are you using a Browser widget and executing javascript in the Browser widget? If so, then there are bugs in some versions of SWT that causes the JVM to crash in native code, in various Windows libraries. Two examples (that I opened) are bug 217306 and bug 127960. These two bug reports are not the only bug reports of the JVM crashing in SWT, however. If you aren't using the Browser widget then these suggestions won't help you. In that case, you can search for a list of SWT bugs causing a JVM crash. If none of those are your issue, then I highly recommend that you open a bug report with SWT. A: I have the same problem with a JNLP application that I have been using for a long time and is pretty reliable. The problem started immediately after I upgraded from Windows 7 to Windows 10. According to my investigation, it is most likely a bug in Win 10. The following is not a solution, but an ugly workaround. In jre/bin directory, there is javaws.exe. If I right-clicked /Properties/Compatibility and ticked Run this program as an administrator, the JNLP app started to work. Please, be aware that this approach could cause security issues and use it only if you have no other option and 100% know what you are doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/140030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: boost::shared_ptr standard container Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.: class foo; typedef boost::shared_ptr<foo> foo_sp; typeded std::map<int, foo_sp> foo_sp_map; foo_sp_map m; If I add a new foo_sp to the map but the key used already exists, will the existing entry be deleted? For example: foo_sp_map m; void func1() { foo_sp p(new foo); m[0] = p; } void func2() { foo_sp p2(new foo); m[0] = p2; } Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing. A: First off, your question title says boost::auto_ptr, but you actually mean boost::shared_ptr And yes, the original pointer will be freed (if there are no further shared references to it). A: It depends on what happens in your ... section Your container class contains copies of instances of foo_sp, when you execute m[0] = p2; the copy of p that was originally in that place goes out of scope. At that time it will be deleted if there are no other foo_sp refers to it. If the copy that was declared in the second line foo_sp p(new foo); is still around then the memory will not be deallocated. The entry will be delete once all references to it have been removed. A: Since stackoverflow won't allow me to comment, I'll just answer. :/ I don't see "p" going out of scope, so the object pointed to by it will not be freed. "p" will still point to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/140033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Loop through all Resources in ResourceManager - C# How do I loop into all the resources in the resourcemanager? Ie: foreach (string resource in ResourceManager) //Do something with the recource. Thanks A: Use ResourceManager.GetResourceSet() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach). To answer Nico's question: you can count the elements of an IEnumerable by casting it to the generic IEnumerable<object> and use the Enumerable.Count<T>() extension method, which is new in C# 3.5: using System.Linq; ... var resourceSet = resourceManager.GetResourceSet(..); var count = resSet.Cast<object>().Count(); A: I wonder why would you like to loop through all of the resources. Anyway, ResourceManager needs to be instantiated giving it a Type or the base name where to lookup for resources. Then you will be able to retrieve a ResourceSet but for a given CultureInfo, ergo if you want to obtain all the resources for a given `ResourceManager
{ "language": "en", "url": "https://stackoverflow.com/questions/140043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: RightNow CRM XML API - Anyone familiar with it? I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page. Any sample code would be greatly appreciated! Link to API: http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf A: I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient: using System.Net; using System.Text; using System; namespace RightNowSample { class Program { static void Main(string[] args) { string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php"; WebClient webClient = new WebClient(); string requestXml = @"<connector> <function name=""ans_get""> <parameter name=""args"" type=""pair""> <pair name=""id"" type=""integer"">33</pair> <pair name=""sub_tbl"" type='pair'> <pair name=""tbl_id"" type=""integer"">164</pair> </pair> </parameter> </function> </connector>"; string secString = ""; string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString); byte[] postDataBytes = Encoding.UTF8.GetBytes(postData); byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes); string responseData = Encoding.UTF8.GetString(responseDataBytes); Console.WriteLine(responseData); } } } I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you. A: This will Create a Contact in Right now class Program { private RightNowSyncPortClient _Service; public Program() { _Service = new RightNowSyncPortClient(); _Service.ClientCredentials.UserName.UserName = "Rightnow UID"; _Service.ClientCredentials.UserName.Password = "Right now password"; } private Contact Contactinfo() { Contact newContact = new Contact(); PersonName personName = new PersonName(); personName.First = "conatctname"; personName.Last = "conatctlastname"; newContact.Name = personName; Email[] emailArray = new Email[1]; emailArray[0] = new Email(); emailArray[0].action = ActionEnum.add; emailArray[0].actionSpecified = true; emailArray[0].Address = "mail@mail.com"; NamedID addressType = new NamedID(); ID addressTypeID = new ID(); addressTypeID.id = 1; addressType.ID = addressTypeID; addressType.ID.idSpecified = true; emailArray[0].AddressType = addressType; emailArray[0].Invalid = false; emailArray[0].InvalidSpecified = true; newContact.Emails = emailArray; return newContact; } public long CreateContact() { Contact newContact = Contactinfo(); //Set the application ID in the client info header ClientInfoHeader clientInfoHeader = new ClientInfoHeader(); clientInfoHeader.AppID = ".NET Getting Started"; //Set the create processing options, allow external events and rules to execute CreateProcessingOptions createProcessingOptions = new CreateProcessingOptions(); createProcessingOptions.SuppressExternalEvents = false; createProcessingOptions.SuppressRules = false; RNObject[] createObjects = new RNObject[] { newContact }; //Invoke the create operation on the RightNow server RNObject[] createResults = _Service.Create(clientInfoHeader, createObjects, createProcessingOptions); //We only created a single contact, this will be at index 0 of the results newContact = createResults[0] as Contact; return newContact.ID.id; } static void Main(string[] args) { Program RBSP = new Program(); try { long newContactID = RBSP.CreateContact(); System.Console.WriteLine("New Contact Created with ID: " + newContactID); } catch (FaultException ex) { Console.WriteLine(ex.Code); Console.WriteLine(ex.Message); } System.Console.Read(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/140044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AVR or PIC to start programming Microcontroller? Which family should I start to learn? (Never did any programming on microcontroller) A: I would suggest AVR. It has far surpassed PIC as the microcontroller platform of choice for general hobbyist projects. Most notably, consider the Arduino (and other *duino) platform, which provides a high end AVR in an easy to interface and popular form factor. A: I very much prefer the AVR over PIC, whose architecture I find a bit messy. This may be just me, and it won't trouble you if you can write in a high level language, most likely (some dialect of) C. Since you're new to microcontrollers I presume performance will not be the issue, so instead I would look for availability of development tools: prototyping boards, IDE and simulation/debugging tools. Personally I liked AVR Studio (Atmel's free development environment) a lot. Jason mentions the TI's MSP430, which is an excellent controller indeed, especially if you're in very low power applications. But I wouldn't recommend it for a newbie, since configuration is a bit cumbersome. (I recall that the description of the oscillator covered 20+ pages in the user manual.) A: I've done some PIC programming - mostly because I liked the idea the chip were only a dollar or two. However, for a beginner, making a decision solely on price is premature optimization. Programming in assembler is an experience. You basically have to learn about 100 concepts before you can blink an LED. (Watchdog timer, reset pins, 8-bit counters/overflows, delay loops, hex, binary, bit-masking, interrupts, interrupt service requests, IO ports, etc.) It's all very educational - and a great feeling to get so close to the machine - but being able to code something in C will hide some of this complexity so you can focus on results. For this reason I would say go with the AVR. (And I believe the prices are now closer to PICs.) Also: If you're interested in getting things done (and don't mind spending ~$30) check out the arduino. A guy selling them at my local electronics shop was saying he's selling tons of them to art students. (It uses the IDE from the Processing project, and compiles code with avr-gcc.) Update: Fixed comment that Arduino runs interpreted code. Also updated the approx Arduino price. A: Some people commented on the strange (and C unfriendly) architecture of the PIC micro. This is true of the smaller PICs, but the 16 bit chips (PIC24F, dsPIC30, etc) have very clear architectures that work very well with C. The PIC24F line has the ability to assign pins to functions (timers, A/D, serial I/O) on the fly, making it a bit easier to design with. The MPLAB environment for debugging and development is quite nice. A: I don't understand what the big deal with arduino is, it will ruin your chance of ever understanding what is actually happening. I program with AVR's and PIC's regularly, basically there is not much difference, I can't see what the big fuss is all about. However for a beginner stay away from arduino, it may be simple, but thats the trap, it gives you no concept of hardware architecture, and no idea what is happening behind the scenes, the stuff beginners need to learn to be an effective programmer. When I was a beginner I started out with an ATmega32 a $20 USBasp programmer, AVR Studio (Free) and AVRDude (Comes with WinAVR) and followed the intro tutorials in AVR Freaks. That is all you need, Done!!! P.S. If you want to really learn how to program micros and have the time learn the assembler for your micro and you will be 20 times the C programmer than someone who started out using arduino. A: Today AVR and PIC are probably the most common microcontrollers among hobbyists. Both have a very wide range of device variants and both can be used to achieve similar results. For a beginner I would suggest AVR due to various reasons: * *AVR family (tiny, mega) is coherent and easy to understand. The architecture is powerful and modern, and is especially suitable for C compilers. AVRs can of course be programmed in assembly too. *Due to its C-friendly architecture, there are quality C compilers available, both commercial and free. The ubiquitous GCC is ported to AVR and called avr-gcc. *For getting started all you really need is a handful of basic components, the AVR chip itself and a breadboard. Even the programming cable between PC and AVR can be built essentially for free (a so called wiggler). However, several commercial development kits are available, most notably Atmel's own STK500. A commercial development kit is more expensive way for getting started, but doesn't require practically any prior knowledge about electronics. Some development kits contain for example LCD displays so it's easy to get interesting stuff done. *It has a rich hobbyist community. PIC is notorious for its peculiar architecture. Many love PIC for this, some hate it. AVR is more straightforward and doesn't seem to cause as much extreme and polar opinions. Both AVR and PIC are used in many serious commercial applications. However, they are not the only options of course. My personal favorite microcontroller for both hobby and commercial work is Silicon Laboratories' C8051 family, most notably C8051F530. There is an excellent free C compiler and assembler for the C8051 family called SDCC. Summary: There are lots of options, but please don't let that overwhelm you. Just pick one and start learning with it. Microcontrollers are, really, surprisingly easy to master once you just decide to get going! A: My vote goes to PIC for the extreme variety of devices availables. But I must say that when I started to use PICs, they was almost nothing else. Maybe now things are changed. A: I vote for TI's MSP430 series. I've used PICs extensively (also Atmel chips a little) and by far the most important thing to me is a good debugging IDE. TI has done a pretty good job on this, and their C++ compiler works really well. You can get going with an eval board for less than $100 including an IDE + USB-debugger. The PICs have better & more diverse hardware peripherals, but MPLAB is a piece of crap and the only C++ IDE for PICs is one by IAR which is rather expensive. (more than $2K) A: I/we chose PIC mostly because there is more peripheral hardware for the same price. And more importantly, you can't even find comparable AVRs. I did choose one of the legacy free versions though (started with PIC18, migrated to dspic33) The IDE is free, the (C) compiler is free in the student version (that disables optimization after the first month). Entry level programmers are fairly cheap too. If you have heaps of interrupts, counters and timers, there is a chance you won't need optimization at all. A programmer straight from Microchip is $30. Note that the above remarks about AVR catering more to HLL development are slightly outdated unless you really go for the legacy architectures like PIC12 and 16. One typically programs the more modern PIC18 (8-bit) and the 16-bit architectures (24F,30F and dspic33 which are based on the same principal core) in C. The 16-bitters even use GCC. There are also MIPS based 32-bitters now, but they rival more with ARM in the audio/video processing scene. Strangely enough, the modern ones are often cheaper than the old ones. Probably they are produced on in a more modern process that has higher yields. Another note: meanwhile Microchip/PIC bought Atmel/AVR, but I assume that for the first few years that won't affect the productlines much. I'm really looking forward to the 60MIPs ethernet enabled 16-bitter that is going to be released this summer (afaik streetprice just above EUR 10) A: My first experience with microcontrollers was with an OOPic-R. It allowed me to make simple robotic experiments without worrying too much about the code. The object oriented programming flow makes everything work fast and is easy to program. Recently, I tried another variety of PIC's, the dirt cheap PICAXE. The included programming interface is a breeze to work with. Also, to physically interface the PICAXE, you only need an RS-232 port to program it and two pins on the chip (no need to do level shifting). I've embedded the PICAXE in very small containers (SMD and DIP chips available) and it has worked quite well. I have no experience with programming microcontrollers in assembly. If you want to try that, the AVR might be more suitable because of it's bigger user community. As far as I know, the cheapest way to program an AVR using ATMEL's tools is the ATMEL AVR ISP mkII for 35$. You can find third-party programmers for 10-15$. A: If you just want to know what is MCU programming, start from Arduino is a good idea. It's cheap, with a novice-friendly IDE (based on processing programming language, which has a similar syntax with C). But this did not answer your quesiton, beacuse altough Arduino is based on AVR, you cannot feel there is an AVR MCU behind that modern IDE. :) A: I had much more success with PIC while I was just getting started. I tried to get a simple starter kit from Arduino and just couldn't get a good basic kit without spending more than $100-200 nickel and diming the setup together. Got a great little starter kit from PIC for about $40 and it has everything: IDE, programmer, starter board with built in circuitry for demos and tutorials. One purchase. Also, the PIC environment was very easy to get set up and working. I was playing with it within an hour. A: I would make my choice based on availability of a C cross-compiler. In the past, that would make AVR the choice. I'm not sure what the status is now. I've programmed a PIC in assembler, and it was not much fun. C is much nicer in many ways. A: My boss picked up the basics using AVR within a week without prior experience. A: http://www.arduino.cc/ HTH A: On of the best features of AVR is the community in the forums at www.avrfreaks.net. You get a bunch of experienced electronics engineers hanging out, willing to help newbies to get going. A: I would say that i fount the 8051 microcontroller the most easiest and Atmel has come up with microcontrollers with so many inbuilt functions .... but still people are more preferably using the AVR's... my hand would go up with the 8051 family ( if found comfortable ) else the AVR's ... A: I love AVR. its easy to program and resources available. there are few community like arduino works with it. A: Some more dicussion about the superiority of AVR, on the other Stack Overflow: http://embeddedgurus.com/stack-overflow/2009/04/pic-stack-overflow/ The popularity of 8 bit PICs baffles me. It’s architecture is awful – the limited call stack is just the first dreadful thing. Throw in the need for paging and banking together with the single interrupt vector and you have a nightmare of a programming model. It would be one thing if this was the norm for 8 bit devices – but it isn’t. The AVR architecture blows the PIC away, while the HC05 / HC08 are also streets ahead of the PIC. Given the choice I think I’d even take an 8051 over the PIC. I don’t see any cost advantages, packaging advantages (Atmel has just released a SOT23-6 AVR which is essentially instruction set compatible with their largest devices) or peripheral set advantages. In short, I don’t get it! Incidentally, this isn’t an indictment of Microchip – they are a great company and I really like a lot of their other products, their web site, tech support and so on (perhaps this is why the PIC is so widely used?) A: I started on a Motorola M68HC11, it was simple enough. I think you'll get about the same experience with any 8Bit controllers.
{ "language": "en", "url": "https://stackoverflow.com/questions/140049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Using InstallUtil and silently setting a windows service logon username/password I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently. Is there are way to do something like this: installutil.exe myservice.exe /customarg1=username /customarg2=password A: A much easier way than the posts above and with no extra code in your installer is to use the following: installUtil.exe /username=domain\username /password=password /unattended C:\My.exe Just ensure the account you use is valid. If not you will receive a "No mapping between account names and security id's was done" exception A: Bravo to my co-worker (Bruce Eddy). He found a way we can make this command-line call: installutil.exe /user=uname /password=pw myservice.exe It is done by overriding OnBeforeInstall in the installer class: namespace Test { [RunInstaller(true)] public class TestInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller serviceProcessInstaller; public OregonDatabaseWinServiceInstaller() { serviceInstaller = new ServiceInstaller(); serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Test"; serviceInstaller.DisplayName = "Test Service"; serviceInstaller.Description = "Test"; serviceInstaller.StartType = ServiceStartMode.Automatic; Installers.Add(serviceInstaller); serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.User; Installers.Add(serviceProcessInstaller); } public string GetContextParameter(string key) { string sValue = ""; try { sValue = this.Context.Parameters[key].ToString(); } catch { sValue = ""; } return sValue; } // Override the 'OnBeforeInstall' method. protected override void OnBeforeInstall(IDictionary savedState) { base.OnBeforeInstall(savedState); string username = GetContextParameter("user").Trim(); string password = GetContextParameter("password").Trim(); if (username != "") serviceProcessInstaller.Username = username; if (password != "") serviceProcessInstaller.Password = password; } } } A: InstallUtil.exe sets StartupType=Manual In case you want to autostart the service, use: sc config MyServiceName start= auto (note there there has to be a space after '=') A: No, installutil doesn't support that. Of course if you wrote an installer; with a custom action then you would be able to use that as part of an MSI or via installutil. A: You can also force your service to run as User using ServiceProcessInstaller::Account = ServiceAccount.User; A popup asking "[domain\]user, password" will appear during service installation. public class MyServiceInstaller : Installer { /// Public Constructor for WindowsServiceInstaller public MyServiceInstaller() { ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller(); ServiceInstaller serviceInstaller = new ServiceInstaller(); //# Service Account Information serviceProcessInstaller.Account = ServiceAccount.User; // and not LocalSystem; ....
{ "language": "en", "url": "https://stackoverflow.com/questions/140054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Java: Advice on handling large data volumes. (Part Deux) Alright. So I have a very large amount of binary data (let's say, 10GB) distributed over a bunch of files (let's say, 5000) of varying lengths. I am writing a Java application to process this data, and I wish to institute a good design for the data access. Typically what will happen is such: * *One way or another, all the data will be read during the course of processing. *Each file is (typically) read sequentially, requiring only a few kilobytes at a time. However, it is often necessary to have, say, the first few kilobytes of each file simultaneously, or the middle few kilobytes of each file simultaneously, etc. *There are times when the application will want random access to a byte or two here and there. Currently I am using the RandomAccessFile class to read into byte buffers (and ByteBuffers). My ultimate goal is to encapsulate the data access into some class such that it is fast and I never have to worry about it again. The basic functionality is that I will be asking it to read frames of data from specified files, and I wish to minimize the I/O operations given the considerations above. Examples for typical access: * *Give me the first 10 kilobytes of all my files! *Give me byte 0 through 999 of file F, then give me byte 1 through 1000, then give me 2 through 1001, etc, etc, ... *Give me a megabyte of data from file F starting at such and such byte! Any suggestions for a good design? A: Use Java NIO and MappedByteBuffers, and treat your files as a list of byte arrays. Then, let the OS worry about the details of caching, read, flushing etc. A: @Will Pretty good results. Reading a large binary file quick comparison: * *Test 1 - Basic sequential read with RandomAccessFile. 2656 ms *Test 2 - Basic sequential read with buffering. 47 ms *Test 3 - Basic sequential read with MappedByteBuffers and further frame buffering optimization. 16 ms A: Wow. You are basically implementing a database from scratch. Is there any possibility of importing the data into an actual RDBMS and just using SQL? If you do it yourself you will eventually want to implement some sort of caching mechanism, so the data you need comes out of RAM if it is there, and you are reading and writing the files in a lower layer. Of course, this also entails a lot of complex transactional logic to make sure your data stays consistent. A: I was going to suggest that you follow up on Eric's database idea and learn how databases manage their buffers—effectively implementing their own virtual memory management. But as I thought about it more, I concluded that most operating systems are already a better job of implementing file system caching than you can likely do without low-level access in Java. There is one lesson from database buffer management that you might consider, though. Databases use an understanding of the query plan to optimize the management strategy. In a relational database, it's often best to evict the most-recently-used block from the cache. For example, a "young" block holding a child record in a join won't be looked at again, while the block containing its parent record is still in use even though it's "older". Operating system file caches, on the other hand, are optimized to reuse recently used data (and reading ahead of the most recently used data). If your application doesn't fit that pattern, it may be worth managing the cache yourself. A: You may want to take a look at an open source, simple object database called jdbm - it has a lot of this kind of thing developed, including ACID capabilities. I've done a number of contributions to the project, and it would be worth a review of the source code if nothing else to see how we solved many of the same problems you might be working on. Now, if your data files are not under your control (i.e. you are parsing text files generated by someone else, etc...) then the page-structured type of storage that jdbm uses may not be appropriate for you - but if all of these files are files that you are creating and working with, it may be worth a look. A: @Eric But my queries are going to be much, much simpler than anything I can do with SQL. And wouldn't a database access be much more expensive than a binary data read? A: This is to answer the part about minimizing I/O traffic. On the Java side, all you can really do is wrap your readers in BufferedReaders. Aside from that, your operating system will handle other optimizations like keeping recently-read data in the page cache and doing read-ahead on files to speed up sequential reads. There's no point in doing additional buffering in Java (although you'll still need a byte buffer to return the data to the client). A: I had someone recommend hadoop (http://hadoop.apache.org) to me just the other day. It looks like it could be pretty nice, and might have some marketplace traction. A: I would step back and ask yourself why you are using files as your system of record, and what gains that gives you over using a database. A database certainly gives you the ability to structure your data. Given the SQL standard, it might be more maintainable in the long run. On the other hand, your file data may not be structured so easily within the constraints of a database. The largest search company in the world :) doesn't use a database for their business processing. See here and here.
{ "language": "en", "url": "https://stackoverflow.com/questions/140056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: When to use dynamic vs. static libraries When creating a class library in C++, you can choose between dynamic (.dll, .so) and static (.lib, .a) libraries. What is the difference between them and when is it appropriate to use which? A: Ulrich Drepper's paper on "How to Write Shared Libraries" is also good resource that details how best to take advantage of shared libraries, or what he refers to as "Dynamic Shared Objects" (DSOs). It focuses more on shared libraries in the ELF binary format, but some discussions are suitable for Windows DLLs as well. A: A lib is a unit of code that is bundled within your application executable. A dll is a standalone unit of executable code. It is loaded in the process only when a call is made into that code. A dll can be used by multiple applications and loaded in multiple processes, while still having only one copy of the code on the hard drive. Dll pros: can be used to reuse/share code between several products; load in the process memory on demand and can be unloaded when not needed; can be upgraded independently of the rest of the program. Dll cons: performance impact of the dll loading and code rebasing; versioning problems ("dll hell") Lib pros: no performance impact as code is always loaded in the process and is not rebased; no versioning problems. Lib cons: executable/process "bloat" - all the code is in your executable and is loaded upon process start; no reuse/sharing - each product has its own copy of the code. A: For an excellent discussion of this topic have a read of this article from Sun. It goes into all the benefits including being able to insert interposing libraries. More detail on interposing can be found in this article here. A: C++ programs are built in two phases * *Compilation - produces object code (.obj) *Linking - produces executable code (.exe or .dll) Static library (.lib) is just a bundle of .obj files and therefore isn't a complete program. It hasn't undergone the second (linking) phase of building a program. Dlls, on the other hand, are like exe's and therefore are complete programs. If you build a static library, it isn't linked yet and therefore consumers of your static library will have to use the same compiler that you used (if you used g++, they will have to use g++). If instead you built a dll (and built it correctly), you have built a complete program that all consumers can use, no matter which compiler they are using. There are several restrictions though, on exporting from a dll, if cross compiler compatibility is desired. A: Really the trade off you are making (in a large project) is in initial load time, the libraries are going to get linked at one time or another, the decision that has to be made is will the link take long enough that the compiler needs to bite the bullet and do it up front, or can the dynamic linker do it at load time. A: Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run. Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the original one that shipped with your code if the update is considered binary compatible with the original version. Additionally dynamic libraries aren't necessarily loaded -- they're usually loaded when first called -- and can be shared among components that use the same library (multiple data loads, one code load). Dynamic libraries were considered to be the better approach most of the time, but originally they had a major flaw (google DLL hell), which has all but been eliminated by more recent Windows OSes (Windows XP in particular). A: If your library is going to be shared among several executables, it often makes sense to make it dynamic to reduce the size of the executables. Otherwise, definitely make it static. There are several disadvantages of using a dll. There is additional overhead for loading and unloading it. There is also an additional dependency. If you change the dll to make it incompatible with your executalbes, they will stop working. On the other hand, if you change a static library, your compiled executables using the old version will not be affected. A: If the library is static, then at link time the code is linked in with your executable. This makes your executable larger (than if you went the dynamic route). If the library is dynamic then at link time references to the required methods are built in to your executable. This means that you have to ship your executable and the dynamic library. You also ought to consider whether shared access to the code in the library is safe, preferred load address among other stuff. If you can live with the static library, go with the static library. A: We use a lot of DLL's (> 100) in our project. These DLL's have dependencies on each other and therefore we chose the setup of dynamic linking. However it has the following disadvantages: * *slow startup (> 10 seconds) *DLL's had to be versioned, since windows loads modules on uniqueness of names. Own written components would otherwise get the wrong version of the DLL (i.e. the one already loaded instead of its own distributed set) *optimizer can only optimize within DLL boundaries. For example the optimizer tries to place frequently used data and code next to each other, but this will not work across DLL boundaries Maybe a better setup was to make everything a static library (and therefore you just have one executable). This works only if no code duplication takes place. A test seems to support this assumption, but i couldn't find an official MSDN quote. So for example make 1 exe with: * *exe uses shared_lib1, shared_lib2 *shared_lib1 use shared_lib2 *shared_lib2 The code and variables of shared_lib2 should be present in the final merged executable only once. Can anyone support this question? A: Besides the technical implications of static vs dynamic libraries (static files bundle everything in one big binary vs dynamic libraries that allow code sharing among several different executables), there are the legal implications. For example, if you are using LGPL licensed code and you link statically against a LGPL library (and thus create one big binary), your code automatically becomes Open Sourced (free as in freedom) LGPL code. If you link against a shared objects, then you only need to LGPL the improvements / bug fixes that you make to the LGPL library itself. This becomes a far more important issue if you are deciding how to compile you mobile applications for example (in Android you have a choice of static vs dynamic, in iOS you do not - it is always static). A: Others have adequately explained what a static library is, but I'd like to point out some of the caveats of using static libraries, at least on Windows: * *Singletons: If something needs to be global/static and unique, be very careful about putting it in a static library. If multiple DLLs are linked against that static library they will each get their own copy of the singleton. However, if your application is a single EXE with no custom DLLs, this may not be a problem. *Unreferenced code removal: When you link against a static library, only the parts of the static library that are referenced by your DLL/EXE will get linked into your DLL/EXE. For example, if mylib.lib contains a.obj and b.obj and your DLL/EXE only references functions or variables from a.obj, the entirety of b.obj will get discarded by the linker. If b.obj contains global/static objects, their constructors and destructors will not get executed. If those constructors/destructors have side effects, you may be disappointed by their absence. Likewise, if the static library contains special entrypoints you may need to take care that they are actually included. An example of this in embedded programming (okay, not Windows) would be an interrupt handler that is marked as being at a specific address. You also need to mark the interrupt handler as an entrypoint to make sure it doesn't get discarded. Another consequence of this is that a static library may contain object files that are completely unusable due to unresolved references, but it won't cause a linker error until you reference a function or variable from those object files. This may happen long after the library is written. *Debug symbols: You may want a separate PDB for each static library, or you may want the debug symbols to be placed in the object files so that they get rolled into the PDB for the DLL/EXE. The Visual C++ documentation explains the necessary options. *RTTI: You may end up with multiple type_info objects for the same class if you link a single static library into multiple DLLs. If your program assumes that type_info is "singleton" data and uses &typeid() or type_info::before(), you may get undesirable and surprising results. A: Static libraries are archives that contain the object code for the library, when linked into an application that code is compiled into the executable. Shared libraries are different in that they aren't compiled into the executable. Instead the dynamic linker searches some directories looking for the library(s) it needs, then loads that into memory. More then one executable can use the same shared library at the same time, thus reducing memory usage and executable size. However, there are then more files to distribute with the executable. You need to make sure that the library is installed onto the uses system somewhere where the linker can find it, static linking eliminates this problem but results in a larger executable file. A: If your working on embedded projects or specialized platforms static libraries are the only way to go, also many times they are less of a hassle to compile into your application. Also having projects and makefile that include everything makes life happier. A: I'd give a general rule of thumb that if you have a large codebase, all built on top of lower level libraries (eg a Utils or Gui framework), which you want to partition into more manageable libraries then make them static libraries. Dynamic libraries don't really buy you anything and there are fewer surprises -- there will only be one instance of singletons for instance. If you have a library that is entirely separate to the rest of the codebase (eg a third party library) then consider making it a dll. If the library is LGPL you may need to use a dll anyway due to the licensing conditions. A: Creating a static library $$:~/static [32]> cat foo.c #include<stdio.h> void foo() { printf("\nhello world\n"); } $$:~/static [33]> cat foo.h #ifndef _H_FOO_H #define _H_FOO_H void foo(); #endif $$:~/static [34]> cat foo2.c #include<stdio.h> void foo2() { printf("\nworld\n"); } $$:~/static [35]> cat foo2.h #ifndef _H_FOO2_H #define _H_FOO2_H void foo2(); #endif $$:~/static [36]> cat hello.c #include<foo.h> #include<foo2.h> void main() { foo(); foo2(); } $$:~/static [37]> cat makefile hello: hello.o libtest.a cc -o hello hello.o -L. -ltest hello.o: hello.c cc -c hello.c -I`pwd` libtest.a:foo.o foo2.o ar cr libtest.a foo.o foo2.o foo.o:foo.c cc -c foo.c foo2.o:foo.c cc -c foo2.c clean: rm -f foo.o foo2.o libtest.a hello.o $$:~/static [38]> creating a dynamic library $$:~/dynamic [44]> cat foo.c #include<stdio.h> void foo() { printf("\nhello world\n"); } $$:~/dynamic [45]> cat foo.h #ifndef _H_FOO_H #define _H_FOO_H void foo(); #endif $$:~/dynamic [46]> cat foo2.c #include<stdio.h> void foo2() { printf("\nworld\n"); } $$:~/dynamic [47]> cat foo2.h #ifndef _H_FOO2_H #define _H_FOO2_H void foo2(); #endif $$:~/dynamic [48]> cat hello.c #include<foo.h> #include<foo2.h> void main() { foo(); foo2(); } $$:~/dynamic [49]> cat makefile hello:hello.o libtest.sl cc -o hello hello.o -L`pwd` -ltest hello.o: cc -c -b hello.c -I`pwd` libtest.sl:foo.o foo2.o cc -G -b -o libtest.sl foo.o foo2.o foo.o:foo.c cc -c -b foo.c foo2.o:foo.c cc -c -b foo2.c clean: rm -f libtest.sl foo.o foo 2.o hello.o $$:~/dynamic [50]> A: A static library gets compiled into the client. A .lib is used at compile time and the contents of the library become part of the consuming executable. A dynamic library is loaded at runtime and not compiled into the client executable. Dynamic libraries are more flexible as multiple client executables can load a DLL and utilize its functionality. This also keeps the overall size and maintainability of your client code to a minimum. A: A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file. You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file). You would use a static library whenever you don't have a reason to use a dynamic library. A: You should think carefully about changes over time, versioning, stability, compatibility, etc. If there are two apps that use the shared code, do you want to force those apps to change together, in case they need to be compatible with each other? Then use the dll. All the exe's will be using the same code. Or do you want to isolate them from each other, so that you can change one and be confident you haven't broken the other. Then use the static lib. DLL hell is when you probably SHOULD HAVE used a static lib, but you used a dll instead, and not all the exes are comaptible with it. A: Apart from all the points that have been mentioned by others, I use static libraries in a specific use-case to: Not allow my end users to get access to some general-purpose libraries that I have developed in my code. In other words, suppose that I have two libraries in my product, A and B. A uses B services and depends on it. But B is a general-purpose library including lots of helpful services that can be used separately. To avoid my end users to benefit from B directly (they should pay for its license!), I usually compile B as a static library and put it directly inside A. As a result, B services would be totally private to A and cannot be used by end users.
{ "language": "en", "url": "https://stackoverflow.com/questions/140061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "498" }
Q: Where should a Subversion repository be? Should it be on the development servers or a Subversion server? I suppose this could be expanded to any client-server version control system. A: The physical repository should be on a stable system that gets regular backups. Generally, a development server does not fit this description... it may be acceptable to put the apache server on the dev server and host the files remotely on a stable, backed-up file server (though there are a number of pitfalls with this approach) if you are unable to get additional server resources. Hosting it on the dev server may be fine if you have an aggressive backup system to protect your code... Just keep in mind that dev servers are prone to configuration changes, being blown-away, or otherwise mucked with that could take down your repo at a critical moment. A: I like to keep mine on its own server, only because in my view its one of the most important servers in an organization, and keeping it on its own server helps admins do backups and other maintenance activities. And because the server is so important you don't want to have other developers mucking around on it in any way that could compromise it by accident. Also if you have a bunch of developers and an active continuous-integration server running you could actually spike the cpu quite a bit and the last thing you want to do is have anything standing in the way of you committing your code changes A: In addition to what other people mentioned about dev servers being trashed regularly, there is a performance argument too. If someone is doing some development or testing on the development server, you don't want that to slow down the SVN server for checkouts or synchronizations. Also if you decide to run something like continuous integration on the same server, you don't want all your unit tests to bog down regular dev/test operations on that server. A: I keep mine on the development server, which also runs Trac, Apache hosting an automatically-updated copy of the project JavaDocs, and the CI build platform. A project would have to be of fairly epic proportions to require a dedicated Subversion server. However, keep in mind that it is very important to keep your Subversion repository backed up on another machine in another location - your repository is your most valuable asset! A: Development boxes will, by definition, get trashed and fall over. It comes with the territory! Do you really want this to happen to your source code repositories?... A: At my firm we put it on a dedicated machine that provides redundant storage. I guess in our culture we put high value on the source and the time and effort it takes to create our source codes. We never put on any kind of testing machine that might become damanged or wiped clean because the configuration became unmanageable. woops. we also keep our defect tracking on the same box but for the same reason. A: We use a clean, blank slate for our repositories. Specifically, we use Slicehost for our main repository. We started with a 256MB slice and upgraded later on to 512MB. Slicehost is great because you know you have a completely clean server to start with, and can build the things you need on your own. Slicehosts' articles are top-notch. Our repo server looks like this: * *Ubuntu Hardy Heron *Subversion *Apache *Ruby on Rails *Warehouse *Passenger to serve Warehouse via Apache *Daily and weekly backups through Slicehost And that's about it. Not much overhead. Edit: Not trying to sell Slicehost here, so if that's not kosher, let me know! Edit again: James makes an excellent point about hosting proprietary code on a third-party server. Extra care should certainly be taken when selecting a host to do such a thing. Unfortunately, many companies simply don't have the resources to build and manage servers in house, which is where we found ourselves prior to selecting a host for our code. A: It is always better to keep your repositories on a stable server where you can reliably take backups whenever needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/140090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is MVC-ARS preferable to classic MVC to prevent overloading? The popular design pattern MVC (Model/View/Controller) has an extended cousin MVC-ARS (Action/Representation/State). The added components all live within the database layer and while are not part of the model, they are invoked by it. Details are as follows: * *State, as in state machine. This follows the classic state machine pattern. There is a current state which is matched with an event which results in a continue or stop condition and perhaps a state change. *Action, as in the objective of all information technology systems, act on the data. This means our transaction, the CRUD (Create/Read/Update/Delete) of data in the database. This may have been blocked by the state machine. *Representation, as in what data are we sending back that will become the model. The data model and the MVC model are likely very different, relational vs. XML hierarchical for instance. Nothing wrong with that if it is explicit and understood. This is the representation. Doesn't this extension prevent overloading of the either the model or the controller by a separation of state control, transaction control, and data snapshot? A: Never underestimate the ability of a developer to bastardize whatever safeguards you think are in place. While these added separations may allow for additional protection, do they make it easier to develop? Do they make the separations easy to understand and use? If not, the developers are less likely to incorporate them into their practices. Developers tend to work towards the least resistance.
{ "language": "en", "url": "https://stackoverflow.com/questions/140098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I return a custom HTTP status code from a WCF REST method? If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method? A: If you need to return a reason body then have a look at WebFaultException For example throw new WebFaultException<string>("Bar wasn't Foo'd", HttpStatusCode.BadRequest ); A: You can also return a statuscode and reason body with WebOperationContext's StatusCode and StatusDescription: WebOperationContext context = WebOperationContext.Current; context.OutgoingResponse.StatusCode = HttpStatusCode.OK; context.OutgoingResponse.StatusDescription = "Your Message"; A: For 404 there is a built in method on the WebOperationContext.Current.OutgoingResponse called SetStatusAsNotFound(string message) that will set the status code to 404 and a status description with one call. Note there is also, SetStatusAsCreated(Uri location) that will set the status code to 201 and location header with one call. A: If you wish to see the status description in the header, REST method should make sure to return null from the Catch() section as below: catch (ArgumentException ex) { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message; return null; } A: There is a WebOperationContext that you can access and it has a OutgoingResponse property of type OutgoingWebResponseContext which has a StatusCode property that can be set. WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; A: WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; throw new WebException("令牌码不正确", new InvalidTokenException()); ref:https://social.msdn.microsoft.com/Forums/en-US/f6671de3-34ce-4b70-9a77-39ecf5d1b9c3/weboperationcontext-http-statuses-and-exceptions?forum=wcf A: This did not work for me for WCF Data Services. Instead, you can use DataServiceException in case of Data Services. Found the following post useful. http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/thread/f0cbab98-fcd7-4248-af81-5f74b019d8de
{ "language": "en", "url": "https://stackoverflow.com/questions/140104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: Sending an arbitrary Signal in Windows? Linux supports sending an arbitrary Posix-Signal such as SIGINT or SIGTERM to a process using the kill-Command. While SIGINT and SIGTERM are just boring old ways to end a process in a friendly or not-so-friendly kind of way, SIGQUIT is meant to trigger a core dump. This can be used to trigger a running Java VM to print out a thread dump, including the stacktraces of all running threads -- neat! After printing the debugging info, the Java VM will continue doing whatever it was doing before; in fact the thread dump just happens in another spawned thread of maximum priority. (You can try this out yourself by using kill -3 <VM-PID>.) Note that you can also register your own signal handlers using the (unsupported!) Signal and SignalHandler classes in the sun.misc-package, so you can have all kinds of fun with it. However, I have yet to find a way to send a signal to a Windows process. Signals are created by certain user inputs: Ctrl-C triggers a SIGINT on both platforms, for instance. But there does not seem to be any utility to manually send a signal to a running, but non-interactive process on Windows. The obvious solution is to use the Cygwin kill executable, but while it can end Windows processes using the appropriate Windows API, I could not send a SIGBREAK (the Windows equivalent to SIGQUIT) with it; in fact I think the only signal it is able to send to Windows processes is SIGTERM. So, to make a long story short and to repeat the headline: How to I send an arbitrary signal to a process in Windows? A: Windows is not POSIX. It does not have signals. The only 'signals' that console programs get is if they call SetConsoleCtrlHandler, in which case it can be notified that the user has pressed Ctrl+C, Ctrl+Break, closed the console window, logged off, or shut the system down. Everything else is done with IPC, typically with window messages or RPC. Check Sun's documentation to see if there's a way to do what you're asking on the Windows JRE. A: In Windows everything revolves around Win32 messages. I do not believe there is a command line tool to do this, but in C++ you could use FindWindow to send an arbitrary message to another Windows program. e.g.: #define WM_MYMSG ( WM_USER+0x100 ) HWND h = ::FindWindow(NULL,_T("Win32App")); if (h) { ::PostMessage(h, WM_MYMSG, 0, 0); } This can also be done in C# using com interop. A: SIGINT and other signals can be send to program using windows-kill (previously was here on original author's GitHub, but now disappeared, also thanks to @NathanOsman we have web archive of sources or web archive of binary releases). Using by syntax windows-kill -SIGINT PID, where PID can be obtained by Microsoft's pslist. Regarding catching SIGINTs, if your program is in Python then you can implement SIGINT processing/catching like in this solution. A: If what you want is to explicitly/programmatically kill another program/process of any kind, within the SysInternals' pstools there is a small tool named "pskill" that behaves just like Unixen "kill" would do. If you want something else, keep reading (though I may be wrong on some of the specifics below - it's been eons since I last developed a Windows program in C using only the WinAPI and Charles Petzold's excellent books "Programming for Windows" as a guide). On Windows you don't properly have "signals", what functions WinMain and WinProc receive from the Operating System are simple messages. For instance, when you click on the "X" button of a window, Windows sends that windows' handler the message WM_CLOSE. When the window's deleted but program's still running, it sends WM_DESTROY. When it's about to get out of the main message processing loop, WinMain (not WinProc) receives WM_QUIT. Your program should respond to all these as expected - you can actually develop an "unclosable" application by not doing what it should upon receiving a WM_CLOSE. When user selects the task from Windows Task Manager and clicks "End Task", the OS will send WM_CLOSE (and another one I don't remember). If you use "End Process", though, the process is killed directly, no messages sent ever (source: The Old New Thing) I remember there was a way to get the HWND of another process' window, once you get that another process could send that window a message thru functions PostMessage and DispatchMessage. A: You can also use jconsole to view the stacktrace of all the running threads. This will work on Windows, and any other OS that supports Java. jconsole also has many other nice features, memory graphs, cpu graphs, etc. It doesn't answer your original question, but hopefully allows you to get the same results. If your not familiar with jconsole, check out the Using JConsole documentation. A: I'm just wondering if the PsTools from, now Microsoft owned, SysInternals would help you. A: Ruby is somehow able to (at least emulate) SIGINT SIGKILL etc. on windows, and trap those messages. Might want to check it out. How ruby does "send signal SIGINT to that process" underneath, in windows, is actually to call TerminateProcess or equivalent on that PID. There's also a windows equivalent method for "catching ctrl+c" I imagine it's what it calls there.
{ "language": "en", "url": "https://stackoverflow.com/questions/140111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Consume Webservice using https protocol I want to consume a web service over https from a java client. What steps will i need to take in order to do this? A: Really, there shouldn't much different from consuming a web service over HTTP. The big thing is that the process calling the web service will have to trust the server's SSL certificate. If the certificate was purchased from a well-known certificate-issuing authority, this usually isn't a problem. Otherwise, the client will want to either trust the root certificate, or the certificate associated with the server's fully qualified host name. A: You may need to use the keytool command to trust the server's SSL certificate. I've generally found that it is necessary to run something like this: keytool -importcert -v -trustcacerts -alias ServerName -file server_cert_file.crt -keystore client_keystore_file A: Blair says it right. all the same, try it out using SoapUI , which is a web service test client. This is an open source utility : so you get a chance to see how things work under the covers.
{ "language": "en", "url": "https://stackoverflow.com/questions/140113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reading hidden share in C# So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network. I thought I could just read \hostname\C$ as a directory path, but with the normal Directory class there doesn't seem to be a way to authenticate against the other servers so you can access the hidden share. I'm sure there's an easy way to do this that I've overlooked, but at the moment I'm a bit stumpted. A: From http://bytes.com/forum/thread689145.html: All processes run in the context of a logged-in user account. If you want to open a file on another computer, your application must be running in the context of a user that has permissions to open files on that machine. You can do this with Impersonation. The easiest way seems to be to give the current user appropriate rights on the other machines. A: To authenticate with a share to which the user running the process does not have permission (which is often the case for administrative shares), try running the net use command: net use SERVERNAME\IPC$ /user:USERNAME PASSWORD Try running this in a separate process before the code which actually tries to access the share, e.g.: ProcessStartInfo psi = new ProcessStartInfo( "net", "use " + SERVERNAME + @"\IPC$ /user:" + USERNAME + " " + PASSWORD); Process p = new Process(); p.StartInfo = psi; p.Start(); p.WaitForExit(); p.Close(); // The code to access the share follows... This is useful if it is not appropriate to give permission to the share for the user account running the process, e.g. for a security model where an end-user application needs to access data on a share to which the user herself should not have direct access. A: Are you looking for a way to set the current user at run-time? If not, as long as the user running the process has access to those machines, this will work for you: DirectoryInfo di = new DirectoryInfo(@"\\machineName\c$\temp"); FileInfo[] files = di.GetFiles(); foreach (FileInfo f in files) { Debug.WriteLine(f.Name); }
{ "language": "en", "url": "https://stackoverflow.com/questions/140115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Available space left on drive - WinAPI - Windows CE I've forgotten the WinAPI call to find out how much space is remaining on a particular drive and pinvoke.net isn't giving me any love. It's compact framework by the way, so I figure coredll.dll. Can anyone with a better memory jog mine? A: GetDiskFreeSpaceEx. That links to pinvoke.net's desktop page; simply replace kernel32 with coredll. Unfortunately System.IO.DriveInfo is not present on Compact Framework. It doesn't quite fit with Windows CE's Unix-style singly-rooted tree.
{ "language": "en", "url": "https://stackoverflow.com/questions/140117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Invoking Web Services From a Java Client I have a simple web app that runs inside Tomcat. I need to call a web service from this web app and I'm not sure how to go about it. It seems there are two methods depending on whether you are using a managed or unmanaged environment: JNDI service lookup (managed) and JAX-RPC ServiceFactory (unmanaged) ...So which technique should I use? A: You don't have to necessarily use those techniques. Assuming you're using Axis as the web services engine and ant as the build tool(http://ws.apache.org/axis/java/user-guide.html), you need to do the following 1) generate the proxy/stub for invoking the web services. This will give you an entry point into calling the webservices 2) provide configuration info for the client -- a .wsdd file 3) know where the WSDL for your webservices is. BR, ~a A: If it is a web-service, why not use apache's httpclient?
{ "language": "en", "url": "https://stackoverflow.com/questions/140127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert a string representation of a hex dump to a byte array using Java? I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array. I couldn't have phrased it better than the person that posted the same question here. But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the byte[] {0x00,0xA0,0xBf} what should I do? I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple. A: Update (2021) - Java 17 now includes java.util.HexFormat (only took 25 years): HexFormat.of().parseHex(s) For older versions of Java: Here's a solution that I think is better than any posted so far: /* s must be an even-length string. */ public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } Reasons why it is an improvement: * *Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte) *Doesn't convert the String into a char[], or create StringBuilder and String objects for every single byte. *No library dependencies that may not be available Feel free to add argument checking via assert or exceptions if the argument is not known to be safe. A: EDIT: as pointed out by @mmyers, this method doesn't work on input that contains substrings corresponding to bytes with the high bit set ("80" - "FF"). The explanation is at Bug ID: 6259307 Byte.parseByte not working as advertised in the SDK Documentation. public static final byte[] fromHexString(final String s) { byte[] arr = new byte[s.length()/2]; for ( int start = 0; start < s.length(); start += 2 ) { String thisByte = s.substring(start, start+2); arr[start/2] = Byte.parseByte(thisByte, 16); } return arr; } A: The BigInteger() Method from java.math is very Slow and not recommandable. Integer.parseInt(HEXString, 16) can cause problems with some characters without converting to Digit / Integer a Well Working method: Integer.decode("0xXX") .byteValue() Function: public static byte[] HexStringToByteArray(String s) { byte data[] = new byte[s.length()/2]; for(int i=0;i < s.length();i+=2) { data[i/2] = (Integer.decode("0x"+s.charAt(i)+s.charAt(i+1))).byteValue(); } return data; } Have Fun, Good Luck A: You can now use BaseEncoding in guava to accomplish this. BaseEncoding.base16().decode(string); To reverse it use BaseEncoding.base16().encode(bytes); A: For what it's worth, here's another version which supports odd length strings, without resorting to string concatenation. public static byte[] hexStringToByteArray(String input) { int len = input.length(); if (len == 0) { return new byte[] {}; } byte[] data; int startIdx; if (len % 2 != 0) { data = new byte[(len / 2) + 1]; data[0] = (byte) Character.digit(input.charAt(0), 16); startIdx = 1; } else { data = new byte[len / 2]; startIdx = 0; } for (int i = startIdx; i < len; i += 2) { data[(i + 1) / 2] = (byte) ((Character.digit(input.charAt(i), 16) << 4) + Character.digit(input.charAt(i+1), 16)); } return data; } A: One-liners: import javax.xml.bind.DatatypeConverter; public static String toHexString(byte[] array) { return DatatypeConverter.printHexBinary(array); } public static byte[] toByteArray(String s) { return DatatypeConverter.parseHexBinary(s); } Warnings: * *in Java 9 Jigsaw this is no longer part of the (default) java.se root set so it will result in a ClassNotFoundException unless you specify --add-modules java.se.ee (thanks to @eckes) *Not available on Android (thanks to Fabian for noting that), but you can just take the source code if your system lacks javax.xml for some reason. Thanks to @Bert Regelink for extracting the source. A: Actually, I think the BigInteger is solution is very nice: new BigInteger("00A0BF", 16).toByteArray(); Edit: Not safe for leading zeros, as noted by the poster. A: I like the Character.digit solution, but here is how I solved it public byte[] hex2ByteArray( String hexString ) { String hexVal = "0123456789ABCDEF"; byte[] out = new byte[hexString.length() / 2]; int n = hexString.length(); for( int i = 0; i < n; i += 2 ) { //make a bit representation in an int of the hex value int hn = hexVal.indexOf( hexString.charAt( i ) ); int ln = hexVal.indexOf( hexString.charAt( i + 1 ) ); //now just shift the high order nibble and add them together out[i/2] = (byte)( ( hn << 4 ) | ln ); } return out; } A: One-liners: import javax.xml.bind.DatatypeConverter; public static String toHexString(byte[] array) { return DatatypeConverter.printHexBinary(array); } public static byte[] toByteArray(String s) { return DatatypeConverter.parseHexBinary(s); } For those of you interested in the actual code behind the One-liners from FractalizeR (I needed that since javax.xml.bind is not available for Android (by default)), this comes from com.sun.xml.internal.bind.DatatypeConverterImpl.java : public byte[] parseHexBinary(String s) { final int len = s.length(); // "111" is not a valid hex encoding. if( len%2 != 0 ) throw new IllegalArgumentException("hexBinary needs to be even-length: "+s); byte[] out = new byte[len/2]; for( int i=0; i<len; i+=2 ) { int h = hexToBin(s.charAt(i )); int l = hexToBin(s.charAt(i+1)); if( h==-1 || l==-1 ) throw new IllegalArgumentException("contains illegal character for hexBinary: "+s); out[i/2] = (byte)(h*16+l); } return out; } private static int hexToBin( char ch ) { if( '0'<=ch && ch<='9' ) return ch-'0'; if( 'A'<=ch && ch<='F' ) return ch-'A'+10; if( 'a'<=ch && ch<='f' ) return ch-'a'+10; return -1; } private static final char[] hexCode = "0123456789ABCDEF".toCharArray(); public String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder(data.length*2); for ( byte b : data) { r.append(hexCode[(b >> 4) & 0xF]); r.append(hexCode[(b & 0xF)]); } return r.toString(); } A: The HexBinaryAdapter provides the ability to marshal and unmarshal between String and byte[]. import javax.xml.bind.annotation.adapters.HexBinaryAdapter; public byte[] hexToBytes(String hexString) { HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytes = adapter.unmarshal(hexString); return bytes; } That's just an example I typed in...I actually just use it as is and don't need to make a separate method for using it. A: I've always used a method like public static final byte[] fromHexString(final String s) { String[] v = s.split(" "); byte[] arr = new byte[v.length]; int i = 0; for(String val: v) { arr[i++] = Integer.decode("0x" + val).byteValue(); } return arr; } this method splits on space delimited hex values but it wouldn't be hard to make it split the string on any other criteria such as into groupings of two characters. A: The Code presented by Bert Regelink simply does not work. Try the following: import javax.xml.bind.DatatypeConverter; import java.io.*; public class Test { @Test public void testObjectStreams( ) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); String stringTest = "TEST"; oos.writeObject( stringTest ); oos.close(); baos.close(); byte[] bytes = baos.toByteArray(); String hexString = DatatypeConverter.printHexBinary( bytes); byte[] reconvertedBytes = DatatypeConverter.parseHexBinary(hexString); assertArrayEquals( bytes, reconvertedBytes ); ByteArrayInputStream bais = new ByteArrayInputStream(reconvertedBytes); ObjectInputStream ois = new ObjectInputStream(bais); String readString = (String) ois.readObject(); assertEquals( stringTest, readString); } } A: Here is a method that actually works (based on several previous semi-correct answers): private static byte[] fromHexString(final String encoded) { if ((encoded.length() % 2) != 0) throw new IllegalArgumentException("Input string must contain an even number of characters"); final byte result[] = new byte[encoded.length()/2]; final char enc[] = encoded.toCharArray(); for (int i = 0; i < enc.length; i += 2) { StringBuilder curr = new StringBuilder(2); curr.append(enc[i]).append(enc[i + 1]); result[i/2] = (byte) Integer.parseInt(curr.toString(), 16); } return result; } The only possible issue that I can see is if the input string is extremely long; calling toCharArray() makes a copy of the string's internal array. EDIT: Oh, and by the way, bytes are signed in Java, so your input string converts to [0, -96, -65] instead of [0, 160, 191]. But you probably knew that already. A: In android ,if you are working with hex, you can try okio. simple usage: byte[] bytes = ByteString.decodeHex("c000060000").toByteArray(); and result will be [-64, 0, 6, 0, 0] A: The Hex class in commons-codec should do that for you. http://commons.apache.org/codec/ import org.apache.commons.codec.binary.Hex; ... byte[] decoded = Hex.decodeHex("00A0BF"); // 0x00 0xA0 0xBF A: I found Kernel Panic to have the solution most useful to me, but ran into problems if the hex string was an odd number. solved it this way: boolean isOdd(int value) { return (value & 0x01) !=0; } private int hexToByte(byte[] out, int value) { String hexVal = "0123456789ABCDEF"; String hexValL = "0123456789abcdef"; String st = Integer.toHexString(value); int len = st.length(); if (isOdd(len)) { len+=1; // need length to be an even number. st = ("0" + st); // make it an even number of chars } out[0]=(byte)(len/2); for (int i =0;i<len;i+=2) { int hh = hexVal.indexOf(st.charAt(i)); if (hh == -1) hh = hexValL.indexOf(st.charAt(i)); int lh = hexVal.indexOf(st.charAt(i+1)); if (lh == -1) lh = hexValL.indexOf(st.charAt(i+1)); out[(i/2)+1] = (byte)((hh << 4)|lh); } return (len/2)+1; } I am adding a number of hex numbers to an array, so i pass the reference to the array I am using, and the int I need converted and returning the relative position of the next hex number. So the final byte array has [0] number of hex pairs, [1...] hex pairs, then the number of pairs... A: Based on the op voted solution, the following should be a bit more efficient: public static byte [] hexStringToByteArray (final String s) { if (s == null || (s.length () % 2) == 1) throw new IllegalArgumentException (); final char [] chars = s.toCharArray (); final int len = chars.length; final byte [] data = new byte [len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16)); } return data; } Because: the initial conversion to a char array spares the length checks in charAt A: If you have a preference for Java 8 streams as your coding style then this can be achieved using just JDK primitives. String hex = "0001027f80fdfeff"; byte[] converted = IntStream.range(0, hex.length() / 2) .map(i -> Character.digit(hex.charAt(i * 2), 16) << 4 | Character.digit(hex.charAt((i * 2) + 1), 16)) .collect(ByteArrayOutputStream::new, ByteArrayOutputStream::write, (s1, s2) -> s1.write(s2.toByteArray(), 0, s2.size())) .toByteArray(); The , 0, s2.size() parameters in the collector concatenate function can be omitted if you don't mind catching IOException. A: If your needs are more than just the occasional conversion then you can use HexUtils. Example: byte[] byteArray = Hex.hexStrToBytes("00A0BF"); This is the most simple case. Your input may contain delimiters (think MAC addresses, certificate thumbprints, etc), your input may be streaming, etc. In such cases it gets easier to justify to pull in an external library like HexUtils, however small. With JDK 17 the HexFormat class will fulfill most needs and the need for something like HexUtils is greatly diminished. However, HexUtils can still be used for things like converting very large amounts to/from hex (streaming) or pretty printing hex (think wire dumps) which the JDK HexFormat class cannot do. (full disclosure: I'm the author of HexUtils) A: public static byte[] hex2ba(String sHex) throws Hex2baException { if (1==sHex.length()%2) { throw(new Hex2baException("Hex string need even number of chars")); } byte[] ba = new byte[sHex.length()/2]; for (int i=0;i<sHex.length()/2;i++) { ba[i] = (Integer.decode( "0x"+sHex.substring(i*2, (i+1)*2))).byteValue(); } return ba; } A: My formal solution: /** * Decodes a hexadecimally encoded binary string. * <p> * Note that this function does <em>NOT</em> convert a hexadecimal number to a * binary number. * * @param hex Hexadecimal representation of data. * @return The byte[] representation of the given data. * @throws NumberFormatException If the hexadecimal input string is of odd * length or invalid hexadecimal string. */ public static byte[] hex2bin(String hex) throws NumberFormatException { if (hex.length() % 2 > 0) { throw new NumberFormatException("Hexadecimal input string must have an even length."); } byte[] r = new byte[hex.length() / 2]; for (int i = hex.length(); i > 0;) { r[i / 2 - 1] = (byte) (digit(hex.charAt(--i)) | (digit(hex.charAt(--i)) << 4)); } return r; } private static int digit(char ch) { int r = Character.digit(ch, 16); if (r < 0) { throw new NumberFormatException("Invalid hexadecimal string: " + ch); } return r; } Is like the PHP hex2bin() Function but in Java style. Example: String data = new String(hex2bin("6578616d706c65206865782064617461")); // data value: "example hex data" A: Late to the party, but I have amalgamated the answer above by DaveL into a class with the reverse action - just in case it helps. public final class HexString { private static final char[] digits = "0123456789ABCDEF".toCharArray(); private HexString() {} public static final String fromBytes(final byte[] bytes) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { buf.append(HexString.digits[(bytes[i] >> 4) & 0x0f]); buf.append(HexString.digits[bytes[i] & 0x0f]); } return buf.toString(); } public static final byte[] toByteArray(final String hexString) { if ((hexString.length() % 2) != 0) { throw new IllegalArgumentException("Input string must contain an even number of characters"); } final int len = hexString.length(); final byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16)); } return data; } } And JUnit test class: public class TestHexString { @Test public void test() { String[] tests = {"0FA1056D73", "", "00", "0123456789ABCDEF", "FFFFFFFF"}; for (int i = 0; i < tests.length; i++) { String in = tests[i]; byte[] bytes = HexString.toByteArray(in); String out = HexString.fromBytes(bytes); System.out.println(in); //DEBUG System.out.println(out); //DEBUG Assert.assertEquals(in, out); } } } A: I know this is a very old thread, but still like to add my penny worth. If I really need to code up a simple hex string to binary converter, I'd like to do it as follows. public static byte[] hexToBinary(String s){ /* * skipped any input validation code */ byte[] data = new byte[s.length()/2]; for( int i=0, j=0; i<s.length() && j<data.length; i+=2, j++) { data[j] = (byte)Integer.parseInt(s.substring(i, i+2), 16); } return data; } A: I think will do it for you. I cobbled it together from a similar function that returned the data as a string: private static byte[] decode(String encoded) { byte result[] = new byte[encoded/2]; char enc[] = encoded.toUpperCase().toCharArray(); StringBuffer curr; for (int i = 0; i < enc.length; i += 2) { curr = new StringBuffer(""); curr.append(String.valueOf(enc[i])); curr.append(String.valueOf(enc[i + 1])); result[i] = (byte) Integer.parseInt(curr.toString(), 16); } return result; } A: For Me this was the solution, HEX="FF01" then split to FF(255) and 01(01) private static byte[] BytesEncode(String encoded) { //System.out.println(encoded.length()); byte result[] = new byte[encoded.length() / 2]; char enc[] = encoded.toUpperCase().toCharArray(); String curr = ""; for (int i = 0; i < encoded.length(); i=i+2) { curr = encoded.substring(i,i+2); System.out.println(curr); if(i==0){ result[i]=((byte) Integer.parseInt(curr, 16)); }else{ result[i/2]=((byte) Integer.parseInt(curr, 16)); } } return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/140131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "439" }
Q: How would I raise an event (jQuery or vanilla Javascript) when a popup window is closed? I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed. var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers. UPDATE: I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally. var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); $(popupWindow.window).unload(function() { alert('hello'); }); Does anybody have any idea as to why the unload event could be raised when the window is loading? One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do: popupWindow.onunload = function(){alert('hello')}; It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the popupWindow.closed property inside of the event to ensure the window was really closed. A: I tried the watcher approach but ran in to the "permission denied" issue while using this in IE6. This happens due to the closed property not being fully accessible around the event of closing the window ... but fortunately with a try { } catch construction it works though :o) var w = window.open("http://www.google.com", "_blank", 'top=442,width=480,height=460,resizable=yes', true); var watchClose = setInterval(function() { try { if (w.closed) { clearTimeout(watchClose); //Do something here... } } catch (e) {} }, 200); Thank you magnus A: I think I figured out what's happening: When you use window.open it opens a new window with location "about:blank" and then changes it to the url you provided at the function call. So, the unload event is bound before the change from "about:blank" to the right url and is fired when the changing occurs. I got it working with JQuery doing this: $(function(){ var win = window.open('http://url-at-same-domain.com','Test', 'width=600,height=500'); $(win).unload(function(){ if(this.location == 'about:blank') { $(this).unload(function(){ // do something here }); } }); }); A: The jQuery code example for the unload event $(window).unload( function () { alert("Bye now!"); } ); From the jQuery unload documentation Edit: I played around and was not able to get the parent window to be able to set the unload. The only way I could get it to work, was by having the script present in the popup window html. The popup window also needed to load jQuery. I have nothing to base this on, but I believe the unload is being triggered, because essentially the popup window is being unloaded from the scope of the parent window. Just a guess. A: I created a watcher that checks if the window has been closed: var w = window.open("http://www.google.com", "_blank", 'top=442,width=480,height=460,resizable=yes', true); var watchClose = setInterval(function() { if (w.closed) { clearTimeout(watchClose); //Do something here... } }, 200); A: You'd have to have the onBeforeUnload event call a method to notify your handler. See this page for a demo. https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm A: Use window.onUnload A: There's one tiny catch I have to mention in relation to the previous mentions of onunload based on my previous experience: Opera 9.0.x-9.2.x only runs window.onUnload if the user navigates away from a page. If the user instead closes the window, the event will never fire. I suspect this was done to combat the self-reloading popup problem (where a popup could reopen itself on page close). This has most likely persisted to Opera 9.5.x. Other browsers may also implement this, but I don't believe IE or Firefox do. A: From what I checked the jQuery unload is just a wrapper for the native function. I could be wrong as I didn't dug that deep. This example worked for me. $(document).ready(function(){ $(window).unload( function (){ alert('preget'); $.get( '/some.php', { request: 'some' } ); alert('postget'); }); }); Remember that some browsers block the window.open requests on unload, IE for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/140133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Creating a custom error page in Umbraco CMS I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that. Does anyone know how to create a custom 404 error page in Umbraco? Is there a way to create a custom error page for runtime errors? A: As stated by other posters, modify the errors section as indicated (including culture if needed.) In addition, add the following in the web config to enable passthrough of errors to umbraco: In /config/umbracoSettings.config (the file itself explains its usage): <errors> <!-- the id of the page that should be shown if the page is not found --> <!-- <errorPage culture="default">1</errorPage>--> <!-- <errorPage culture="en-US">200</errorPage>--> <error404>2664</error404> </errors> In /web.config <system.webServer> <!-- Some other existing stuff --> <httpErrors existingResponse="PassThrough" /> </system.webServer> (Note: This is .NET 4) A: umbraco also supports culture dependent error pages in case you're working with multilingual sites... Config changes a tiny bit. Instead of <errors> <error404>1050</error404> </errors> you'd now write <errors> <errorPage culture="default">1</errorPage>--> <errorPage culture="en-US">200</errorPage>--> </errors> Cheers, /Dirk A: In /config/umbracoSettings.config modify <error404>1</error404> "1" with the id of the page you want to show. <errors> <error404>1</error404> </errors> Other ways to do it can be found at Not found handlers A: First create an error page (and template) in your umbraco installation. Let us say error.aspx. Publish it. Then edit config/umbracoSettings.config. Under <errors> section <error404>1111</error404> Where 1111 is the umbraco node ID for the error.aspx page Node ID can be found by hovering mouse on the error node in content section. It's usually a 4 digit number. Then edit the web.config: In <appSettings> section change <customErrors mode as show below: <customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx"/> A: Currently umbracoSettings.conf has to be configured the following way in order to make it work in a multilingual way: <errors> <!-- the id of the page that should be shown if the page is not found --> <!-- <errorPage culture="default">1</errorPage>--> <!-- <errorPage culture="en-US">200</errorPage>--> <error404> <errorPage culture="default">1</errorPage> <errorPage culture="ru-RU">1</errorPage> <errorPage culture="en-US">2</errorPage> </error404> </errors> Please note the error404 element which surrounds the errorPage elements, as well as the comments omitting this small yet important detail...
{ "language": "en", "url": "https://stackoverflow.com/questions/140137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Deleting Windows performance counter categories I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete? A: As far as I know, there is no way to safely delete them except programatically (they're intended for apps to create and remove during install) but it is trivial to do from a PowerShell command-line console. Just run this command: [Diagnostics.PerformanceCounterCategory]::Delete( "Your Category Name" ) HOWEVER: (EDIT) You can delete the registry key that's created, and that will make the category vanish. For a category called "Inventory" you can delete the whole key at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Inventory ... and although I wouldn't be willing to bet that cleans up everything, it will make the category disappear. (If you run Process Monitor while running the Delete() method, you can see can a lot of other activity happening, and there doesn't seem to be any other changes made). It's important to note that as I said originally: when you get that error from Visual Studio, it might be that it's already deleted and you need to refresh the view in VS. In my testing, I had to restart applications in order to get them to actually get a clean list of the available categories. You can check the full list of categories from PowerShell to see if it's listed: [Diagnostics.PerformanceCounterCategory]::GetCategories() | Format-Table -auto But if you check them, then delete the registry key ... they'll still show up, until you restart PowerShell (if you start another instance, you can run the same query over there, and it will NOT show the deleted item, but re-running GetCategories in the first one will continue showing it. By the way, you can filter that list if you want to using -like for patterns, or -match for full regular expressions: [Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -like "*network*" } | Format-Table -auto [Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -match "^SQL.*Stat.*" } | Format-Table -auto A: I know this question if old but I found a way to do this non-programatically: http://msdn.microsoft.com/en-us/library/windows/desktop/aa372130%28v=vs.85%29.aspx Use unlodctr from command prompt, you might also need to use lodctr /q to query your category. Or do it the hard way by modifying the registry key (don't delete it): HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 http://msdn.microsoft.com/en-us/library/windows/desktop/aa373172%28v=vs.85%29.aspx A: You could also use LinqPad, as that doesn't involve an install of any kind - http://www.linqpad.net/. Run the following code as a "C# Statement(s)": System.Diagnostics.PerformanceCounterCategory.Delete("Name of category to delete"); I'd run it twice, first time to do the actual delete, second time to get an error message to confirm the delete was successful. A: You could disable it using the microsoft resource kit tool - install it from http://download.microsoft.com/download/win2000platform/exctrlst/1.00.0.1/nt5/en-us/exctrlst_setup.exe or disable it from the registry manually (have not tried) described here http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/94214.mspx?mfr=true
{ "language": "en", "url": "https://stackoverflow.com/questions/140149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: How to access Subversion from Oracle PL/SQL? For a governmental agency, we build a release management system developped in PHP and Oracle. The data for this application is stored in database tables and is processed with PL/SQL packages and procedures. The release management process is extensively based on metadata coming from Subversion repositories. We access the repositories from PL/SQL through the internal Oracle JVM to execute svn commands on the unix server on which resides the Oracle instances. The results from svn commands are received in XML and parsed before beeing processed by PL/SQL. Accessing Subversion this way is not very performant for frequent repeated use. Currently, what we do is storing the Subversion metadata in database tables at each commit in the Subversion repositories (via Subversion hooks). We extract the log information for each Subversion transaction and keep it in some oracle tables. We are then able to obtain Subversion metadata with normal SQL queries. Is there better ways to access Subversion from PL/SQL ? A: If your using Oracle's Java JVM, you could try to use SVNKit to communicate with the SVN server nativly from Java, instead of shelling out to the operating system to execute commands. A: I think the basic flow makes sense. I would recommend doing experiments to see where exactly the performance bottlenecks are and then take if from there. For example, is it crossing from PL/SQL to Oracle JVM? Is it JVM shelling out to execute the svn command? Is it the svn round trip? Is it the parsing of the XML? Let's say, for example, it's the svn round trip. Maybe you could have a process on the oracle machine that caches answers from the svn server so that at times the round trip could be avoided? Maybe the svn round trip could be async? But, like I said, you need to know where the bottleneck is. A: I'm also looking for an API to integerate Subversion and Oracle. I need to be able to pull Oracle PL/SQL objects (procedures, packages) into Subversion and then once changes are made to objects it should be applied to those objects in Oracle database. A: One more solution is to use software which stays between ORACLE and SVN and synchronizes PL/SQL with sources. Here is one of these programs which can be started by cron: https://sourceforge.net/projects/dbcode-svn-sync/ .
{ "language": "en", "url": "https://stackoverflow.com/questions/140153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What triggers ConstraintException when loading DataSet? How can I find out which column and value is violating the constraint? The exception message isn't helpful at all: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. A: When you use a strong typed dataset and used the visual designer (xsd): to access tbl.Rows[0].RowError information, you need to create the Fill method. You can't use the Get method, since the DataTable is instanced within generated code. A: For googlers who want a snippet to get more details on the ConstraintException: try { ds.EnforceConstraints = true; } catch (ConstraintException ex) { string details = string.Join("", ds.Tables.Cast<DataTable>() .Where(t => t.HasErrors) .SelectMany(t => t.GetErrors()) .Take(50) .Select(r => "\n - " + r.Table.TableName + "[" + string.Join(", ", r.Table.PrimaryKey.Select(c => r[c])) + "]: " + r.RowError)); throw new ConstraintException(ex.Message + details); } A: Like many people, I have my own standard data access components, which include methods to return a DataSet. Of course, if a ConstraintException is thrown, the DataSet isn't returned to the caller, so the caller can't check for row errors. What I've done is catch and rethrow ConstraintException in such methods, logging row error details, as in the following example (which uses Log4Net for logging): ... try { adapter.Fill(dataTable); // or dataSet } catch (ConstraintException) { LogErrors(dataTable); throw; } ... private static void LogErrors(DataSet dataSet) { foreach (DataTable dataTable in dataSet.Tables) { LogErrors(dataTable); } } private static void LogErrors(DataTable dataTable) { if (!dataTable.HasErrors) return; StringBuilder sb = new StringBuilder(); sb.AppendFormat( CultureInfo.CurrentCulture, "ConstraintException while filling {0}", dataTable.TableName); DataRow[] errorRows = dataTable.GetErrors(); for (int i = 0; (i < MAX_ERRORS_TO_LOG) && (i < errorRows.Length); i++) { sb.AppendLine(); sb.Append(errorRows[i].RowError); } _logger.Error(sb.ToString()); } A: There is a property called RowError you can check. See http://dotnetdebug.net/2006/07/16/constraintexception-a-helpful-tip/ Edited to add this link showing iteration of rows to see which had errors. http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic58812.aspx A: I added some code that I've found to be useful in debugging ConstraintException occurrences here Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/140161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: java.lang.String in jndi default context with Apache Geronimo - How? In a servlet I do the following: Context context = new InitialContext(); value = (String) context.lookup("java:comp/env/propertyName"); On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key propertyName? In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web. A: One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more <env-entry> tags. For example, something like the following: <env-entry> <description>My string property</descriptor> <env-entry-name>propertyName</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Your string goes here</env-entry-value> </env-entry> Each env-entry tag declares a new environment variable that you can then access from the java:comp/env context. Once you add the necessary env-entry's you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work. A: It is possible to put your properties in a file and make the name and location of the file a resource-ref of type URL in web.xml. The value of the resource is set in geronimo-web.xml. Your web.xml will have the following entry: <resource-ref> <res-ref-name>configFileName</res-ref-name> <res-type>java.net.URL</res-type> </resource-ref> In geronimo-web.xml you define the value for the configFileName <name:resource-ref> <name:ref-name>configFileName</name:ref-name> <name:url>file:///etc/myConfigFile</name:url> </name:resource-ref> In java you have the following code to lookup the value: initialContext = new InitialContext(); URL url = (URL) initialContext.lookup("java:comp/env/configFileName"); String configFileName = url.getPath(); Then you have to open the file and read whatever value is in there. The result of all this is that you have the properties in a file on the filesystem. It will not be overwritten if you redeploy your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/140162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regular expressions but for writing in the match When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... Right now I'm doing this... def getExpandedText(pattern, text, replaceValue): """ One liner... really ugly but it's only used in here. """ return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \ text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):] so if I do sth like >>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo") 'hola aaaooobbb como estas?' It changes the (...) with 'ooo'. Do you guys know whether with python regular expressions we can do this? thanks a lot guys!! A: sub (replacement, string[, count = 0]) sub returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged. p = re.compile( '(blue|white|red)') >>> p.sub( 'colour', 'blue socks and red shoes') 'colour socks and colour shoes' >>> p.sub( 'colour', 'blue socks and red shoes', count=1) 'colour socks and red shoes' A: You want to use re.sub: >>> import re >>> re.sub(r'aaa...bbb', 'aaaooobbb', "hola aaaiiibbb como estas?") 'hola aaaooobbb como estas?' To re-use variable parts from the pattern, use \g<n> in the replacement string to access the n-th () group: >>> re.sub( "(svcOrdNbr +)..", "\g<1>XX", "svcOrdNbr IASZ0080") 'svcOrdNbr XXSZ0080' A: Of course. See the 'sub' and 'subn' methods of compiled regular expressions, or the 're.sub' and 're.subn' functions. You can either make it replace the matches with a string argument you give, or you can pass a callable (such as a function) which will be called to supply the replacement. See https://docs.python.org/library/re.html A: If you want to continue using the syntax you mentioned (replace the match value instead of replacing the part that didn't match), and considering you will only have one group, you could use the code below. def getExpandedText(pattern, text, replaceValue): m = re.search(pattern, text) expandedText = text[:m.start(1)] + replaceValue + text[m.end(1):] return expandedText A: def getExpandedText(pattern,text,*group): r""" Searches for pattern in the text and replaces all captures with the values in group. Tag renaming: >>> html = '<div> abc <span id="x"> def </span> ghi </div>' >>> getExpandedText(r'</?(span\b)[^>]*>', html, 'div') '<div> abc <div id="x"> def </div> ghi </div>' Nested groups, capture-references: >>> getExpandedText(r'A(.*?Z(.*?))B', "abAcdZefBgh", r'<\2>') 'abA<ef>Bgh' """ pattern = re.compile(pattern) ret = [] last = 0 for m in pattern.finditer(text): for i in xrange(0,len(m.groups())): start,end = m.span(i+1) # nested or skipped group if start < last or group[i] is None: continue # text between the previous and current match if last < start: ret.append(text[last:start]) last = end ret.append(m.expand(group[i])) ret.append(text[last:]) return ''.join(ret) Edit: Allow capture-references in the replacement strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/140182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best method to have a C++ member function get called by a C callback ? Given a typical class: struct Whatever { void Doit(); }; Whatever w; what is the best way to get the member function to be called by a C void* based callback such as pthread_create() or a signal handler ? pthread_t pid; pthread_create(&pid, 0, ... &w.Doit() ... ); A: Most C callbacks allow to specify an argument e.g. int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); So you could have void myclass_doit(void* x) { MyClass* c = reinterpret_cast<MyClass*>(x); c->doit(); } pthread_create(..., &myclass_doit, (void*)(&obj)); A: The most concise solution is to define, in a header file shared by all your code: template <typename T, void (T::*M)()> void* thunk( void* p) { T* pt = static_cast<T*>(p); (pt->*M)(); return 0; } You probably want to define 4 versions: one each where the thunk returns void and void*, and one each where the member function returns void and void*. That way the compiler can match the best one, depending on the circumstances (and in fact it will complain if everything doesn't match.) Then all you have to type every time you run into one of these situations is: pthread_create(&pid, 0, &thunk<Whatever, &Whatever::doit>, &w); This will even work when the method is private, as long as the method is referenced from within the class's code. (If not, I have to wonder why the code is referencing a private method.) A: Use a C-function wrapper like this: struct Whatever { void Doit(); }; extern "C" static int DoItcallback (void * arg) { Whatever * w = (Whatever *) arg; w->DoIt(); return something; } Only works if you can pass the pointer to the class somehow. Most callback mechanisms allow this. Afaik this is the only method to do this. You can't directly call a method from C without lots of hacking. A: Is the member function private? If not, use the standard idiom: void* pthread_foo_caller(void* arg) { Foo* foo = static_cast<Foo*>(arg); foo->bar(); return NULL; } If the member function is private, you can declare a static method in the class that takes a "this" pointer and calls the appropriate method. For example: class Foo { public: static pthread_foo_caller(void* arg); ... }; void* Foo::pthread_foo_caller(void* arg) { Foo* foo = static_cast<Foo*>(arg); foo->private_bar(); return NULL; } A: The member function MUST be static. Non-static have an implied "this" argument. Pass the pointer to your Whatever instance as the void* so that the static member can get at the instance. A: Here's a simple way to do it, don't forget to manage the lifetime of your "MemberFunction" object properly. #include class MyClass { public: void DoStuff() { printf("Doing Stuff!"); } }; struct MemberFunction { virtual ~MemberFunction(){} virtual void Invoke() = 0; }; void InvokeMember(void *ptr) { static_cast(ptr)->Invoke(); } template struct MemberFunctionOnT : MemberFunction { typedef void (T::*function_t)(); public: MemberFunctionOnT(T* obj, function_t fun) { m_obj = obj; m_fun = fun; } void Invoke() { (m_obj->*m_fun)(); } private: T *m_obj; function_t m_fun; }; template MemberFunction* NewMemberFunction(T *obj, void (T::*fun)()) { return new MemberFunctionOnT(obj, fun); } //simulate a C-style function offering callback functionality. void i_will_call_you_later(void (*fun)(void*), void *arg) { fun(arg); } int main() { //Sample usage. MyClass foo; MemberFunction *arg = NewMemberFunction(&foo, &MyClass::DoStuff); i_will_call_you_later(&InvokeMember, arg); return 0; } A: One thing you should be aware of is that if you write code like this: try { CallIntoCFunctionThatCallsMeBack((void *)this, fCallTheDoItFunction); } catch (MyException &err) { stderr << "badness."; } void fCallTheDoItFunction(void *cookie) { MyClass* c = reinterpret_cast<MyClass*>(cookie); if (c->IsInvalid()) throw MyException; c->DoIt(); } You may run into some serious trouble depending on your compiler. It turns out that in some compilers while optimizing, they see a single C call in a try/catch block and exclaim with joy, "I am calling a C function that, because it is good old fashioned C, cannot throw! Calloo-cally! I shall remove all vestiges of the try/catch since it will never be reached. Silly compiler. Don't call into C that calls you back and expect to be able to catch. A: See this link Basically, it's not directly possible, because: "Pointers to non-static members are different to ordinary C function pointers since they need the this-pointer of a class object to be passed. Thus ordinary function pointers and [pointers to] non-static member functions have different and incompatible signatures" A: While I haven't used it from C, for doing callbacks, I highly recommend looking at libsigc++. It's been exactly what I've needed a number of times when doing C++ callbacks.
{ "language": "en", "url": "https://stackoverflow.com/questions/140204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Combining split date ranges in a SQL query I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like StudentID StartDate EndDate Field1 Field2 1 9/3/2007 10/20/2007 3 True 1 10/21/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like StudentID StartDate EndDate Field1 Field2 1 9/3/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True What would be the SELECT statement for this query? A: The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should point you in the right direction. You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer. CREATE VIEW dbo.StudentStartDates AS SELECT S.StudentID, S.StartDate, S.Field1, S.Field2 FROM dbo.Students S LEFT OUTER JOIN dbo.Students PREV ON PREV.StudentID = S.StudentID AND PREV.Field1 = S.Field1 AND PREV.Field2 = S.Field2 AND PREV.EndDate = DATEADD(dy, -1, S.StartDate) WHERE PREV.StudentID IS NULL GO CREATE VIEW dbo.StudentEndDates AS SELECT S.StudentID, S.EndDate, S.Field1, S.Field2 FROM dbo.Students S LEFT OUTER JOIN dbo.Students NEXT ON NEXT.StudentID = S.StudentID AND NEXT.Field1 = S.Field1 AND NEXT.Field2 = S.Field2 AND NEXT.StartDate = DATEADD(dy, 1, S.EndDate) WHERE NEXT.StudentID IS NULL GO SELECT SD.StudentID, SD.StartDate, ED.EndDate, SD.Field1, SD.Field2 FROM dbo.StudentStartDates SD INNER JOIN dbo.StudentEndDates ED ON ED.StudentID = SD.StudentID AND ED.Field1 = SD.Field1 AND ED.Field2 = SD.Field2 AND ED.EndDate > SD.StartDate AND NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate) GO A: In my experience, I have to combine the ranges in post-processing (not in SQL but in my script). I'm not sure that a SQL can do this, particularly because you can never know exactly how many date ranges need to be chained in any particular case. If this can be done though, I'd love to know too. EDIT: My answer is assuming that you have more than one range of dates per student, not just a start and an end. If you only have the one date range with no gaps, then the other mentioned solutions are the way to go. A: SELECT StudentID, MIN(startdate) AS startdate, MAX(enddate), field1, field2 FROM tablex GROUP BY StudentID, field1, field2 That would yield you the result assuming the wasn't a gap between on student's time range. A: select StudentID, min(StartDate) StartDate, max(EndDate) EndDate, Field1, Field2 from table group by StudentID, Field1, Field2 A: If the min()/max() solutions are not good enough (e.g. if the dates are not contiguous and you want to group separate date ranges separately), I wonder if something using Oracle's START WITH and CONNECT BY clauses would work. Which, of course, wouldn't work on every database. A: EDIT: Make another set of SQL for Access. I tested all of this, but piece by piece because I don't know how to make several statements at one time in Access. Since I also don't know how to do comments, you can see the comments in the SQL version, below. select studentid, min(startdate) as Starter, max(enddate) as Ender, field1, field2, max(startDate) - Min(endDate) as MaxGap into tempIDs from student group by studentid, field1, field2 ; delete from tempIDs where MaxGap > 1; UPDATE student INNER JOIN TempIDs ON Student.studentID = TempIDS.StudentID SET Student.StartDate = [TempIDs].[Starter], Student.EndDate = [TempIDs].[Ender]; I think this is it, in SQL Server - I didn't do it in Access. I haven't tested it for fancy conditions such as overlapping several records, etc., but this should get you started. It updates all the duplicate, small-gap records, leaving extras in the database. MSDN has a page on eliminating duplicates: http://support.microsoft.com/kb/139444 select studentid, min(startdate) as StartDate, max(enddate) as EndDate, field1, field2, datediff(dd, Min(endDate),max(startDate)) as MaxGap into #tempIDs from #student group by studentid, field1, field2 -- Update the relevant records. Keeps two copies of the massaged record -- - extra will need to be deleted. update #student set startdate = #TempIDS.startdate, enddate = #tempIDS.EndDate from #tempIDS where #student.studentid = #TempIDs.StudentID and MaxGap < 2 A: Have you considered a non-equi join? That would look something like this: SELECT A.StudentID, A.StartDate, A.EndDate, A.Field1, A.Field2 FROM tblEnrollment AS A LEFT JOIN tblEnrollment AS B ON (A.StudentID = B.StudentID) AND (A.EndDate=B.StartDate-1) WHERE B.StudentID Is Null; What that gives you is all the records that don't have a corresponing record that starts the day after the ending date of the first record. [Caveat: Beware that you can only edit a non-equi join in the Access query designer in SQL View -- switching to Design View could cause the join to be lost (though if you do switch Access tells you about the problem, and if you immediately switch back to SQL View, you won't lose it)] If you then UNION that with this: SELECT A.StudentID, A.StartDate, B.EndDate, A.Field1, A.Field2 FROM tblEnrollment AS A INNER JOIN tblEnrollment AS B ON (A.StudentID = B.StudentID) AND (A.EndDate= B.StartDate-1) It should give you what you need, assuming there are never more than two contiguous records at a time. I'm not sure how you'd do it if you had more than two contiguous records (it might involve looking at StartDate-1 compared to EndDate), but this might get you started in the right direction. A: An alternate final query to the one provided by Tom H. in the accepted answer is SELECT SD.StudentID, SD.StartDate, MIN(ED.EndDate), SD.Field1, SD.Field2 FROM dbo.StudentStartDates SD INNER JOIN dbo.StudentEndDates ED ON ED.StudentID = SD.StudentID AND ED.Field1 = SD.Field1 AND ED.Field2 = SD.Field2 AND ED.EndDate > SD.StartDate GROUP BY SD.StudentID, SD.Field1, SD.Field2, SD.StartDate This also worked on all test data. A: Heres an example with test data using SQL Server 2005/2008 syntax. DECLARE @Data TABLE( CalendarDate datetime ) INSERT INTO @Data( CalendarDate ) -- range start SELECT '1 Jan 2010' UNION ALL SELECT '2 Jan 2010' UNION ALL SELECT '3 Jan 2010' -- range start UNION ALL SELECT '5 Jan 2010' -- range start UNION ALL SELECT '7 Jan 2010' UNION ALL SELECT '8 Jan 2010' UNION ALL SELECT '9 Jan 2010' UNION ALL SELECT '10 Jan 2010' SELECT DateGroup, Min( CalendarDate ) AS StartDate, Max( CalendarDate ) AS EndDate FROM( SELECT NextDay.CalendarDate, DateDiff( d, RangeStart.CalendarDate, NextDay.CalendarDate ) - ROW_NUMBER() OVER( ORDER BY NextDay.CalendarDate ) AS DateGroup FROM( SELECT Min( CalendarDate ) AS CalendarDate FROM @data ) AS RangeStart JOIN @data AS NextDay ON NextDay.CalendarDate >= RangeStart.CalendarDate ) A GROUP BY DateGroup A: This is a classic problem in SQL (the language) e.g. covered in Joe Celko's books 'SQL for Smarties" (chapter 23, Regions, Runs, Gaps, Sequences and Series) and his latest book "Thinking in Sets" (chapter 15). While it's 'fun' to fix the data at run time with a monster query, for me this is one of those situations that can be better fixed off line and procedurally (personally I'd do it with formulas in an Excel spreadsheet). The important thing is to put in place effective database constraints to prevent the overlapping periods reoccurring. Again, writing sequenced constraints in SQL is a classic: see Snodgrass (http://www.cs.arizona.edu/people/rts/tdbbook.pdf). Hint for MS Access users: you'll need to use CHECK constraints.
{ "language": "en", "url": "https://stackoverflow.com/questions/140205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you use gdb to debug your code? As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier? A: Some hints: * *use a graphical frontend (kdbg is quite good, ddd is at least better than command-line gdb, kdevelop has a nice gdb frontend but has some bgs, nemiver looks quite nice as well but is still in the works) *make sure to have debug symbols and source code for all important parts (your own code and also some system libs) * *on RedHat, you can install the -debuginfo packages to make both symbols and source code magically appear in the debugger - really cool because you can looks into libc function calls etc. *on Debian/Ubuntu, you can install the -dbg packages to get symbols; installing appropriate source files for system packages seems to be difficult, though *I tend to add assert() and abort() calls in places that should not be reached, or in places that I want to study (some kind of heavy-weight breakpoint) *ideally the assert() or abort() calls should be wrapped in some method or macro that only enables them in Debug releases, or even better that only enables them if a certain env var is set *install a signal handler for SIGSEGV and SIGABRT; personally I check if a certain env var is set before installing the handlers; and in the handler I execute a hardcoded external command which usually lives somewhere in ~/.local/bin/; that command might then start kdbg and attach it to the crashing app. Voila, debugger pops up the moment your app does something bad. *If you use unit tests, you could similarly attach a debugger whenever a test case fails, to inspect the app then. A: In general you find something that isn't how it should be, and work backwards until you understand why. The most obvious is the most useful: Setting a breakpoint on a function or line number and walking through the code line by line. Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb: gdb> p show_my_struct(struct) My custom display of Foo: ... Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.: gdb> watch foo Watchpoint4: foo gdb> A: One particularly useful feature of gdb is its ability to inspect the final state of a program that's crashed. To inspect a crash dump (or core file, as it's more commonly called), start gdb as follows: gdb <program-name> <core-file> For example: gdb a.out core Upon running this command on a core file, gdb will tell you how the program terminated and display where in the program the error occurred: Program terminated with signal 11, Segmentation fault. #0 0x08048364 in foo () at foo.c:4 4 *x = 100; In the example above, you can see that the program terminated with a segmentation fault while trying to assign a value to a pointer. By typing backtrace (or bt or where) at gdb's prompt, you can view the program's complete backtrace: (gdb) backtrace #0 0x08048364 in foo () at foo.c:4 #1 0x0804837f in main () at foo.c:9 At this point, you know that main() called foo() and foo() crashed on line 4 while trying to assign a value to *x. Many times, this provides enough information to allow you to fix the bug. A: You can also use Geany. A: I do a lot of parallel-program dev, so I've found that using a simple wrapper in python/ruby that allows me to have gdb attached to all processes on all nodes and communicating back to me is extraordinarily helpful (I haven't found a better way if anyone knows of one, not to hijack the thread, though...) I'm not sure how experienced the OP is, so: The GDB docs are pretty nice and all encompassing. The first chapter is a good introduction to all the basics. http://www.gnu.org/software/gdb/documentation/ Although not gdb, they are related: I've personally found that breaking complex lines down to aid in determining which statements are erroring helps. Also, Valgrind (http://valgrind.org/) is really nice/usefull for tackling buffer-overflows and the like (I haven't had luck with gdb for doing this. A: Basic but very useful - Use the text gui with the option -tui. A: Use ddd, a visual front-end for gdb. It lets you do things easily with a few mouse clicks and visualise how the code works, plus in the debugger console you have an intercative gdb.
{ "language": "en", "url": "https://stackoverflow.com/questions/140217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Reusable code / class Repositories I've got several modules containing functions, classes and templates that I keep in a directory called (hah!) 'reuse'. I know the content reasonably well, so to find a particular class or bit of code doesn't take too long, but it is slowly growing in size and I need some sensible method to store them for easy search & retrieval. How should I do this? A related question can be found here: full text search for source code A: * *Group the sources by area of use (network, security, text processing, etc); best in directories for easier browsing. *Tag functions by adding keywords into the source documentation. Use an appropriate comment markup system (like javadoc) and create some kind of indexable docs. *Search by using some kind of full text search (grep -r, google desktop) on your sources. A: Usually, I group my files depending on the general purpose of the files. Ex: Reuse\Database Reuse\Graphics Reuse\Math Reuse\Etc... You can then sub-group your groups Reuse\Graphics\2D Reuse\Graphics\3D HTH A: Depends on the system, but the moment the amount of reusable could reaches a certain threshold I tend to try to convert logical chunks of it into "real" libraries in the same sense like you would use from 3rd parties (with documentation etc.) and put them into the respective library path, so that they become truly reusable. If you don't mind giving them away under some OSS license, you could even go as far as putting them into the CPAN/PyPI/PEAR-equivalent of whatever environment you're working with. This adds even more reuseability. I guess the important part still is that you bundle your code into real libraries. Then the retrieval part should be much easier since mostly automatic. A: You can divise all you classes in directories. What language is for the question? Because .Net you could have a librairy like a DLL divised with namespace. A: * *Group the functions/classes/templates into modules/directories by function. Pretend you'll be releasing them as open-source libraries; consider how you would want someone else's code to be organized. Eventually, it will be someone else's code: you, a year or two ago. *Use a documentation system. Doxygen will generate a handy HTML code browser for you. A: Had a debate on this a while ago. Standard folderization of your code is good for readability and organization, but when you want to just grab things, the one other way is to use tagging somehow (like by adding tags to the file names or other meta data). Tags work good in the place of folders because you can dig up specific or general things quickly, whereas with folders you need to dig through trees to get specific stuff. Tags: O(n). Folders: O(n^2) Maybe. :P A: Folderization according to language (subdivided into function), with tags, in a VCS'd directory, with Doxygen/Perldoc/*Pod/*-extracted documentation. You'll have an easily greppable archive of reusable modules/documentation instantly portable into your working ./ A: This question covers much the same ground & I'll close this question in it's favor.
{ "language": "en", "url": "https://stackoverflow.com/questions/140224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which issue trackers support sub-tickets, and how well do they work for bridging the gap between project managers and developers? There's a feature that I'd like to see in issue tracking software that just doesn't seem to be all that common, and that is the ability to divide a ticket (bug, feature request, etc) into sub-tasks and view them in a hierarchical fashion, perhaps with some kind of progress bar style report of progress on a particular ticket and its child tickets. My thinking is that this would be useful for both developers and project managers: project managers like to have a fairly broad overview of what is going on, whereas developers need to drill down to the details, and very often need to divide a task into sub-tasks. This would also come in handy if someone put two issues into one ticket. Does anyone know of an issue tracker which does this? So far the ones I've looked at (Trac, FogzBugz, and Basecamp) all have a flat organisation of tickets, so they're either useful for the developers or for the project managers but not for both. Assembla does allow a ticket to have child tickets (and multiple parent tickets) but it doesn't do a very good job of usability on this specific feature. If there is such an issue tracker, has anyone used it for both developers and project managers, and if so, how much success did you have with it? Alternatively, is there a better approach that can be usable by both categories of users? (Update: This is not a subjective "what is your favourite bug tracking software" question. I am asking about bug trackers with a specific feature for a specific purpose, so please don't post your favourite bug tracker if it doesn't do what I've asked for. The only arguably subjective element is how well it works for this particular purpose.) A: You want version 7 of Fogbugz. This support multi-levels of hierachy and shows it in a treeview. A: JIRA has the ability to break tasks down into arbitrary sub-tasks, like you're after. It's also super-shiny, so project-manager-types should like it. A: There is a lengthy discussion about bug trackers here. I like Mantis, myself. A: Mantis does have relationships between issues, like parent, child, related etc. It does not exactly have a tree view, but it does show the related/parent/child issues ina list when you are viewing an issue. Having tried trac and Mantis, Its my personal fav A: Well, we've used TestTrack for years now, which supports hierarchical linking between items. It's project management UI is nothing to write home about however. It seems as though you're looking for something more like @Task, where you create a project plan using a system similar to Microsoft Project, with future tasks depending on previous tasks, etc. The UI is pretty slick, but when you get to the bug tracker you're pretty much back in "glorified spreadsheet" mode - i don't get the impression this was really designed by or for programmers. Still, might be worth a look if you're really serious about needing this. IMHO, the problem with adding a hierarchy to your tracking system is that issues do not naturally have a hierarchy when they're added; someone in QA finds a regression, or a user calls in from the field, and an issue gets created. Until at least some research is done into the root cause of the problem, the issue is stand-alone, and chances are, it'll be stand-alone until it's fixed unless it's identified as dependent on some larger project... for which there is likely already some sort of a project management system in place. A: redmine and chilliproject support subtasks without any extra plugins. A: JIRA A: Based on one of the other answers I've had a look at Jira, which goes part of the way towards doing what I'm looking for and seems to work reasonably well, though it isn't quite as slick as I'd hoped. However, it only allows sub-tasks in the Professional and Enterprise versions; this feature is disabled by default; and you only get a single level of sub-tasks. The default reports also list top level tasks as well as sub-tasks together in a flat view, so you have to specifically create a custom report if you want to view just the top level ones. Another feature that I intend to investigate when I get a chance is Mantis, which apparently has similar functionality. I will update here once I've tried it. A: Rally supports both dev and project management views http://www.rallydev.com/ A: Tele-Support HelpDesk has a very good and easy to use bug tracking system that also has the benefit of exposing it to the support department to link customers to the issues and then notify the customers when the issues are complete. I live in it daily, and have found the workflow to be extremely productive. Management always knows whats currently in progress, what was just fixed, and what issues are hot (and even how long something should take to get fixed). It has a very good customizable priority system. Each issue can have a category and product assigned to it and at a button click will be organized to that list. There is a quick filter option, and the ability to do even finer filtering. With estimated time to completion it auto calcs total completion on the fly based on what is currently visible in the list. our Typical Workflow: Bugs are entered into the system by the support staff/QA Staff. Management reviews the list of "new" bugs and sets the priority they would want them done in. Development staff looks at priority list and sets estimated effort levels. Management reviews and adjusts priority. Development completes issues. QA verifies completed issues and notifies customer upon successful update posting. At all stages, any one in the staff can look at the list and see what the current status is, and even add notes or attach another customer to the problem. There are fields for release version, which we use with a custom filter / report to auto generate our release notes. (screen shot of open known issue: which is the bug tracking portion of the product). A: FogBugz is the issue tracker made by Joel Spolsky's company FogCreek. Its not free, but there's a hosted version that is pretty nice. From my own personal experience it has some excellent features and it's easy to use. It certainly looks nicer and has better usability than mantis or bugzilla, but it's not open, and it makes some tradeoffs for a simpler interface. A: TUTOS. It even does Project Management activities at the top. Workflow, Wiki, it is pretty good. www.tutos.org A: I've used Mantis in many organistions and particularly because of the sub-issue feature which is one of my key points I look for in an issue-tracker. They have Freemind export in Mantis now but I'm sure I've seen parent-child diagrams drawn at one site, maybe because they installed JpGraph. I'm also using the free single-user install of Axosoft's OnTime system which has very flexible sub-issue entry although the UI is a little clunky - you have to search for issues rather than being able to specify a given issue number directly as the target of the relationship. OTOH it allows you to configure a bunch of relationships in one hit in the dialog so is quicker in that scenario. A: Bugzilla has the notion of dependent bugs, which isn't exactly the sub-task paradigm you are looking for, but can be viewed as close. Unfortunately, the interface for this is quite clunky, as is the rest of the Bugzilla interface, but it does get the job done. On the positive side, the relationships among bugs can be presented as a graph as well as a fairly easy-to-traverse tree structure to allow for exploring related issues. Additionally, as sub-issues are completed or change, those changes get percolated up the dependency tree so that those responsible for the higher-level tasks are easily notified that things they may have been waiting on are completed. A: JIRA integrated with Pivotal Tracker. JIRA allows for tickets. It gives JQL filter ability for search. Gives ability to share tickets between groups. Gives ability for workflow diagrams, history, transitions, comments, etc. Gives ability to view reporters, assignees, implementers. For each ticket there's ability to add Comments, Attachments, Attach Screenshots, Link, Clone, Resolve Issue. JIRA provides a very nice layout of the current ticket state. Pivotal Tracker allows "velocity" management of project for Agile Development. Useful for PMs and developers. Provides graphs, charts. Provides ability to integrate JIRA's tickets into its project. Provides a dashboard with projects. Provides real-time velocity graphs. Provides a number of views within each project including Current, Ice Box, My Work. Each JIRA ticket can be a "Story" in PT. Each story goes through Start, Finish, Deliver, Accept/Reject, and Rejected stages for SDLC. Each story gives ability to Add Task, Comments, Attachments, and Upload Files. JIRA workflow Pivotal Tracker workflow
{ "language": "en", "url": "https://stackoverflow.com/questions/140236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Targeting .NET Framework 3.5, Using .NET 2.0 Runtime. Caveats? I'm developing an application that is targeting the .NET 3.5 Framework. The application's setup installs the .NET 2.0 runtime on the target machine. So far I haven't had any issues with doing this, but I'm wondering what problems I'm going to have down the line. Do I need to be installing the 3.5 runtime? I must package the .NET runtime installer into our installation (no network install). The size of the runtime installer is the issue. The .NET 2.0 runtime installer is 23MBs (manageable), the .NET 3.0 runtime installer is 50MBs (getting big) and the .NET 3.5 runtime installer is 200MBs (yikes!). What the heck is in those extra 170MBs? A: This is a tough question to answer, because ultimately it depends on what .NET 3.5 features you are using. If you are using some of the new libraries, such as LINQ, then yes, you'll need to install the 3.5 runtimes. However, if you are just using some of the new syntatic sugars introduced in 3.5, you may not. The reason for this is that .NET 3.5 is 100% compatible with the 2.0 CLR. A: If it's a client app that doesn't use asp.net etc you may be able to use the .Net Client Profile install which is much smaller (c. 26MB) - further details at: http://blogs.msdn.com/bclteam/archive/2008/05/21/net-framework-client-profile-justin-van-patten.aspx http://www.hanselman.com/blog/SmallestDotNetOnTheSizeOfTheNETFramework.aspx A: If you're referencing 3.5 specific libaries such as System.Core or System.Xml.Linq then you'll need to ship 3.5. A: there is some différence in the generated code part of datasets between 3.5 SP1 and 3.5 (no sp), something about serialization. you may have trouble with this if you upgrade your installation to 3.5SP1, even in the core functionalities. A: .NET 3.5 is not literary 100% compatible with .NET 2.0, but with .NET 2.0 SP1. But I don't know if that will give you any problems. The .NET 2.0 SP1 update is said to be made to make Extension Methods and maybe Automatic Properties available (don't remember specifics). Scott Hanselman has a good blog post on this. As for the size of the .NET 3.5 deployable file is that it's .NET 2.0, 3.0 and 3.5 for x86, x64 and the other 64-bit architecture in one big file.
{ "language": "en", "url": "https://stackoverflow.com/questions/140239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Will the Javascript performance improvements from Trace Trees find their way into other interpreted languages? It sounds like Mozilla is having good luck improving JavaScript performance with TraceMonkey. See also Andreas Gal's paper on Trace Trees. Are these improvements available to other interpreters/compilers and if so, does this mean we'll see a cascade of improvements in other interpreted languages? A: There's a research JVM by Andreas Gal called HotPath, and some people from his team are currently working on adding nested trace tree based JITting to Maxine (Sun's new research JVM written in Java) and HotSpot. So, at least it is showing up in other VMs for other languages as well. Also, the new PyPy JIT compiler (currently being prototyped in Prolog) uses some kind of tracing technique, although I don't know how closely related that is to Gal/Franz style nested trace trees. The Rubinius guys are definitely aware of this work, and very open to experimentation. I wouldn't be surprised, if some advanced compilation techniques start showing up there, soon. BTW: there is a Ruby VM written in JavaScript, called HotRuby. If you run that on TraceMonkey, you get trace tree based Ruby for free :-) A: The only possible answer to this is: Hopefully!
{ "language": "en", "url": "https://stackoverflow.com/questions/140241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I simulate ext3 filesystem corruption? I would like to simulate filesystem corruption for the purpose of testing how our embedded systems react to it and ultimately have them fail as gracefully as possible. We use different kinds of block device emulated flash storage for data which is modified often and unsuitable for storage in NAND/NOR. Since I have a pretty good idea of how often data is modified in different parts of the file tree and where sensitive data is stored. I would like to inject errors in specific areas and not just randomly. In cases of emergency we use fsck -y as a sort of last resort in order to attempt to bring the system up and report that is in a very bad state. I would very much like to cause errors which would trigger fsck to attempt repairs in order to study the effect on the systems capability to come back up. dd if=/dev/random is not precise enough for my purpose since it can't easily be used to inject controlled errors. Are there any other tools or methods which fit my needs better or do I have to invent my own? A: If you already know what to modify, dd can read a file containing the bytes you want to write, and you tell it where to write them. To figure out where to write, debugfs from the e2fsprogs package could help you. A: It should be possible to use a Linux filesystem image fuzzer to cause corruption: * *e2fuzz from e2fsprogs *http://people.redhat.com/sgrubb/files/fsfuzzer-0.7.tar.gz *http://projects.info-pull.com/mokb/fsfuzzer-0.6.tgz *http://www.cccmz.de/~snakebyte/fsfuzzer-0.6-lmh2.tar.bz2 *http://thread.gmane.org/gmane.comp.file-systems.ext4/32167 (uses zzuf) or one of the Linux disk fault injection techniques (e.g. dm-flakey in corruption mode) described in https://unix.stackexchange.com/a/144200 .
{ "language": "en", "url": "https://stackoverflow.com/questions/140253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Is there a way to return different types from a WCF REST method? I am trying to write a web service to spec and it requires a different response body depending on whether the method completes successfully or not. I have tried creating two different DataContract classes, but how can I return them and have them serialized correctly? A: The best way to indicate that your WCF web service has failed would be to throw a FaultException. There are settings in your service web.config files that allow the entire fault message to be passed to the client as part of the error. Another approach may be to inherit both of your results from the same base class or interface. The service would return an instance of the base type. You can then use the KnownType attribute to inform the client that multiple types may be returned. Come to think of it, it might be possible to use Object as the base type, but I haven't tried it. Failing either of those approaches, you can create a custom result object that contains both a result and error properties and your client can then decide which course of action to take. I had to use this approach for Silverlight 2 because Beta 2 does not yet fully support fault contracts. It's not pretty, I wouldn't normally recommend it, but if it's the only way that works or you feel it is the best approach for your situation... If you are having troubles with ADO.NET Data Services, I have less experience there. Here's some information on implementing FaultContracts A: The answer is yes but it is tricky and you lose strong typing on your interface. If you return a Stream then the data could be xml, text, or even a binary image. For DataContract classes, you'd then serialize the data using the DataContractSerializer. See the BlogSvc and more specifically the RestAtomPubService.cs WCF service for more details. Note, that source code will also show you how to accept different types of data into a WCF rest method which requires a content type mapper. A: If you are using a xml based binding, then I believe there is no way to do that. A simple solution in that case would to just have part of the message flag if there was a failure, and store the failure information somewhere if needed. For a JSON binding you may be able to use a method that returns an object, then return two different types of objects. If I remember correctly (which is rare), that is possible because the JavaScriptSerializer class uses reflection if the object is clean of serialization attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/140255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Catching 'external drive inserted' event in a windows service I'm trying to write a super-simple podcast-to-device downloading service to use for running. I imagine that it'll like this: Whenever a particular device is plugged in (via USB), it: * *Deletes everything from the device *Checks for all the latest entries in a number of RSS Podcast feeds *Downloads those to the device *Notifies the user about when its done. I have some passing experience with windows services, but am not sure how to (using .NET/C#) catch the 'media device/usb hard drive has been plugged in' event. Any advice? A: The simplest solution would be to periodically enumerate the devices! CodeProject has a comprehensive C# article for this here : http://www.codeproject.com/KB/system/DriveDetector.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/140287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using locale.setlocale in embedded Python without breaking file parsing in C thread We're using a third-party middleware product that allows us to write code in an embedded Python interpreter, and which exposes an API that we can call into. Some of these API calls allow us to load various kinds of file, and the loading code is implemented in C. File loading happens in a separate thread, and calls back into Python when the data is available. So far, all well and dandy. We've been i14ing (heh) our product, and one thing we'd like to do is format user-facing numerical output according to the user's locale settings. So, from Python, we do this: import locale locale.setLocale( locale.LC_ALL, '' ) Now, this works (in that the user-facing numbers are formatted correctly for their locale). However, if the user's locale differs from the default C locale, any files that are subsequently loaded will return incorrect data, presumably because all string-to-float conversion has been affected, right down to the metal. We can't work around this by implementing locale aware file loading, so our current workaround is to only set the locale when formatting output for the user, and then set it back again afterwards. That is, something like: import locale currentLocale = locale.getLocale( locale.LC_ALL ) locale.setLocale( locale.LC_ALL, '' ) displayNumbersToTheUser() locale.setlocale( locale.LC_ALL, currentLocale ) This seems a bit clunky, and I was wondering whether this is a common approach to formatting locale-aware output for the user? My other concern is that this is obviously not thread safe, so we'll presumably still get problems if any file parsing occurs in a separate thread when the locale is changed. Any information on best practice is appreciated - I don't have much experience with this sort of thing. A: Setting the locale after multiple threads have started operating may have unexpected results. Unless I could figure out a more subtle approach, I'd probably just split file loading and the user interface into separate processes, communicating through a pipe or a file socket.
{ "language": "en", "url": "https://stackoverflow.com/questions/140295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET: Unable to validate data What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links). FWIW, I'm not running a web farm. Exception Error Message: Unable to validate data. Error Source: System.Web Error Target Site: Byte[] GetDecodedData(Byte[], Byte[], Int32, Int32, Int32 ByRef) Post Data VIEWSTATE: /wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB EVENTVALIDATION: /wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg= Exception Stack Trace at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.default_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) ~ William Riley-Land A: In .NET 3.5 SP1 the RenderAllHiddenFieldsAtTopOfForm property was added to the PagesSection configuration. Web.config <configuration> <system.web> <pages renderAllHiddenFieldsAtTopOfForm="true"></pages> </system.web> </configuration> Interestingly, the default value of this is true. So, in essence, if you are using .NET 3.5 SP1 then the ViewState is automatically being rendered at the top of the form (before the rest of the page is loaded) thus eliminating the ViewState error you are getting. A: I've experienced the issue with certain specific versions of Safari 3. My solution was to move the ViewState to the top of the form (extended the Page class and overwrote the Render method for pre-3.5 SP1, or .Net 3.5 SP1 and later does this by default), and to split up the ViewState to several different fields instead of one monster file. See ViewState Chunking in ASP.NET 2.0 (maxPageStateFieldLength) A: This free online tool: http://aspnetresources.com/tools/machineKey generates a machineKey element under the system.web element in the web.config file. Here is an example of what it generates: <machineKey validationKey="1619AB2FDEE6B943AD5D31DD68B7EBDAB32682A5891481D9403A6A55C4F91A340131CB4F4AD26A686DF5911A6C05CAC89307663656B62BE304EA66605156E9B5" decryptionKey="C9D165260E6A697B2993D45E05BD64386445DE01031B790A60F229F6A2656ECF" validation="SHA1" decryption="AES" /> Once you see this in your web.config, the error itself suddenly makes sense. The error you are getting says "ensure that configuration specifies the same validationKey and validation algorithm". When you look at this machineKey element, suddenly you can see what it is talking about. By "hard coding" this value in your web.config, the key that asp.net uses to serialize and deserialize your viewstate stays the same, no matter which server in a server farm picks it up. Your encryption becomes "portable", thus your viewstate becomes "portable". I'm just guessing also that maybe the very same server (not in a farm) has this problem if for any reason it "forgets" the key it had, due to a reset on any level that wipes it out. That is perhaps why you see this error after an idle period and you try to use a "stale" page. A: "a postback is stopped before all the viewstate loads" I've had this exact problem before, and this was the cause. Initially we disabled the ViewStateMac property (enableViewStateMac="false" in the page directive) to solve it, but this is not a true solution to the problem and can threaten data integrity. We ultimately resolved it by disabled our submit button until the page had completely loaded, and trimming the size of our viewstate by disabling it on some controls. A: I've found the root of this problem in my web site and I finally managed to solve it. This is not a direct answer to your question, but I wanted to share this little piece of information. In the past I tried everything (including the solution proposed by Jeffaxe, above) but with no result, and I didn't want to set enableViewStateMac="false" (as Raelshark mentions above) to my page, because this just hides the problem. What caused the problem in my case? The problem was caused by the use of the Intelligencia.UrlRewriter (Version 2.0 RC 1 build 6) module in certain pages of my web site. I was using some SEO friendly links and that was causing the ViewState validation failure. When I used "normal" links (instead of the SEO-friendly links) the problem disappeared! I reproduced the problem a few times to make sure it was not a false alarm (I use ASP.NET 3.5). I know that some of you may not use the above module, and still get this error, which implies that the cause is something else. At least, sharing this experience might be helpful to some. A: I got this error when I had a form tag setup on my page without an action attribute, and then in the code-behind, I changed the form's action attribute to "Action.aspx". And in JavaScript, I submitted the form (theForm.submit();) I think in my case it was a security issue, and that you can't change this after it's already been set on the page... ? A: The most likely cause of this error is when a postback is stopped before all the viewstate loads (the user hits the stop or back buttons), the viewstate will fail to validate and throw the error. Other potential causes: * *An application pool recycling between the time the viewstate was generated and the time that the user posts it back to the server (unlikely). *A web farm where the machineKeys are not synchronized (not your issue). Update: Microsoft article on the issue. In addition to the above they suggest two other potential causes: * *Modification of viewstate by firewalls/anti-virus software *Posting from one aspx page to another. A: Not sure if this would help anyone, but my solution was the exclusion of the machineKey in my webconfig for my cookie to get passed.
{ "language": "en", "url": "https://stackoverflow.com/questions/140303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to prevent Visual Studio 2008 from expanding excluded folders when opening solution? We just migrated to Visual Studio 2008 from 2005. Now whenever I open our project solution the solution explorer auto expands every directory that is excluded or contains an excluded file. A: I'm not sure why it would expand every excluded item, but you can click the "Show All Files" icon at the top of solution explorer which will toggle whether or not it shows hidden/excluded items.
{ "language": "en", "url": "https://stackoverflow.com/questions/140313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I redirect to a page when the user session expires? I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help. Thanks! A: I usually add an HtmlMeta control to the Page.Header.Controls collection on the master page when the user has "logged in". Set it to Refresh to your SessionExpired.aspx page with an appropriate timeout length, and you're good to go. A: You can handle this in global.asax in the Session_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired: public void Session_OnStart() { if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null) { HttpContext.Current.Response.Redirect("SessionTimeout.aspx") } } Alas I have not found any elegant way of finding out the name of the session cookie. A: If I understand correctly, "Session_End" fires internally and does not have an HTTP context associated with it: http://forums.asp.net/t/1271309.aspx Therefore I don't think you could use it to redirect the user. I've seen others suggest using the "Session_OnStart()" event in the global.ascx file: http://forums.asp.net/p/1083259/1606991.aspx I have not tried it, but putting the following code in "global.ascx" might work for you: void Session_OnStart() { if (Session.IsNewSession == false ) { } else { Server.Transfer("SessionExpired.aspx", False); } } A: We use Forms Authentication and call this method in the Page_Load method private bool IsValidSession() { bool isValidSession = true; if (Context.Session != null) { if (Session.IsNewSession) { string cookieHeader = Request.Headers["Cookie"]; if ((null != cookieHeader) && (cookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) { isValidSession = false; if (User.Identity.IsAuthenticated) FormsAuthentication.SignOut(); FormsAuthentication.RedirectToLoginPage(); } } } return isValidSession; } A: The other way is to tell the browser to redirect itself (via javascript) after a certain amount of time... but that can always be deactivated by the user. A: You can't redirect the user when the session expires because there's no browser request to redirect: * *If the user visits your site within the session timeout (20 minutes by default), the session hasn't ended, therefore you don't need to redirect them. *If the user visits your site after the session has timed out, the session has already ended. This means that they will be in the context of a new session - Session_OnEnd will already have fired for the old session and instead you'll be getting Session_OnStart for the new session. Other than a client-side feature (eg JavaScript timer etc), you therefore need to handle the redirect in a Session_OnStart instead - but obviously you need to distinguish this from someone coming to the site afresh. One option is to set a session cookie when their session starts (ie a cookie with no expiry so that it only lasts until the browser is closed), then look for that cookie in Session_OnStart - if it's present it is a returning user with an expired session, if not it's a new user. Obviously you can still use Session_OnEnd to tidy up on the server side - it's just the client interaction that isn't available to you. A: Are you putting something in the Session object that should always be there? In other words, if they log in, you may be putting something like UserID in the session Session("UserID") = 1234 So, if that is the case, then you could add something to your codebehind in the master page that checks for that value. Something like this: Dim UserID As Integer = 0 Integer.TryParse(Session("UserID"), UserID) If UserID = 0 Then Response.Redirect("/sessionExpired.aspx") End If A: You can also check the solutions provided in below link Detecting Session Timeout And Redirect To Login Page In ASP.NET A: Add or update your Web.Config file to include this or something similar: <customErrors defaultRedirect="url" mode="RemoteOnly"> <error statusCode="408" redirect="~/SessionExpired.aspx"/> </customErrors> A: Are you looking to redirect on the next request, or redirect immediately, without user intervention? If you're looking to redirect without user intervention, then you can use ClientScript.RegisterStartupScript on your Master Page to inject a bit of javascript that will redirect your clients when their session expires. System.Text.StringBuilder sb = new System.Text.StringBuilder(); String timeoutPage = "SessionExpired.aspx"; // your page here int timeoutPeriod = Session.Timeout * 60 * 1000; sb.AppendFormat("setTimeout(\"location.href = {0};\",{1});", timeoutPage, timeoutPeriod); Page.ClientScript.RegisterStartupScript(this.GetType(), "timeourRedirect", sb.ToString(), true); A: Code from here namespace PAB.WebControls { using System; using System.ComponentModel; using System.Web; using System.Web.Security; using System.Web.UI; [DefaultProperty("Text"), ToolboxData("<{0}:SessionTimeoutControl runat=server></{0}:SessionTimeoutControl>")] public class SessionTimeoutControl : Control { private string _redirectUrl; [Bindable(true), Category("Appearance"), DefaultValue("")] public string RedirectUrl { get { return _redirectUrl; } set { _redirectUrl = value; } } public override bool Visible { get { return false; } } public override bool EnableViewState { get { return false; } } protected override void Render(HtmlTextWriter writer) { if (HttpContext.Current == null) writer.Write("[ *** SessionTimeout: " + this.ID + " *** ]"); base.Render(writer); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (this._redirectUrl == null) throw new InvalidOperationException("RedirectUrl Property Not Set."); if (Context.Session != null) { if (Context.Session.IsNewSession) { string sCookieHeader = Page.Request.Headers["Cookie"]; if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0)) { if (Page.Request.IsAuthenticated) { FormsAuthentication.SignOut(); } Page.Response.Redirect(this._redirectUrl); } } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/140329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Nullable entity projection in Entity Framework I have a following SQL Server 2005 database schema: CREATE TABLE Messages ( MessageID int, Subject varchar(500), Text varchar(max) NULL, UserID NULL ) The column "UserID" - which can be null - is a foreign key and links to the table CREATE TABLE Users ( UserID int, ... ) Now I have several POCO classes with names Message, User etc. that I use in the following query: public IList<Message> GetMessages(...) { var q = (from m in dataContext.Messages.Include("User") where ... select m); // could call ToList(), but... return (from m in q select new Message { ID = m.MessageID, User = new User { ID = m.User.UserID, FirstName = m.User.FirstName, ... } }).ToList(); } Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database. Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL. If I change the last couple of lines to return (from m in q select new Message { ID = m.MessageID, User = m.User == null ? null : new User { ID = m.User.UserID, ... } }).ToList() then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported. Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks. A: You forgot to include the declaration of your "Message" class but I suspect that the UserID property in that class is not declared as a nullable type. If that is the case, change it from "int" to "int?" (nullable int). A: Since you did an .Include("Users") you should be able to just traverse the User property in the Message object to get the information your want. A: I suspect your relationship is not 1 to 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/140331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I read a file in C++? I am having some problems reading from a file. I have two header files: a and b. b is derived from a,and c is derived from b. Now i want to open a text file. The whole format is like this: A john A johnee P 123 If the first charcter is 'a' and 'p' is also there, then print the second line, else print the first line. #include "c.h" #include <iostream> # include <fstream> using namespace std; c :: c() { ifstream input; input.open ("abc.txt"); ch = input.get(); input >> ch; if (ch ='A') a* z =new a(); else input.close(); } Can anyone give me some advice on how to accomplish this? A: If the first charcter is 'a' and 'p' is also there, then print the second line, else print the first line. Could you give an example of what this program's output should look like based on the text file you have? I did notice one thing, though: if (ch ='A') Change that to: if (ch =='A') You need to use two =s for comparisons.
{ "language": "en", "url": "https://stackoverflow.com/questions/140337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Win32/MFC Get window rect from client rect I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it! Does anyone know what it is? It will do something similar to: const CRect client(0, 0, 200, 200); const CRect window = ClientRectToWindowRect(client); SetWindowPos(...) A: You're probably thinking of AdjustWindowRectEx(). Keep in mind, this is intended for use when creating a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use GetWindowRect(). A: Is this what you are looking for? ClientToScreen http://msdn.microsoft.com/en-us/library/ms532670(VS.85).aspx A: If you want to map client co-ordinates to window co-ordinates use the ClientToWindow API. If you want to map client co-ordinates to screen co-ordinates use the ClientToScreen API. A: For control reposition use: RECT client; ::SetRect(&client, 0, 0, 200, 200); ::MapWindowPoints(hwndControl, ::GetParent(hwndControl), (POINT*)&client, 2); ::SetWindowPos(...) A: This will give you window rect in client coordinates, so you can use rect(top,left) as offset CRect rectFrame; GetWindowRect(&rectFrame); ScreenToClient(&rectFrame);
{ "language": "en", "url": "https://stackoverflow.com/questions/140347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are the advantages and disadvantages of using XML schemas? We are utilizing the XML data type in Microsoft SQL Server 2005 for a project. Some members of the team and I feel that we should also use XSDs while members of the other camp feel that we should keep the XMLs ad hoc and not treat them as "types". The XMLs are an effort to bring structure and centrality to a number of text configuration files that are a maintenance nightmare. We are using .NET 3.5/C# and our tables are designed with the appropriate data types. My argument is that we are already "types oriented" in our thinking why break that approach because it is XML. It is because of the lack of types with the text files that the original problem occured. Not using a "types" approach leaves us open to the same problem. May be my understanding of the benefits of XML schemas are incorrect. So what are the advantages and disadvantages of using XML schemas? A: Keeping a repository of XMLs without an XSD is akin (in my opinion) to having a database where all the types are declared as VARCHAR(n). You don't care what kind of input you get, you just want input. XSDs assure that your XMLs have the type of input that you expect. They give structure to your model, the very thing you're looking for. A: Unfortunately even the authoring body of XSD (W3C) understands that XSD is a pretty bad technology. That said, it's intention isn't necessarily bad. One of C#'s major benefits is that it is statically typed. Statically typing your XML documents gives them the same benefits. What's probably best here is reverse engineering your classes to produce the Schema using the XML serialization attributes. When you do this C# will create a custom data reader for your XML file which will dramatically improve performance. One of the biggest costs of XML is that it has to be string parsed. The more assumptions you can make about your XML files (e.g. their structure), the better your performance is likely to be. So ultimately like many things, is their enough of a need for performance benefits to justify the costs in developer time. Or is there a strong enough desire to use statically typed systems to justify the cost of writing the XSD. Ultimately your project needs will dictate what you should do, but static-typing and performance are major benefits to consider. A: Well, as said in the other posts and in the question, XSD will ensure that you're using the right type at the right place in your XML and that you'll have to think twice before changing its structure. But XSD is really over-verbose, if I can say so. And it's sometimes really a mess te describe a complex structure, with conditional content. Hopefully, XSD is not the only way to validate a XML, a much more simpler approach is to use RelaxNG, and especially its compact syntax which is really more readable than what you could ever imagine with XSD. A: One big advantage to using schemas is that it helps make sure that everyone on the project agrees as to how an XML document should be laid out. Also, by using schemas, you can enable validation in your XML parser, making it easier to tell when some piece of code fails because it's given some bad XML. On the downside, maintaining schemas can be a pain, and it may not be worth the effort depending on your project. A: If you don't have a schema, you'll end up reimplementing all of the validation yourself (or not validating at all and crashing on invalid input). XSD parser/validators do all of that work for you, and are optimized and debugged by experts in their domain. Why would you redo all of that work yourself? A: XSD's are not the only XML schema available. Use http://relaxng.org/ instead. RelaxNG lets you express the schema in XML, rather than necessitating learning yet another data "language" as XSD's do. A: important reason for the development of XML is that it allows for the use of data from more sources and in more ways as it has become a widely accepted standard for exchanging data between any number of computer systems.
{ "language": "en", "url": "https://stackoverflow.com/questions/140355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Data Protection and Web 2.0 Web sites Many countries now have data protection legislation which afford individuals the rights to: * *request that an organization hand over all information they hold on the individual and *to request that any information held on the individual is destroyed Facebook got into trouble over the second part of this in the UK as it is nigh on impossible to delete your information from Facebook. This is understandable. A persons' data in a social media site is intricately woven into the fabric of the site. Users generate posts, messages, chat, relationships with others, photos, applications etc. and in turn other people will add their own comments / thoughts on this content. However, I am far from convinced that simply stating in your terms and conditions that your data cannot be deleted complies with data protection legislation (at least in the UK - any programming lawyers want to comment?). We tend to handle the issue of deleting users content by overwriting key fields in the record for that user (e.g. username, name, email address) and by overwriting key fields in the content they have posted (e.g. comments, blog posts). This means that you may come accross a discussion post attributed to "deleted user" which reads "This post was deleted." Data protection issues even affect decisions such as hosting (we tend to host applications in the UK for many clients for Data Protection reasons, despite the higher cost). As a developer, how far is this my problem? I have a feeling that responsibility would ultimately fall on the legal owner of the application (my clients / employers) and it would be up to them to come after my company for not giving the issue proper consideration if they fell foul of this. My questions to you are: * *How do you deal with the issue of deleting content from a social media application where data protection compliance is an issue? *Whose responsibility is this ultimately? *Should I just lighten up and be less concerned about these kinds of issues? EDIT: Some great answers to 2 and 3 already, but what of the main issue? How do you handle removing a user's content from a complex social media application where it is tied in with so much other content A: Stating that data cannot be deleted is certainly not compliant with EU data protection laws; where we have the right to request deletion and request that it not be shared; basically we can expect that data is * *fairly and lawfully processed, -processed for specified purposes and not in any manner incompatible with those purposes, *adequate, relevant and not excessive, *accurate, *kept for no longer than is necessary, *processed in line with the individual’s legal rights, *kept securely, *transferred to countries outside the European Economic Area, only if the individual’s rights can be assured. So not deleting when a user closes his account is arguably in breach of "kept for no longer than necessary". The responsibility lies with the data controller; the company who collects and processes the data. If you have no involvement with day to day running of the system, if you have sold it to clients and they administer the system, then it's their problem. Should you lighten up? Well that's subjective; personally, being in the UK, I take these things into account; because privacy is important, regardless of any commercial aspect. To deal with your question about deleting from a social networking application it simply doesn't matter. The data must be deleted regardless of the application itself. Now it's personal information that is the problem, so you may assume that it's just names, dates of birth etc; however what if a comment gives identifiable information away? It's a bit of a minefield. The safest option is simply to nuke everything. In addition because displaying the information on the web means it may/will be transferred outside the EU you should have explicit permission for this when users sign up, the UK Information Commissioner has guidelines Insert standard I am not a lawyer, this is not legal advice disclaimer here A: Blowdart's answer is great although I wonder about data which intrinsically relates to more than one individual - like a Facebook message or wall posting. Or even a PDF which contains the names of multiple individuals - what if one of them asked for the information to be deleted? I imagine that you would be allowed to retain that data. Anyway that's not my answer. My answer is on the question of 'who is responsible'. While the data controller (your client) is indeed responsible under the legislation, you as a professional adviser may have a duty to them. So if they were prosecuted they might pursue you for damages for providing incomplete or wrong advice. I would recommend that you make them aware of the legislation, advise them to get a lawyer (there are lots of good ones around who specialise in information law), and put it in writing. You'll be doing the client a service and protecting yourself at the same time. If you are hosting the application then the position may be slightly different - there is a 'bureau' registration under the data protection act which may be appropriate here, but in any case you should probably take a bit of legal advice yourself. None of this is likely to apply to you as an employee, but it may apply to your employers as a supplier.
{ "language": "en", "url": "https://stackoverflow.com/questions/140365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I programmatically determine how to fit smaller boxes into a larger package? Does anyone know of existing software or algorithms to calculate a package size for shipping multiple items? I have a bunch of items in our inventory database with length, width and height dimesions defined. Given these dimensions I need to calculate how many of the purchased items will fit into predefined box sizes. A: This is a Bin Packing problem, and it's NP-hard. For small number of objects and packages, you might be able to simply use the brute force method of trying every possibility. Beyond that, you'll need to use a heuristic of some sort. The Wikipedia article has some details, along with references to papers you probably want to check out. The alternative, of course, is to start with a really simple algorithm (such as simply 'stacking' items) and calculate a reasonable upper-bound on shipping using that, then if your human packers can do better, you make a slight profit. Or discount your calculated prices slightly on the assumption that your packing is not ideal. A: Are you trying to see how many of a single type fits into a particular sized package, or are you trying to mix types as well? Sounds like you're trying to solve the Knapsack Problem. You might be able to find some algorithms for that which could be adapted to your specific requirements. Just understand that it will be hard to find an efficient algorithm, as the problem is NP complete (though depending on your specific requirements you may be able to find an efficient approximation, or your inputs may be small enough that it doesn't matter). A: If the boxes are to be hand packed, then you might consider writing an algorithm which would do what a reasonable human would do. The reason I suggest this is because unless you want to print out packing instructions for each order, then whoever is doing your packing is going to have to workout how they are going to fit the ordered items in however many boxes it has been allocated for the order. This might then lead to your human packers coming to SO asking on how to programmatically workout how to pack n items into m boxes. :-P (They might also ask you to do it, ask you for instructions, etc). As long as your algorithm does what a reasonable human being would do, I would personally accept its shipping estimate. A: Metaheuristics are good to deal with real world bin packing problems when there are many packages and/or many constraints. One open source Java implementation is Drools Planner. A: Maybe this will sound obvious, but it might be worthwhile to memoize the problem, then do some of them by hand. Finding a most effecient solution for arbitrary inputs and boxes in NP-hard, but by restricting the problem space, and accepting some inefficiency, that NP size might be something reasonable, and by memoizing, you might be able to bring the "common-case" time down substantially. It might also help to think about things in terms of hierarchical packing. A: The literature on "3D Bin packing" is far and wide. You can get a good overview by tracking the publications of Professor David Pisinger. He also published one of the few high quality implementations of bin packing with sourcecode: 3dbpp.c My own logistics toolkit pyShipping comes with a 3D Bin Packing implementation for Warehousing applications. It is basically implementing 4D Bin Packing (3D size & weigth) and gets an acceptable solution for typical order sizes (a few dozens of packages) in under a second runtime. It is used in production (meaning a warehouse) for some months now to determine the upper bound of shipping crates to be used. The warehouse workers are often able to pack somewhat more efficiently but that's OK with me. A: Pisinger is one of the few academics who posts working code. In one of his papers he mentions the "Minimum Depth" problem. Here is a practical and efficient algorithm for 3D Rectangular Box Packing that adjusts the height of the enclosing box. And here is an implementation in php. A: After lot of searching i have found a GitHub repository that might help someone. Function PackingService.Pack() takes list of Container and list of Item(s) to be packed as parameter and return result which contains lot of information including "container(s) packed in percentage and list of packed and unpacked items"
{ "language": "en", "url": "https://stackoverflow.com/questions/140406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Why avoid pessimistic locking in a version control system? Based on a few posts I've read concerning version control, it seems people think pessimistic locking in a version control system is a bad thing. Why? I understand that it prevents one developer from submitting a change while another has the file checked out, but so what? If your code files are so big that you constantly have more than one person working on them at the same time, I submit that you should reorganize your code. Break it up into smaller functional units. Integration of concurrent code changes is a tedious and error-prone process even with the tools a good version control system provides to make it easier. I think it should be avoided if at all possible. So, why is pessimistic locking discouraged? A: It depends on your project and team generally. Pessimistic locking is good because it is easy to understand - one dev at a time, and no merging required! However, the bad thing about is is exactly that - one dev at a time. I have the situation right now where a colleague has gone on-site, and before he left, he checked everything out so that if he had to fix any bugs, he could return and check all his changes in.... great for him, lousy for me and the rest of the dev team at base. If you can get around pessimistic locking in your team then its fine to use it, really, the biggest reason people hate it is because its Visual SourceSafe's default practice. If you're not confident in merging lots of changes, then you have another reason to use it - if you've ever used a optimistic locking SCM, and cocked up a merge, you'll know how hard it is to recover. If you can handle merging, then optimistic locking is superior and I'd recommend it, but you don't have to hand your geek card in if you don't want to use it. A: * *Bob needs to edit FooBar.java *John has it checked out for editing *Bob edits his local copy anyway and saves it as FooBar.java.bak *When John checks his in, Bob checks it out *Bob copies FooBar.java.bak over it and checks it in *John gets to reimplement his feature I've seen it happen time and time again. Developers do this because this process is annoying: * *Bob needs to edit FooBar.java *John has it checked out for editing *Bob has to wait twiddling his thumbs until John is done Pessimistic locking feels like amateur hour, sorry. A: * *You don't always have the option to break files apart * *Config Files *XML Files *Even relatively small files can still contain distinct parts that more than one developer needs access to * *Libraries *Utilities *Merging Tools are much smarter than they have ever been * *Conflicts are rather rare *Reduces delays due to developers having files "accidentally" checked out A: If a developer can't handle merging and fixing conflicts, he should be re-educated. It is common for even small files to get conflicts, for example with JSPs one person (web developer) could be changing the layout code, and someone else could change the API for the model that the JSP is using. A: Regarding the case with Bob and John, cooperative systems like svn do not prevent this scenario any more than a locking system does. I can 'update' FooBar.java, which satisfies svn that I have the latest edition, then delete that file locally and overwrite it with my own personal copy that I made without any regard for the baseline version, and check that in, happily destroying the other guy's changes. No system, locking or not, prevents this, so I do not see the point of even bringing it into the debate. The real issue is deciding what your balance is between likelihood of merge mistakes vs. inconvenience caused by people locking files The notion that either a locking or non-locking system is "superior" is nonsense. I've used VSS, in its default full locking mode, with 6 developers, and it worked like a dream. Occasionally, somebody would forget to release a lock and we'd have to hunt them down or break the lock manually and hand-merge when they returned, but this was very minimal. I've seen svn screw up its automatic merge more than once, such that I don't really trust it. It doesn't always flag a 'conflict' when two people have changed the same file in a way that cannot be automatically merged together. Conversely, I've seen people get impatient with VSS's locks, edit their own copies, and sloppily check them in over the top of other peoples' code, and I've seen svn handily catch me when I might accidentally try to check something in that has been changed by somebody else since I last checked it out. My point is, this is not a sensible debate to have. The success of either system comes down to how you manage the conflict points when they occur, not whether one system or the other is better. A: Pessimistic locking is (personal experience) in the way of collaboration. It's sometimes easily replaced by good team communication. Just by saying "Hey, I'm gonna work on this few files for a while". I've worked in teams of 2 to 6 people without locking and we never had a problem, beyond some usual and necessary merges. I also worked once with locking in a Visual SourceSafe hosted project. It was IMHO counter-productive. A: * *Go play with Source Safe and have a developer leave for a two week vacation. Add to that the VSS admins not being around. Now you have a fix to be posted but you can't because of the developer *If you have multiple features and/or bug fixes being worked on. No matter how small your code is broken up, you will still have contention for a central file. A: Software developers are always optimists -- just look at their estimating skils! In practice we find conflicts are rare and the benefits of not having to worry about locking outweigh the occasional conflict resolution step. A: if your code files are so big that you constantly have more than one person working on them at the same time If this is the case it's time for 'human beings' to take charge and coordinate any changes. In the ideal case, and if your project management is any good, you will rarely hit a time where you're trying to change a locked file because someone will have coordinated things so this won't practically happen. In other words you'll know 'Bob' is doing a large set of changes in components X/Y/Z, if you have a bug fix in component X you'll know to talk to Bob before trying to submit your changes. As I say this is ideal ;) A: Pessimistic locking is a good idea if serious conflicts are going to be likely. For most programming you won't see any serious conflicts, so pessimistic locking is fairly pointless. Exceptions to this would be if you are: * *Working on binary files where you can't really merge - art assets (models, textures, etc) are a good example. *Working with non-technical users who don't know how to merge, and don't want to learn (mostly artists, but some technical writers will throw a fit about this too). *Working on very large files which can't easily be merged or broken into smaller files due to the high degree of complexity (never seen a situation like that first hand, but I'm sure it's possible). Otherwise...
{ "language": "en", "url": "https://stackoverflow.com/questions/140409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How do I translate 8bit characters into 7bit characters? (i.e. Ü to U) I'm looking for pseudocode, or sample code, to convert higher bit ascii characters (like, Ü which is extended ascii 154) into U (which is ascii 85). My initial guess is that since there are only about 25 ascii characters that are similar to 7bit ascii characters, a translation array would have to be used. Let me know if you can think of anything else. A: I think you just can't. I usually do something like that: AccentString = 'ÀÂÄÉÈÊ[and all the other]' ConvertString = 'AAAEEE[and all the other]' Looking for the char in AccentString and replacing it for the same index in ConvertString HTH A: In code page 1251, chars are coded with 2 bytes : one for the basic char and one for the variation. Then, when you encode back in ASCII, only basic chars are kept. public string RemoveDiacritics(string text) { return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(text)); } From : http://www.clt-services.com/blog/post/Enlever-les-accents-dans-une-chaine-(proprement).aspx A: Indeed as proposed by unexist : "iconv" function exists to handle all weird conversion for you, is available in almost all programming language and has a special option which tries to convert characters missing in the target set with approximations. Use iconv to simply convert your input UTF-8 string to 7bit ASCII. Otherwise, you'll always end hitting corner case : a 8bit input using a different codepage with a different set of characters (thus not working at all with your conversion table), forgot to map one last stupid accented caracter (you mapped all grave/acute accent, but forgot to map Czech caron or the nordic '°'), etc. Of course if you want to apply the solution to a small specific problem (making file-system friendly filenames for your music collection) the the look-up arrays are the way to go (either an array which for each code number above 128 maps an approximation under 128 as proposed by JeeBee, or the source/target pairs proposed by vIceBerg depending on which substitution functions are already available in your language of choice), because it's quickly hacked together and quickly check for missing elements. A: For .NET users the article in CodeProject (thanks to GvS's tip) does indeed answer the question more correctly than any other I've seen so far. However the code in that article (in solution #1) is cumbersome. Here's a compact version: // Based on http://www.codeproject.com/Articles/13503/Stripping-Accents-from-Latin-Characters-A-Foray-in private static string LatinToAscii(string inString) { var newStringBuilder = new StringBuilder(); newStringBuilder.Append(inString.Normalize(NormalizationForm.FormKD) .Where(x => x < 128) .ToArray()); return newStringBuilder.ToString(); } To expand a bit on the answer, this method uses String.Normalize which: Returns a new string whose textual value is the same as this string, but whose binary representation is in the specified Unicode normalization form. Specifically in this case we use the NormalizationForm FormKD, described in those same MSDN docs as such: FormKD - Indicates that a Unicode string is normalized using full compatibility decomposition. For more information about unicode normalization forms, see Unicode Annex #15. A: Most languages have a standard way to replace accented characters with standard ASCII, but it depends on the language, and it often involves replacing a single accented character with two ASCII ones. e.g. in German ü becomes ue. So if you want to handle natural languages properly it's a lot more complicated than you think it is. A: Is converting Ü to U really what you would like to do? I don't know about other languages but in German Ü would become Ue, ö would become oe, etc. A: You seem to have nailed it I think. A 128 byte long array of bytes, indexed by char&127, containing the matching 7-bit character for the 8-bit bit character. A: Hm, why not just change the encoding of the string with iconv? A: It really depends on the nature of your source strings. If you know the string's encoding, and you know that it's an 8-bit encoding — for example, ISO Latin 1 or similar — then a simple static array is sufficient: static const char xlate[256] = { ..., ['é'] = 'e', ..., ['Ü'] = 'U', ... } ... new_c = xlate[old_c]; On the other hand, if you have a different encoding, or if you're using UTF-8 encoded strings, you will probably find the functions in the ICU library very helpful. A: The upper 128 characters do not have standard meanings. They can take different interpretations (code pages) depending on the user's language. For example, see Portuguese versus French Canadian Unless you know the code page, your "translation" will be wrong sometimes. If you are going to assume a certain code page (e.g. the original IBM code page) then a translation array will work, but for true international users, it will be wrong a lot. This is one reason why unicode is favored over the older system of code pages. Strictly speaking, ASCII is only 7 bits. A: There is an article on CodeProject that looks good. Also the conversion using codepage 1251 take my interest (see other answer). I don't like the conversion tables, since the number of characters in Unicode are that large you easily miss one. A: I think you already nailed it on the head. Given your limited domain, a conversion array or hash is your best bet. No sense creating anything complex to try to automagically do it. A: A lookup array is probably the simplest and fastest way to accomplish this. This is one way that you can convert say, ASCII to EBCDIC. A: I use this function to fix a variable with accents to pass to a soap function from VB6: Function FixAccents(ByVal Valor As String) As String Dim x As Long Valor = Replace(Valor, Chr$(38), "&#" & 38 & ";") For x = 127 To 255 Valor = Replace(Valor, Chr$(x), "&#" & x & ";") Next FixAccents = Valor End Function And inside the soap function I do this (for the variable Filename): FileName = HttpContext.Current.Server.HtmlDecode(FileName) A: Try the uni2ascii program.
{ "language": "en", "url": "https://stackoverflow.com/questions/140422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Authenticating against active directory using python + ldap How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_SUBTREE Filter = "(&(objectClass=user)(sAMAccountName="+un+"))" Attrs = ["displayName"] l = ldap.initialize(Server) l.protocol_version = 3 print l.simple_bind_s(DN, Secret) r = l.search(Base, Scope, Filter, Attrs) Type,user = l.result(r,60) Name,Attrs = user[0] if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] print displayName sys.exit() Running this with myusername@mydomain.co.uk password username gives me one of two errors: Invalid Credentials - When I mistype or intentionally use wrong credentials it fails to authenticate. ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'} Or ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'} What am I missing out to bind properly? I am getting the same errors on fedora and windows. A: That worked for me, l.set_option(ldap.OPT_REFERRALS, 0) was the key to access the ActiveDirectory. Moreover, I think that you should add an "con.unbind()" in order to close the connection before finishing the script. A: Here's some simple code that works for me. import ldap # run 'pip install python-ldap' to install ldap module. conn = ldap.open("ldaphost.company.com") conn.simple_bind_s("myuser@company.com", "mypassword") This is based on a previous answer. A: I was missing l.set_option(ldap.OPT_REFERRALS, 0) From the init. A: If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server: import win32security token = win32security.LogonUser( username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) authenticated = bool(token) A: if you have Kerberos installed and talking to AD, as would be the case with, say, Centrify Express installed and running, you might just use python-kerberos. E.g. import kerberos kerberos.checkPassword('joe','pizza','krbtgt/x.pizza.com','X.PIZZA.COM')` would return True a user 'joe' has password 'pizza' in the Kerberos realm X.PIZZA.COM. (typically, I think, the latter would be the same as the name of the AD Domain) A: Based on the excellent ldap3 tutorial: from ldap3 import Server, Connection, ALL, NTLM server = Server('server_name_or_ip', get_info=ALL) conn = Connection(server, user="user_name", password="password", auto_bind=True) conn.extend.standard.who_am_i() server.info I did the above in Python3 but it's supposed to be compatible with Python 2. A: I see your comment to @Johan Buret about the DN not fixing your problem, but I also believe that is what you should look into. Given your example, the DN for the default administrator account in AD will be: cn=Administrator,cn=Users,dc=mydomain,dc=co,dc=uk - please try that. A: I tried to add l.set_option(ldap.OPT_REFERRALS, 0) but instead of an error Python just hangs and won't respond to anything any more. Maybe I'm building the search query wrong, what is the Base part of the search? I'm using the same as the DN for the simple bind (oh, and I had to do l.simple_bind, instead of l.simple_bind_s): import ldap local = ldap.initialize("ldap://127.0.0.1") local.simple_bind("CN=staff,DC=mydomain,DC=com") #my pc is not actually connected to this domain result_id = local.search("CN=staff,DC=mydomain,DC=com", ldap.SCOPE_SUBTREE, "cn=foobar", None) local.set_option(ldap.OPT_REFERRALS, 0) result_type, result_data = local.result(result_id, 0) I'm using AD LDS and the instance is registered for the current account. A: I had the same issue, but it was regarding the password encoding .encode('iso-8859-1') Solved the problem. A: Use a Distinguished Name to log on your system."CN=Your user,CN=Users,DC=b2t,DC=local" It should work on any LDAP system, including AD A: For me changing from simple_bind_s() to bind() did the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/140439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "96" }
Q: Continuous Integration Servers My company is considering changing continuous integration servers (I won't say which one we have now, so I won't skew your responses in anyway :) ) I wondering if anybody has any recommendations? Best user experience, level of difficulty to maintain, etc... Our code is all in java, and we use ANT as a build tool. A: I recently implemented a Hudson server. Having previously used Cruise Control, I am very satisfied with Hudson and very impressed with its ease of setup and use. Adding new projects is infinitely easier than it was with Cruise Control. A: Atlassian's Bamboo looks nice but I don't have any experience with it. Looks to be similar in features to Cruise or TeamCity. A: Like some other people here, I really love Hudson. It is extremly easy to install (it's just a war file to deploy), to configure and to use. In addition, it offers a lot of functionalities that are not always available on others systems (build matrix, master and slaves, security on server or project level...) The number of existing plugins is quite important now, and creating its own plugin is not that hard... To finish, this application evolves really fast: we are currently on the 257th release and they made more than 100 releases since one year! For french people, I wrote a quite complete guide to use Hudson here. A: If you are using Atlassian staff software (e.g. Jira, Clover etc.) Bamboo is your way. We use it for couple months and I can recommend it. It worth its money. A: If you are not completely sold on Hudson a one click test drive should change your mind. Click below: https://hudson.dev.java.net/hudson.jnlp This will launch Hudson through Java Web Start for a test drive. Once it launches, visit http://localhost:8080/ to get to the dashboard. Any configuration that you do with this Hudson will be stored in ~/.hudson, so your data will survive through Hudson process restart. If you are using fairly standard tools such as svn and ant/maven - you should have a build up and running in 5 minutes. Different tools and it might take 20 minutes! See an introduction here: http://wiki.hudson-ci.org/display/HUDSON/Meet+Hudson A: Bamboo works great; if you have cash I'd recommend that. Cruise Control is worth its price; I've never been able to get it to reliably discover that source changes were made and build, nor have I have been able to get it to build manually. The interface and configuration are horribly complex. A: We use Cruise Control. It's got all the features we want and was pretty easy to set up. Integration w/ ANT and SVN is fine. Con: every once in a while we have to restart the process or the machine as it stops sending out messages for the nightly build. Not sure what that's about but it's just annoying. A: as usual with java world, there is the open source world and the commercial world. We've already seen pretty good coverage of the various offerings. Hudson : I don't know of a single other java server offering that is as easy as this to evaluate. java -jar hudson.war -- how easy can it get than that ? NOT only can you use it on windows, you can use it on all the usual java platforms. Ant, Maven and a host of other build platforms are supported. The best thing about Hudson is the plug-in capability. It is being developed almost continuously. You ask for a feature and it won't take long for it to be done. I usually don't like sounding like a fanboy, but this app/developer/community sure impresses me. BR, ~A A: Just a word on the Continuous Integration Feature Matrix: it wasn't collected by the CruiseControl people, it was started on CodeHaus by the DamageControl project and moved to the CruiseControl wiki when DamageControl went into hibernation. The information is largely maintained by the project/product owners or by their fans. A: Edit: We use Hudson now. A while ago I looked into a bunch of these with the following requirements: * *Java code *Ant builds *Groovy builds *Distributed builds *SCM trigger integration *http reports *smtp reports The Continuous Integration Feature Matrix is a great place to start. I ended up selecting AnthillPro and am using it successfully, just scratching at the surface of what we can and hope to use it for. A: I guess I will be the first to mention Luntbuild. Aside from the less-than-catchy name, it's a great CI server. * *Super easy to setup. *Web UI for creating/managing your projects and users *Support for LOTS of version control systems (I've used it with CVS, SVN, and StarTeam) *Pretty slick remote API *Relatively high granularity for access control (so you can give clients access to only their builds, and not toher clients' builds) *and much much more. Check out the Live demo. account/password demo/demo Note: The live demo is a few releases back. A: I am happy with bamboo. I looked at a number of free solutions before settling on it. A: Jetbrains TeamCity looked really good when we looked at it. It is java based so should be easy for your teamn to extend, and can do distributed builds etc... There's a freebie version you can evaluate. A: I have been looking into this too and although I initially was looking at CruiseControl, I heard good things about Hudson and decided to give it a try. I am completely blown away by how easy it was to get started (just download and run) and the configuration is done through the GUI so there's no fiddling around with XML config files. Within minutes I had performed my first Ant build. I now have it running as a Windows service on a server which is available 24/7 both in the office and via VPN. Upgrading is as simple as downloading the new war file and restarting. Support for junit reports is out of the box. Installing additional plugins is also very easy and I have added plugins for Trac, Cobertura, FindBugs and PMD. Code and test quality is increasing as it's very satisfying to see the trend graphs rising! I now use it to manage all of my builds for test and production environments. Since I manage several web applications this gives me more time to spend on actual programming. I honestly can't remember how I managed without it. A: We've used Cruise Control with decent results. We have since started using Maven for the build tool in all our projects. With that came the move to Hudson for CI which is very nice. If you think a move to Maven might be in your future, I'd recommend it. I think Hudson can even be used to call Ant tasks though a Maven wrapper might be in order. http://hudson-ci.org/ A: Thoughtworks Cruise is the commercial offspring of the CruiseControl open source project. Looks very nice, lots of features, distributed builds etc. I don't know what it's extendability is. A: An org I run (openqa.org) has, at one time or another, used just about all of them. In terms of easy setup, go with TeamCity or Bamboo. But in terms of overall reliability, you might want to look at Hudson. I really like JetBrains, but we found TeamCity to get in to weird states after a while, causing our builds to be very unreliable. Too bad, since I love IDEA! A: We've been using Automated Build Studio and have been pretty happy with it. It's a windows app, so you're stuck on a windows build server, but on the plus side it's super easy to set up, maintain and use. You build your process from components via point and click, and can use scripting if none of the components meet your needs. A: Of the few that I've used, Buildbot stands out as the most powerful and flexible. It's not the prettiest, though, if that matters to you. A: I've administered both Bamboo and Hudson, and I would recommend Hudson. They are both great, but Hudson has better report support, for instance publishing your coverage reports etc. is so much easier inside Hudson. This is likely to change in the near future, but despite Bamboo's integration w/ JIRA etc. and it's statistics, Hudson, for ease of use and third-party support, is better regardless of dollar amount (it is free, Bamboo is not). A: We use Hudson too and if it wasn't the recession, we would probably use Bamboo and most of the Atlassian products(Bamboo, Crucible, Confluence) together with JIRA. A: I use Continuum for my continuous integration server. No reason other than I was going to hire a development manager who had used at his last assignment so it seemed to make sense to pick something at least one of us was experienced with. Prior to picking Continuum I had a junior developer spend two weeks trying to get CruiseControl going. However, we got Continuum 1.0 to run first go. A: We are using Zutubi Pulse and it works great for us. It's very easy to use ant has many advanced features. A: We use StarTeam and between Hudson and CruiseControl.NET,CC.NET has some bugs when integrating with StarTeam. It does not seem to recognize the workspace that we define in the config files. A: Last year on the a conference in the USA i first heard about Cruise Control .net on a 1 hour presentation, on my way home in the plain i decided to implement a small POC for our company and succcesfuly done it in less than 5 hours (including all the learning i could have done). I am using it since than and i must say that i am very pleased with the results, and ease of operation, There are some drawback (E.g. lack of distribution of task across servers scale although you can monitor several servers) i found a a bug in one of the implementation and because it is an open source i could have fixed it very quickly (big advantage) - i created a little [project][1] in codeplex to contain my fixes before i contribute them to the community as a check in. I highly encourage you to look at this platform, also it would be nice if you can say what you actually need. [1]: http://www.codeplex.com/DavidovitzCCE project A: CruiseControl.NET is much more effective on Windows boxes then the original Java based one. Especially when dedicated build server is not available yet. A: Check out our Parabuild. Compared to free tools, it is very easy to set up and its maintenance overhead is close to zero. it's not free but you get what you pay for. A: Why don't you use a hosted CI service then you don't have to worry about maintenance, costs etc. MikeCI is a hosted CI service which hosts your builds in the Amazon EC2 and for just $10 per month is a hell of a lot cheaper than maintaining your own CI server. Give it a go. A: Consider a free hosted CI service at fazend.com. It supports ant. A: You may want to look at it also http://www.thoughtworks-studios.com/solutions/deployment-managementlink text ThoughtWorks Deployment Management Solution combines the power of Twist (Agile testing) with Go (release management). * *Twist captures the requirements to be tested directly from business users and then supports their automation as long-term tests that evolve with the application. * Go helps development and IT operations teams model release processes and deploy software repeatably and reliably.
{ "language": "en", "url": "https://stackoverflow.com/questions/140453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "78" }
Q: Client/JS Framework for "Unsaved Data" Protection? We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data). I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out? A: Wanted to expand slightly on Volomike excellent jQuery code. So with this, we have a very very cool and elegant mechanism to accomplish the objective of preventing inadvertent data loss through navigating away from updated data prior to saving – ie. updated field on a page, then click on a button, link or even the back button in the browser before clicking the Save button. The only thing you need to do is add a “noWarn” class tag to all controls ( especially Save buttons ) that do a post back to the website, that either save or do not remove any updated data. If the control causes the page to lose data, ie. navigates to the next page or clears the data – you do not need to do anything, as the scripts will automatically show the warning message. Awesome! Well done Volomike! Simply have the jQuery code as follows: $(document).ready(function() { //---------------------------------------------------------------------- // Don't allow us to navigate away from a page on which we're changed // values on any control without a warning message. Need to class our // save buttons, links, etc so they can do a save without the message - // ie. CssClass="noWarn" //---------------------------------------------------------------------- $('input:text,input:checkbox,input:radio,textarea,select').one('change', function() { $('BODY').attr('onbeforeunload', "return 'Leaving this page will cause any unsaved data to be lost.';"); }); $('.noWarn').click(function() { $('BODY').removeAttr('onbeforeunload'); }); }); A: Additional to Lance's answer, I just spent an afternoon trying to get this snippet running. Firstly, jquery 1.4 seems to have bugs with binding the change event (as of Feb '10). jQuery 1.3 is OK. Secondly, I can't get jquery to bind the onbeforeunload/beforeunload (I suspect IE7, which I'm using). I've tried different selectors, ("body"), (window). I've tried '.bind', '.attr'. Reverting to pure js worked (I also saw a few similar posts on SO about this problem): $(document).ready(function() { $(":input").one("change", function() { window.onbeforeunload = function() { return 'You will lose data changes.'; } }); $('.noWarn').click(function() { window.onbeforeunload = null; }); }); Note I've also used the ':input' selector rather than enumerating all the input types. Strictly overkill, but I thought it was cool :-) A: I've created a jQuery plug-in which can be used to implement a warn-on-unsaved-changes feature for web applications. It supports postbacks. It also includes a link to information on how to normalize behavior of the onbeforeunload event of Internet Explorer. A: One piece of the puzzle: /** * Determines if a form is dirty by comparing the current value of each element * with its default value. * * @param {Form} form the form to be checked. * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code> * otherwise. */ function formIsDirty(form) { for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; var type = element.type; if (type == "checkbox" || type == "radio") { if (element.checked != element.defaultChecked) { return true; } } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { if (element.value != element.defaultValue) { return true; } } else if (type == "select-one" || type == "select-multiple") { for (var j = 0; j < element.options.length; j++) { if (element.options[j].selected != element.options[j].defaultSelected) { return true; } } } } return false; } And another: window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms["someFormOfInterest"])) { // For IE and Firefox if (e) { e.returnValue = "You have unsaved changes."; } // For Safari return "You have unsaved changes."; } }; Wrap it all up, and what do you get? var confirmExitIfModified = (function() { function formIsDirty(form) { // ...as above } return function(form, message) { window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms[form])) { // For IE and Firefox if (e) { e.returnValue = message; } // For Safari return message; } }; }; })(); confirmExitIfModified("someForm", "You have unsaved changes."); You'll probably also want to change the registration of the beforeunload event handler to use LIBRARY_OF_CHOICE's event registration. A: If you use jQuery, here's an easy trick: $('input:text,input:checkbox,input:radio,textarea,select').one('change',function() { $('BODY').attr('onbeforeunload',"return 'Leaving this page will cause any unsaved data to be lost.';"); }); But just remember, if you have a condition where you redirect from this page, or you want to permit a successful form post, you need to do this before that redirect or submit event like so: $('BODY').removeAttr('onbeforeunload'); ...or you'll get yourself in a loop where it keeps asking you the prompt. In my case, I had a big app and I was doing location.href redirects in Javascript, as well as form posting, and then some AJAX submits that then come back with a success response inline in the page. In any of those conditions, I had to capture that event and use the removeAttr() call. A: I made one more slight improvement to the jQuery implementations listed on this page. My implementation will handle if you have client-side ASP.NET page validation enabled and being used on a page. It avoids the "error" of clearing the onBeforeLeave function when the page doesn't actually post on click due to a validation failure. Simply use the no-warn-validate class on buttons/links that cause validation. It still has the no-warn class to use on controls that have CausesValidation=false (e.g. a "Save as Draft" button). This pattern could probably be used for other validation frameworks other than ASP.NET, so I post here for reference. function removeCheck() { window.onbeforeunload = null; } $(document).ready(function() { //----------------------------------------------------------------------------------------- // Don't allow navigating away from page if changes to form are made. Save buttons, links, // etc, can be given "no-warn" or "no-warn-validate" css class to prevent warning on submit. // "no-warn-validate" inputs/links will only remove warning after successful validation //----------------------------------------------------------------------------------------- $(':input').one('change', function() { window.onbeforeunload = function() { return 'Leaving this page will cause edits to be lost.'; } }); $('.no-warn-validate').click(function() { if (Page_ClientValidate == null || Page_ClientValidate()) { removeCheck(); } }); $('.no-warn').click(function() { removeCheck() }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/140460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Testing for multiple screens with javascript Is it possible to tell if the user of a website is using multiple monitors? I need to find the position of a popup but it's quite likely the user will have a multiple monitor setup. Whilst window.screenX etc. will give the position of the browser window it's useless for multiple monitors. A: I didn't find the answer I needed anywhere on StackOverflow, so responding late to the several related threads here. The solution is, first, check for secondary display with window.screen.isExtended. Then await window.getScreenDetails(), which returns an object that includes an array of screens. Very thorough explanation here: https://web.dev/multi-screen-window-placement/ A: I do not believe that it is possible right now; however js is becoming more popular for desktop use in widgets in addition to web development and that would be an excellent feature to request for a future version A: This is an overly complicated solution. I'd highly recommend refactoring this - it's not been used on a production site, only as a quick 'proof of concept' to myself. Right, caveats over. I've first assumed that the user might not have a dual monitor setup, but they might have a really big monitor and so the same functionality could be applied anyway. var newWindow, screenSpaceLeft = window.screenX, screenSpaceTop = window.screenY, screenSpaceRight = screen.availWidth - (window.screenX + window.outerWidth), screenSpaceBottom = screen.availHeight - (window.screenY + window.outerHeight), minScreenSpaceSide = 800, minScreenSpaceTop = 600, screenMargin = 8, width = (screen.availWidth / 2.05), height = screen.availHeight, posX = (screen.availWidth / 2), posY = 0; e.preventDefault(); if (screenSpaceRight > screenSpaceLeft && screenSpaceRight > screenSpaceTop && screenSpaceRight > screenSpaceBottom && screenSpaceRight > minScreenSpaceSide) { if (width > screenSpaceRight) { width = screenSpaceRight - screenMargin; } if (posX < (screen.availWidth - screenSpaceRight)) { posX = window.screenX + window.outerWidth + screenMargin; } } else if (screenSpaceLeft > screenSpaceRight && screenSpaceLeft > screenSpaceTop && screenSpaceLeft > screenSpaceBottom && screenSpaceLeft > minScreenSpaceSide) { if (width > screenSpaceLeft) { width = screenSpaceLeft - screenMargin; } posX = 0; } else if (screenSpaceTop > screenSpaceRight && screenSpaceTop > screenSpaceLeft && screenSpaceTop > screenSpaceBottom && screenSpaceTop > minScreenSpaceTop) { posX = 0; posY = 0; width = screen.availWidth; height = (screen.availHeight / 2.05); if (height > screenSpaceTop) { height = screenSpaceTop - screenMargin; } } else if (screenSpaceBottom > screenSpaceRight && screenSpaceBottom > screenSpaceLeft && screenSpaceBottom > screenSpaceTop && screenSpaceBottom > minScreenSpaceTop) { posX = 0; width = screen.availWidth; if (window.screenY + window.outerHeight + screenMargin > (screen.availHeight / 2)) { posY = window.screenY + window.outerHeight + screenMargin; } else { posY = (screen.availHeight / 2); } height = (screen.availHeight / 2.05); if (height > screenSpaceBottom) { height = screenSpaceBottom - screenMargin; } } newWindow = window.open(this.href, "_blank", "width=" + width + ",height=" + height + ",location=yes,menubar=no,resizable=yes,scrollbars=yes,status=yes,menubar=yes,top=" + posY + ",left=" + posX); It checks how much available screen space there is, and if a minimum amount if available (800 x 600), it opens the window there. If there isn't enough space, it overlays the window on the right hand side of the screen, taking up just about half of it. Notes: First, it should be altered to find out where the maximum amount of space is rather than just arbitarily search left, right, top, bottom. Second, I suspect that in some places where screen.availHeight has been used, screen.height should be used instead. Likewise for width. This is because we're not overly interested in where the taskbar is when deciding if the user has a second monitor or not (or a lot of space on the screen). Third, it won't work in IE < 8. This can easily be rectified by using screenLeft and screenTop rather than screenX/screenY where appropriate. Fourth, the code is messy and could be made to look a lot more elegant than it does. I make no apologies for this. However, you should NOT use such awful, unmaintainable JS anywhere and it NEEDS to be rewritten. I've only placed it here because it's in my train of thought at the moment and I'll most likely forget to post a good solution here when I write this properly as it won't happen for a few months. Right. There you go. I accept no responsibility for making your javascript horrible, ugly and downright difficult to do anything with. :) A: I found this as a solution that someone has used... I do not see why you couldn't trust it. [if the width is greater then (Height/3) * 4 > (Screen.Width) THEN] [User has dual monitor] [End If] A: You can't do that. You could position the popup centered on the parent window however. I think it's a better idea to show a "div" as dialog in the middle of your website, because the chance that this is popup blocked is smaller and it's IMO less annoying. A: What about the size of the screen? Multiple screens have usually a great size. Just check the sizes and decide if it's reasonable to be on just one or more screens. A: You could make a well-educated guess with JavaScript's screen.width (.availWidth) and screen.height (.availHeight). My idea was to assume (!) that monitors in general follow a certain ratio, whereas the .[avail]width should be outside of it because the screen is duplicated only in terms of width, but not height. Writing this answer, it sounds like a severe hack though. Nothing I would really rely on.
{ "language": "en", "url": "https://stackoverflow.com/questions/140462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What is the maximum possible length of a .NET string? What is the longest string that can be created in .NET? The docs for the String class are silent on this question as far as I can see, so an authoritative answer might require some knowledge of internals. Would the maximum change on a 64-bit system? [This is asked more for curiosity than for practical use - I don't intend to create any code that uses gigantic strings!] A: Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint). UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters. using System; using System.Collections.Generic; public class MyClass { public static void Main() { int i = 100000000; try { for (i = i; i <= int.MaxValue; i += 5000) { string value = new string('x', i); //WL(i); } } catch (Exception exc) { WL(i); WL(exc); } WL(i); RL(); } #region Helper methods private static void WL(object text, params object[] args) { Console.WriteLine(text.ToString(), args); } private static void RL() { Console.ReadLine(); } private static void Break() { System.Diagnostics.Debugger.Break(); } #endregion } A: Since the Length property of System.String is an Int32, I would guess that that the maximum length would be 2,147,483,647 chars (max Int32 size). If it allowed longer you couldn't check the Length since that would fail. A: The theoretical limit may be 2,147,483,647, but the practical limit is nowhere near that. Since no single object in a .NET program may be over 2GB and the string type uses UTF-16 (2 bytes for each character), the best you could do is 1,073,741,823, but you're not likely to ever be able to allocate that on a 32-bit machine. This is one of those situations where "If you have to ask, you're probably doing something wrong." A: For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do… The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file. The problem with s += "stuff" is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff" is extremely costly. If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth: StringBuilder sb = new StringBuilder(5000); for (; ; ) { sb.Append("stuff"); } StringBuilder will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration. A: Since String.Length is an integer (that is an alias for Int32), its size is limited to Int32.MaxValue unicode characters. ;-) A: The max length of a string on my machine is 1,073,741,791. You see, Strings aren't limited by integer as is commonly believed. Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed. Now, here's something you're welcome to try yourself. Create a new C# console app in Visual Studio and then copy/paste the main method here: static void Main(string[] args) { Console.WriteLine("String test, by Nicholas John Joseph Taylor"); Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then."); Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string."); Console.WriteLine("\nThe test starts ...now:\n"); int Length = 0; string s = ""; int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception. LoopPoint: // Make a string appendage the length of the value of Increment StringBuilder StringAppendage = new StringBuilder(); for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++) { StringAppendage.Append("0"); } // Repeatedly append string appendage until an out of memory exception is thrown. try { if (Increment > 0) while (Length < int.MaxValue) { Length += Increment; s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm")); } } catch (OutOfMemoryException ex) // Note: Any other exception will crash the program. { Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + "."); Length -= Increment; Increment /= 10; Console.WriteLine("After decimation, the value of Increment is " + Increment + "."); } catch (Exception ex2) { Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + "."); Console.WriteLine("Press a key to continue..."); Console.ReadKey(); } if (Increment > 0) { goto LoopPoint; } Console.WriteLine("Test complete."); Console.WriteLine("\nThe max length of a string is " + s.Length + "."); Console.WriteLine("\nPress any key to continue."); Console.ReadKey(); } My results were as follows: String test, by Nicholas John Joseph Taylor Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then. This is a quickish test to narrow down results to find the max supported length of a string. The test starts ...now: s.Length = 1000000000 at 08/05/2019 12:06 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000. Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07 Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete. The max length of a string is 1073741791. Press any key to continue. The max length of a string on my machine is 1073741791. I'd appreciate it very much if people could post their results as a comment below. It will be interesting to learn if people get the same or different results. A: 200 megs... at which point your app grinds to a virtual halt, has about a gig working set memory, and the o/s starts to act like you'll need to reboot. static void Main(string[] args) { string s = "hello world"; for(;;) { s = s + s.Substring(0, s.Length/10); Console.WriteLine(s.Length); } } 12 13 14 15 16 17 18 ... 158905664 174796230 192275853 211503438 A: String allocates dynamic memory size in the heap of your RAM. But string address is stored in stack that occupies 4 bytes of memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/140468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "268" }
Q: Base constructor in C# - Which gets called first? Which gets called first - the base constructor or "other stuff here"? public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } A: As others have said, the base constructor gets called first. However, constructors are not really the first thing that happens. Let's say you have classes like this: class A {} class B : A {} class C : B {} First, field initializers will be called in order of most-derived to least-derived classes. So first field initializers of C, then B, then A. The constructors will then be called in the opposite order: First A's constructor, then B, then C. A: I'd say base EDIT see: http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx there it says: using System; class Base { public Base() { Console.WriteLine("BASE 1"); } public Base(int x) { Console.WriteLine("BASE 2"); } } class Derived : Base { public Derived():base(10) { Console.WriteLine("DERIVED CLASS"); } } class MyClient { public static void Main() { Derived d1 = new Derived(); } } This program outputs BASE2 DERIVED CLASS A: Base Constructor is called first. But the initializer of fields in derived class is called first. The calling order is * *derived class field initializer *base class field initializer *base class constructor *derived class constructor (You can treat 2 and 3 as a whole to construct the base class.) Taken from CSharp Language Speification 5.0: 10.11.3 Constructor execution Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed. Given the example using System; class A { public A() { PrintFields(); } public virtual void PrintFields() {} } class B: A { int x = 1; int y; public B() { y = -1; } public override void PrintFields() { Console.WriteLine("x = {0}, y = {1}", x, y); } } when new B() is used to create an instance of B, the following output is produced: x = 1, y = 0 The value of x is 1 because the variable initializer is executed before the base class instance constructor is invoked. However, the value of y is 0 (the default value of an int) because the assignment to y is not executed until after the base class constructor returns. It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body. The example using System; using System.Collections; class A { int x = 1, y = -1, count; public A() { count = 0; } public A(int n) { count = n; } } class B: A { double sqrt2 = Math.Sqrt(2.0); ArrayList items = new ArrayList(100); int max; public B(): this(100) { items.Add("default"); } public B(int n): base(n – 1) { max = n; } } contains several variable initializers; it also contains constructor initializers of both forms (base and this). The example corresponds to the code shown below, where each comment indicates an automatically inserted statement (the syntax used for the automatically inserted constructor invocations isn’t valid, but merely serves to illustrate the mechanism). using System.Collections; class A { int x, y, count; public A() { x = 1; // Variable initializer y = -1; // Variable initializer object(); // Invoke object() constructor count = 0; } public A(int n) { x = 1; // Variable initializer y = -1; // Variable initializer object(); // Invoke object() constructor count = n; } } class B: A { double sqrt2; ArrayList items; int max; public B(): this(100) { B(100); // Invoke B(int) constructor items.Add("default"); } public B(int n): base(n – 1) { sqrt2 = Math.Sqrt(2.0); // Variable initializer items = new ArrayList(100); // Variable initializer A(n – 1); // Invoke A(int) constructor max = n; } } A: Don't try to remember it, try to explain to yourself what has to happen. Imagine that you have base class named Animal and a derived class named Dog. The derived class adds some functionality to the base class. Therefore when the constructor of the derived class is executed the base class instance must be available (so that you can add new functionality to it). That's why the constructors are executed from the base to derived but destructors are executed in the opposite way - first the derived destructors and then base destructors. (This is simplified but it should help you to answer this question in the future without the need to actually memorizing this.) A: Actually, the derived class constructor is executed first, but the C# compiler inserts a call to the base class constructor as first statement of the derived constructor. So: the derived is executed first, but it "looks like" the base was executed first. A: Eric Lippert had an interesting post on the related issue of object initialization, which explains the reason for the ordering of constructors and field initializers: Why Do Initializers Run In The Opposite Order As Constructors? Part One Why Do Initializers Run In The Opposite Order As Constructors? Part Two A: Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code: public class BaseClass { private string sentenceOne = null; // A public BaseClass() { sentenceOne = "The quick brown fox"; // B } } public class SubClass : BaseClass { private string sentenceTwo = null; // C public SubClass() { sentenceTwo = "jumps over the lazy dog"; // D } } Order of execution is: C, A, B, D. Check out these 2 msdn articles: * *Why do initializers run in the opposite order as constructors? Part One *Why do initializers run in the opposite order as constructors? Part Two A: The base constructor will be called first. try it: public class MyBase { public MyBase() { Console.WriteLine("MyBase"); } } public class MyDerived : MyBase { public MyDerived():base() { Console.WriteLine("MyDerived"); } } A: http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=777 Base Constructor gets called first. A: The Exception Constructor will be called, then your Child class constructor will be called. Simple OO principle Have a look here http://www.dotnet-news.com/lien.aspx?ID=35151 A: The base constructor will be called first, otherwise, in cases where your "other stuff" must make use of member variables initialized by your base constructor, you'll get compile time errors because your class members will not have been initialized yet. A: base(?) is called before any work is done in the child constructor. This is true, even if you leave off the :base() (in which case, the 0-parameter base constructor is called.) It works similar to java, public Child() { super(); // this line is always the first line in a child constructor even if you don't put it there! *** } *** Exception: I could put in super(1,2,3) instead. But if I don't put a call to super in explicitly, super() is called. A: Constructor calls are called (fired) from the bottom up, and executed from the top down. Thus, if you had Class C which inherits from Class B which inherits from Class A, when you create an instance of class C the constructor for C is called, which in turn calls the instructor for B, which again in turn calls the constructor for A. Now the constructor for A is executed, then the constructor for B is executed, then the constructor for C is executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/140490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "140" }
Q: Workaround for J2ME Hessian limitations? The official J2ME implementation of Hessian seems to have serious limitations : complex objects are not supported. This limitation is not mentioned anywhere on the online documentation, but if you google "hessian j2me" you will find posts about this problem. No solutions found with google though. Does anyone have a solution for this problem ? Is there an alternate implementation of Hessian for J2ME ? I would like to avoid getting strings from Hessian and then do some JSON/XML parsing to get objects... A: This is somewhat confusing as a Hessian is a matrix of mixed second partial derivatives, and a library that couldn't handle complex numbers would indeed be a problem. Why'd they have to reuse a well-established name with other meanings?
{ "language": "en", "url": "https://stackoverflow.com/questions/140510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What options do you recommend for language translation on content driven Web sites? Please read the whole question. I'm not looking for an approach to managing multi-lingual content, but I'm looking for a way to actually get that multi-lingual content. This usually falls within technical recommendations on most projects I work on, and I hope someone can offer some help. We are working with a client now who has the personnel to physically translate content, and each language has a separate domain, hosting, CMS, etc. For those clients that want to do business internationally though, and have no personnel, what are some approaches or services to use? Is it cheaper to farm this out to people, or to do it dynamically, and what are the technical drawbacks? Any advice you can offer is helpful. I know this isn't strictly a programming question, but I think it falls within the technical realm. A: I have yet to see a dynamic translation service that would be suitable for the content of a professional website. Language translation is not (yet) a mechanical activity - it requires thought and analysis. Your clients would best be served by outsourcing translation (or hiring a translator). A: Normally you would need two teams: a forward translation and a backward translation and you do this in parallel (3-4 four teams would be good) - you then check where the backward translation are in agreement (hopefully this is at 75-85%), you then get an expert to give your recommendations on the remaining 15-25%. You could theoretically set this up in Mechanical Turk.
{ "language": "en", "url": "https://stackoverflow.com/questions/140522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tips, Guides and/or Tutorials on writing a Windows desktop app for a PHP programmer by trade Yup, long title. I've been programming in PHP for the last 6 years or so for work and personal projects, but I've got an idea for a desktop app (which incidentally, uses a web REST api). I'm debating on how to approach this - I've got some experience in Java, C++, Perl and Python, but have never had the chance or opportunity to write and distribute an app to others of any significance. The app will need to communicate with a REST API (with OAuth), as well as access the file system, and possibly do some image manipulation (encoding/resizing, but this is a nice to have). I've been thinking something on .NET, but AIR is a possibility too (though I really dont want a huge runtime hanging around, this will be a system-tray type app). I'm not looking for someone to write it, but I could use a nudge in the right direction. A: In terms of language support, you can do it in C++, Java, C#, Python, etc. In practical terms, I'd say C++, Java and C# are the choice for most of the users. But keep in mind that GUI support in both C++ and Java is complex to learn and use. If you plan to make many large projects, performance is a concern (both in size and speed) and you need a simple installation process, use C++. If these last restrictions don't apply (only the size and number of projects), use Java. Assume you'll have to spend some considerable initial time preparing the infrastructure (libraries & etc.). If your plan is more short-term (not so many projects, not so large ones), use C#. It's realy the easiest to learn, use and produce code that works, and with the Mono project it's not restricted to MS platforms anymore. A: I would recommend the Visual Studio Express editions. Since you have experience with C-style languages, try starting with Visual C# Express. The 2008 SP1 edition is a very powerful IDE and it's completely free. The only downside for personal or small-grade development with the Express editions is that they don't have the class designer and you can't use Add-Ins. Be sure to target .NET 2.0 to reach a wider audience. If Windows XP is fine as a minimum requirement, you can also try .NET 3.5 with WPF, which makes application development more like web development, which may help you with the user interface design since you're coming from a web background. The runtime overhead is negligible, since most people will have a running .NET 2.0 Framework anyway (you can't uninstall it from Vista or later, and the ATI Catalyst Control Panel comes with .NET 2.0 as well, so many casual computer users have it). I think it's at least a recommended Windows Update for Windows XP. Note: There are localized versions as well, so you don't necessarily need the English version to which I posted the link. Delphi is fine as well, but the free editions of the original Delphi have some issues and no free Delphi edition, nor the Lazarus version, comes even close to what Visual Studio 2008 has to offer. A: Being a Delphi programmer for years, you can do everything you want with it. I'm starting to use C# at work. It's a great language too, but for a distributed application. the .NET framework still stops me from using it for my personnal apps. In my point of view, Delphi is a good option. You can look at Lazarus/Free Pascal if you want a free IDE. With this option, you build your EXE and that's it. Ship the EXE to the customer and it's working. No need for DLL/framework thing to have on the computer. Of course, if you're using database stuff or third party DLL, you must ship the necessary stuff with it. But it's simplier than with VB with all the vbrunxx.dll, or with all .NET language. It's my 2c... I think I'll be flamed for this! ;-) HTH A: If you're learning it new, skip Windows Forms and go directly to WPF. Its very similar to building a UI in xhtml, but with awesome data binding and less compatability issues. A: If you go with AIR you'll have a cross platform solution. You can also leverage some of the new AMF support in Zend Framework for a faster more efficient communications protocol. XML is big, JSON smaller but AMF is binary and much more compressed. AIR also allows you to write an application in two ways. The first is the traditional flash player/Flex combination and the other is to just write a bunch of HTML pages with Javascript in it that utilizes the AIR provided APIs. Aptana produce a functional free IDE plugin to Eclipse to write AIR apps in this second way. FlashDevelop is another free IDE that would be more suitable to the flash/flex way of writing an app. Flexbuilder is also free for 30 days and cheap if you are a student (free IIRC). A: I'd go with Delphi too. The free Turbo Explorer is fine for a quick project, or just to try it (and buy a license later). If you want to be a long term freebee user, go directly with Lazarus/FPC. Main reasons: single .exe possibility, good interfacing with other libs. Both support several sets of sockets libraries as well as database connectivity both to free and unfree databases. .NET is fine for corporate use, if you corporation installs it default (remember, XP comes with .NET 1.x). For wide-audience use, it is a bore to convince users to install the runtime, that it isn't a virus, and that it doesn't enable you to monitor them through their monitor.
{ "language": "en", "url": "https://stackoverflow.com/questions/140529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }