Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm looking for a java gui testing tool in which tests can be created by recording my gui actions (buttons pressed, windows closed, etc.) A scripting mechanism for writing tests is not required. It could be free or commercial, but cheap and great is better than expensive and great. My application is a rich-client app written in Java SE 6. Yoav
If it's a Swing app you could take a look at [Marathon](http://marathontesting.com/marathon/).
I concur with Kettelerij, Marathon's the way to go. * It's easy to integrate into external systems like Subversion & CruiseControl, becasue all the scripts are human readable (Jython) and not locked into some proprietary format that requires an export (like most of the commercial tools). * It is able to record scripts in your choice of Jython or JRuby, which are essentially python and ruby that give you access to Java API. Very easy to understand. * For advanced testers, you are able to identify which GUI component you want to select using not just their names, but instead a a unique subset of their properties, for example `click('{Text: OK Enabled: true}')` ... finds a component whose `getText()` is "OK" and `isEnabled()` is "true". This makes the scripts highly dynamic and easier to maintain.
which is the best java gui testing tool?
[ "", "java", "user-interface", "testing", "" ]
Is there a generic BitArray in .NET? I only found the non-generic one. Can there be a generic BitArray? (i.e. would it be reasonable?) --- ### Edit: Maybe I should have said type-safe not generic. Basically when you enumerate the type as `object`, should it not be `int` or `bool`? Or one of them provided in another member enumerator? --- ### Example: ``` foreach (bool bit in myBitArray) { } ``` --- ### Edit: I just checked the enumerator of the `BitArray` class, but everything returns an `object` except `.Current` property: ``` public virtual object Current ```
No, there isn't. I'm not even sure what part of a BitArray would be generic if there were one. It wouldn't be hard to create an extension method to take the `BitArray` and return a `bool[]` or `List<bool>` using a `for` loop on the `BitArray`. The `for` loop would not involve boxing since you would be using the `BitArray`'s indexer, and the `bool[]` `List<bool>` could be enumerated without boxing as well. Example extension method: ``` static List<bool> ToList( this BitArray ba ) { List<bool> l = new List<bool>(ba.Count); for ( int i = 0 ; i < ba.Count ; i++ ) { l.Add( ba[ i ] ); } return l; } ``` What I found from a quick benchmark (curiosity overcame me) was that `foreach (bool b in myBitArray.ToList())` took 75% to 85% of the time that `foreach (bool b in myBitArray)`. That creates the list each time. Creating the list once and iterating over it many times took 20% to 25% of the time that `foreach (bool b in myBitArray)` took. You could only take advantage of that if you need to iterate over the `bool` values multiple times and *know* that they won't have changed from the time you called `myBitArray.ToList()`. `foreach (bool b in Enumerable.Cast<bool(myBitArray))` took 150% of the time that `foreach (bool b in myBitArray)` took. **Yet another edit:** I'd say that since it is a game, it probably does make sense for you to do whatever it takes to have a very lean iteration with no boxing/unboxing, even if that means writing your own `BitArray`. You could save time and use [Reflector](http://www.red-gate.com/products/reflector/) to copy most of study `BitArray`'s code since the class is sealed (can't inherit and add functionality), just in case there are bit-twiddling optimizations to learn from. **Edit:** Struck the suggestion to copy code out of Reflector. Some things, like iterators and closures, yield weird generated code that you don't want to copy directly anyway.
BitArray is a specialized collection class from the NET 1.x era. It is quite type-safe as long as you use `ba.Set(int, bool)` and the indexer property. What is 'not typesafe' is the enumeration, BitArray implements IEnumerable but not IEnumerable< bool>. So Joan is right, using `foreach()` involves casting from object to bool. But is that a real problem? The elements in a BitArray are booleans, and only meaningful when combined with their position. Note that BitArray does not have an `Add()` method, just a `Set(i, true)`. So the simple answer is: don't use `foreach()`, or anything else based on IEnumerable. It only produces a stream of true/false values that can hardly be useful. In the following snippet the BitArray is perfectly type-safe and efficient: ``` BitArray isEven = ...; for(int i = 0; i < isEven.Count; i++) { isEven.Set(i, i % 2 == 0); } ```
Is there a generic (type-safe) BitArray in .NET?
[ "", "c#", ".net", "bitarray", "" ]
> **Possible Duplicates:** > [How can I get the size of an array from a pointer in C?](https://stackoverflow.com/questions/232691/how-can-i-get-the-size-of-an-array-from-a-pointer-in-c) > [Is there any way to determine the size of a C++ array programmatically? And if not, why?](https://stackoverflow.com/questions/197839/is-there-any-way-to-determine-the-size-of-a-c-array-programmatically-and-if-n) I get a pointer to a chunk of allocated memory out of a C style function. Now, it would be really interesting for debugging purposes to know how big the allocated memory block that this pointer points is. Is there anything more elegant than provoking an exception by blindly running over its boundaries? Thanks in advance, Andreas ### EDIT: I use VC++2005 on Windows, and GCC 4.3 on Linux ### EDIT2: I have `_msize` under VC++2005 Unfortunately it results in an exception in debug mode.... ### EDIT3: Well. I have tried the way I described above with the exception, and it works. At least while I am debugging and ensuring that immediately after the call to the library exits I run over the buffer boundaries. Works like a charm. It just isn't elegant and in no way usable in production code.
It's not standard but if your library has a `msize()` function that will give you the size. A common solution is to wrap `malloc` with your own function that logs each request along with the size and resulting memory range, in the release build you can switch back to the 'real' `malloc`.
If you don't mind sleazy violence for the sake of debugging, you can #define macros to hook calls to malloc and free and pad the first 4 bytes with the size. To the tune of ``` void *malloc_hook(size_t size) { size += sizeof (size_t); void *ptr = malloc(size); *(size_t *) ptr = size; return ((size_t *) ptr) + 1; } void free_hook (void *ptr) { ptr = (void *) (((size_t *) ptr) - 1); free(ptr); } size_t report_size(ptr) { return * (((size_t *) ptr) - 1); } ``` then ``` #define malloc(x) malloc_hook(x) ``` and so on
How can I get the size of a memory block allocated using malloc()?
[ "", "c++", "c", "memory-management", "malloc", "" ]
I am working with a piece of code that I find kinda strange. The code I am working on is part of an import utility that takes a CSV file and imports the data into the database. Inside the code, I see: ``` ImportUtils.printf("Validation started"); ``` When I look into this method, it is simply calling System.out.println: ``` public static void printf(String s) { System.out.println(s); } ``` Is there any advantage to this? Could this pose an issue down the road?
Instead of creating a simple System.out.println wrapper consider switching to a full logging API. There are many available ( [Commons Logging](http://commons.apache.org/logging/), [Log4j](http://logging.apache.org/log4j/), [SLF4J](http://www.slf4j.org/), and many more). These can easily be configured as simple wrappers around the console that are useful for initial development. Down the road these can be modified to write to files, send emails, write to database, ... These also provide contextual information ( like which class is generating the logs ) that is very useful and a pain to put in on your own.
A typical example of obsessive decoupling. Completely pointless since if you really want System.out to write somewhere else, you're free to use [System.setOut()](http://java.sun.com/javase/6/docs/api/java/lang/System.html#setOut(java.io.PrintStream)). If you need more flexibility, there's not exactly a shortage of logging frameworks to choose from.
Is it good to place System.out.println into a separate method?
[ "", "java", "" ]
I have an issue with Cross-Browser native events vs CallBack events. I have an HTML link "Click Me" with a given `href=""`. On `dom:loaded` I attach a function to this link (to do Ajax Stuff). JavaScript code is loaded at the end of the page to follow YSlow Recommandation. **Issue**: If you load this page really quickly (pressing F5) then click on link then * the `alert()` is not called * the link is followed (reloading the page) It happens when the server lags. In fact the page has not finished loading and the browser execute the code. **Demo**: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> </head> <body> <a href="#toolate" id="action">Click Me</a> <!-- According to YSlow Recommandation load at the bottom --> <script src="../js/lib/prototype.js" type="text/javascript" language="JavaScript"></script> <script> /* <![CDATA[ */ document.observe('dom:loaded', function() { $('action').observe('click', function(event){ alert("click"); Event.stop(event); }); }); /* ]]> */ </script> </body> </html> ``` **Turn Around**: A turn around is to add `onClick="return false;"`: ``` <a href="#toolate" id="action" onClick="return false;">Click Me</a> ``` It works for lags but not for quick click. And I don't like this kind of turn around because my goal is to remove the `onclick` on all `<a href="">`
We have done many many test on our CMS on many browsers. Sorted by speed: 1. JavaScript can't execute before a really fast click 2. onclick="return false" works fine in most case 3. JavaScript doing 2.) onLoad is too slow but could be enought 4. DIV using as shield brings other issues and is not a good choice
You could look into this: > JQuery has a handy little function that > launches your javascript as soon as > the Document Object Model is ready… > which happens before the page has > finished loading. ``` $(document).ready(function(){ // Your code here... }); ``` [via](http://15daysofjquery.com/quicker/4/) You could also put a big disabled div in front of everything while the page is loading to forbid clicking, but I wouldn't recommend it. Not sure if I got your question right, let me know if I didn't
Handling browser native click before dom:loaded
[ "", "javascript", "onclick", "cross-browser", "prototypejs", "dom-events", "" ]
I have a web page which I have prevented the default action on all submit buttons, however I would like to re-enable default submit action on a button how can I do this? I am currently preventing the default action using the following: ``` $("form").bind("submit", function(e){ e.preventDefault(); }); ``` I have successfully done this using the following: ``` $(document).ready(function(){ $("form:not('#press')").bind("submit", function(e){ e.preventDefault(); }); ``` But can I do this dynamically when the button is clicked?
You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding. There is no magical event.cancelled=false; As requested ``` $('form').submit( function(ev){ ev.preventDefault(); //later you decide you want to submit $(this).unbind('submit').submit() }); ```
Either you do what redsquare proposes with this code: ``` function preventDefault(e) { e.preventDefault(); } $("form").bind("submit", preventDefault); // later, now switching back $("form#foo").unbind("submit", preventDefault); ``` Or you assign a form attribute whenever submission is allowed. Something like this: ``` function preventDefault(e) { if (event.currentTarget.allowDefault) { return; } e.preventDefault(); } $("form").bind("submit", preventDefault); // later, now allowing submissions on the form $("form#foo").get(0).allowDefault = true; ```
How to reenable event.preventDefault?
[ "", "javascript", "jquery", "" ]
When running a web in visual studio, the following line returns true. ``` if (Membership.ValidateUser(Login1.UserName, Login1.Password)) ``` However, the moment I access the same code through a web, it returns false. Same database, same computer, same web folder, the only difference is that when I'm running through debug in visual studio, it works and when I'm trying to access it through a web, it fails. Thanks
When you are in debug mode you are in the security context of the user you are logged in as. When you access over the web you may be in the context of the same user or the IIS anonymous user or the identity of the application pool depending on your configuration. If you configure IIS and web.config to use windows authentication and impersonate = true, you should get the same result.
If you are using SQL Express, make sure that the folder the database resides in has permissions for the IIS worker process user to modify. On Windows XP it is typically the IIS\_ or ASPNET user. On Windows 2003+ this should normally be the NETWORK SERVICE group.
C# .NET - Membership.ValidateUser returns false in web; true in visual studio
[ "", "c#", ".net", "asp.net", "" ]
So, I have a macro. ``` // swap_specialize.hpp #include <algorithm> #ifndef STD_SWAP_SPECIALIZE #define STD_SWAP_SPECIALIZE( CLASSNAME ) \ namespace std { \ template<> inline \ void swap( CLASSNAME & lhs, CLASSNAME & rhs ) \ { lhs.swap(rhs); } } #endif ``` So then I have a class ``` // c.hpp #include <vector> #include "swap_specialize.hpp" class C { public: C(); void swap(C& rhs) { data_.swap(rhs.data_); } C& operator=(C rhs) { rhs.swap(*this); return *this; } private: std::vector<int> data_; } STD_SWAP_SPECIALIZE(C) ``` Does the usage of a macro to specialize std::swap in this way follow coding conventions?
I would say it's OK if it increases readability. Judge yourself. Just my two cents: Specializing `std::swap` isn't really the right way to do this. Consider this situation: ``` my_stuff::C c, b; // ... swap(c, b); // ... ``` This won't find `std::swap` if you haven't done `using std::swap` or something similar. You should rather declare your own swap in `C`'s namespace: ``` void swap(C &a, C &b) { a.swap(b); } ``` Now, this will work also in the above case, because argument dependent lookup searches in the namespace of the class. Code swapping generic things where the type isn't known should do it like this: ``` using std::swap; swap(a, b); ``` Regardless of the type, this will use the best matching swap, and fall-back to `std::swap` if there wasn't a better matching one in the namespaces of `a`. Hard-coding the call to `std::swap` will cut too short on types that don't specialize `std::swap` but rather decide to provide their own swap in their namespace. This is superious in another way: Imagine `C` is a template. You cannot specialize `std::swap` in this case. But just defining your own swap, that's perfectly fine. ``` template<typename T> void swap(C<T> &a, C<T> &b) { a.swap(b); } ``` This is the way how the swap for `std::string` and other classes is implemented too.
I don't see it buying you much. For non-template classes, it saves you very few lines. And for template classes, when you want to specialize generically (i.e. for all `T`), it just won't work.
Use a macro to specialize std::swap
[ "", "c++", "macros", "coding-style", "" ]
Right now I'm working on a project which requires an integer to be converted to a base 62 string many times a second. The faster this conversion is completed, the better. The problem is that I'm having a hard time getting my own base conversion methods to be fast *and* reliable. If I use strings, it's generally reliable and works well, but it's slow. If I use char arrays, it's generally much faster, but it's also very messy, and unreliable. (It produces heap corruption, comparison of strings that should match return a negative, etc.) So what's the fastest and most reliable way of converting from a very large integer to a base 62 key? In the future, I plan on utilizing SIMD model code in my application, so is this operation parallelizable at all? EDIT: This operation is performed several million times a second; as soon as the operation finishes, it begins again as part of a loop, so the faster it runs, the better. The integer being converted is of arbitrary size, and can easily be as large as a 128 bit integer (or larger). EDIT: This is the function I am currently using. ``` char* charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; int charsetLength = (int)(strlen(charset)); //maxChars is an integer specifying the maximum length of the key char* currentKey = new char[maxChars]; void integerToKey(unsigned long long location) { unsigned long long num = location; int i = 0; for(; num > 0; i++) { currentKey[i] = charset[num % (charsetLength)]; num /= charsetLength + 1; } currentKey[i + 1] = '\0'; } ``` I ripped this out of a class that is part of my application, and some of the code is modified so that it makes sense sans its owning class.
Probably what you want is some version of itoa. Here is a link that shows various versions of itoa with performance tests: <http://www.strudel.org.uk/itoa/> In general, I know of two ways to do this. One way it to perform successive divisions to strip off one digit at a time. Another way is to precompute conversions in "blocks". So you could precompute a block of int to text conversion of size 62^3 then do the digits 3 at a time. Provided you do the memory layout and lookup efficiently this can be slightly faster at runtime but incurs a startup penalty.
I feel bad because I cant remember where I originally found this, but I have been using this in my code and have found it to be pretty fast. You could modify this to be more efficient in certain places I am sure. Oh and I feel worse because this is written in Java, but a quick c&p and refactor could get it working in c++ ``` public class BaseConverterUtil { private static final String baseDigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; public static String toBase62( int decimalNumber ) { return fromDecimalToOtherBase( 62, decimalNumber ); } public static String toBase36( int decimalNumber ) { return fromDecimalToOtherBase( 36, decimalNumber ); } public static String toBase16( int decimalNumber ) { return fromDecimalToOtherBase( 16, decimalNumber ); } public static String toBase8( int decimalNumber ) { return fromDecimalToOtherBase( 8, decimalNumber ); } public static String toBase2( int decimalNumber ) { return fromDecimalToOtherBase( 2, decimalNumber ); } public static int fromBase62( String base62Number ) { return fromOtherBaseToDecimal( 62, base62Number ); } public static int fromBase36( String base36Number ) { return fromOtherBaseToDecimal( 36, base36Number ); } public static int fromBase16( String base16Number ) { return fromOtherBaseToDecimal( 16, base16Number ); } public static int fromBase8( String base8Number ) { return fromOtherBaseToDecimal( 8, base8Number ); } public static int fromBase2( String base2Number ) { return fromOtherBaseToDecimal( 2, base2Number ); } private static String fromDecimalToOtherBase ( int base, int decimalNumber ) { String tempVal = decimalNumber == 0 ? "0" : ""; int mod = 0; while( decimalNumber != 0 ) { mod = decimalNumber % base; tempVal = baseDigits.substring( mod, mod + 1 ) + tempVal; decimalNumber = decimalNumber / base; } return tempVal; } private static int fromOtherBaseToDecimal( int base, String number ) { int iterator = number.length(); int returnValue = 0; int multiplier = 1; while( iterator > 0 ) { returnValue = returnValue + ( baseDigits.indexOf( number.substring( iterator - 1, iterator ) ) * multiplier ); multiplier = multiplier * base; --iterator; } return returnValue; } } ```
Fastest base conversion method?
[ "", "c++", "radix", "" ]
``` foreach (string oName in oValues) { if (string.IsNullOrEmpty(Request.Form[oName])) { oCount += 1; } } if (oCount == 0) { _clientID = Request.Form["ClientID"]; _password = Request.Form["Password"]; _pracType = Request.Form["PracType"]; _encrypt = Request.Form["Encrypt"]; if (GetCRC(_clientID) == _password) { if (_clientID != null) { var verify = VerifyClientInformation(int.Parse(_clientID)); var gsa = new GSDataLayer.Authentication.Auth(); gsa.CreateAuthEntry(_clientID, _password, _pracType, _encrypt, verify.CanUpdate); _aMgr.GotoHomePage(); } else { error.Text = "This conditional failed."; } } else { _aMgr.GotoErrorPage("nocrc"); } } else { _aMgr.GotoErrorPage("noform"); } ``` the `GotoErrorPage` method: ``` public void GotoErrorPage(string errorcode) { if (HttpContext.Current.Request.UserHostAddress != "127.0.0.1") // for testing only { var instance = new Control(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Redirect(instance.ResolveClientUrl( string.Format("~/ErrorPage.aspx?e={0}", errorcode))); HttpContext.Current.Response.End(); } } ``` If `oCount` is 0, it redirects just fine but if it is > 0 the redirect does not happen. Any ideas on why this might be? thanks # edit Well, I feel rather silly...the conditional for the `UserHostAddress` in `GotoErrorPage()` was the culprit. I had forgotten that this was remnant from my initial testing because I did not want any redirects to happen, just outputting text (errors, results, etc). After removing that conditional, redirects happen just fine. What is throwing me for a spin, though, is it was working fine earlier. Although, I think I also figured that out as well. Since I am developing this on a network, some of my colleagues can access it via the intranet by using my computer's name (`program003`) instead of `localhost`. I think before the 'problem' showed up, I was using my computer's name instead of `localhost` while testing. Regardless, when I use `localhost`, the IP is `127.0.0.1`, but when I use `program003` I get this IPv6 address: > `fe80::b1d7:b18b:d10f:f526%8` If I am not mistaken, the loopback address for IPv6 is supposed to be `::1`? Very strange.
See my edit for problem/solution.
Looking at the logic if `GetCRC(_clientID) == _password` is true and `_clientID != null` is false, then you're left with no action taken at all, so you have at least one possible explanation there. May I also take the opportunity to say how much the dropped braces and hungarian breaks my mind? This is very hard to read for my eyes.
How come this redirect does not work with this section of code?
[ "", "c#", "asp.net", "" ]
I have a pageLoad function that sets some CSS on a .ascx control that I cannot change. On page load everything is fine, but when an update panel updates the control, my CSS is no longer applied. How can I rerun my function after the page updates? ``` $(function() { $("textarea").attr("cols", "30"); $("input.tbMarker").css({ "width": "100px" }).attr("cols","25"); }); ``` This obviously only runs on the initial page load. How can I run it after an update?
Adding an add\_pageLoaded handler can also work. ``` Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoadedHandler); ``` Note: the handler will fire for any callback, but you can use `sender._postBackSettings.panelID` to filter when you want your function called. More samples: * <http://blog.jeromeparadis.com/2007/03/01/1501/> * <http://zeemalik.wordpress.com/2007/11/27/how-to-call-client-side-javascript-function-after-an-updatepanel-asychronous-ajax-request-is-over/>
Most simple way is to use MSAjax pageLoad Event in your javascript code : ``` <script> ///<summary> /// This will fire on initial page load, /// and all subsequent partial page updates made /// by any update panel on the page ///</summary> function pageLoad(){ alert('page loaded!') } </script> ``` I have used it many times, it works like charm. Most important thing is don't confuse it with document.ready function (which will be executed only once after the page Document Object Model (DOM) is ready for JavaScript code to execute),yet pageLoad Event will get executed every time the update panel refreshes. Source: [Running script after Update panel AJAX asp.net](https://stackoverflow.com/questions/9026496/running-script-after-update-panel-ajax-asp-net)
How can I run some javascript after an update panel refreshes?
[ "", "asp.net", "javascript", "jquery", "updatepanel", "" ]
I have a form which posts data to the same page. Based on the user's radio button selection I am inserting *checked="checked"* into the radio button form element to redisplay the correct selection. This works fine, however when the form is redisplayed (in case of bad input etc), I need a div to be revealed (containing the relevant fields from the form). I have an onclick event that reveals the div in the first place (before the user has posted the form), and this works fine, but when I redisplay the form I don't want the user to have to manually reveal the form again by clicking. Therefore I've been trying something along the following lines (heavily cut down for the purposes of this post)... ``` <link href="styles/style1.css" rel="stylesheet" type="text/css" /> <script language="JavaScript"> if (document.getElementById('complete_yes').checked) { document.getElementById('repair_complete').style.display = 'block'; } else { document.getElementById('repair_complete').style.display = 'none'; } </script> <form action="javascript_test.php" method="POST"> <input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes <input id="complete_no" type="radio" name="complete" value="false"/>No <input type="submit" value="Save"> <div id="repair_complete"> I'm a div! </div> ``` ... but it returns an *Object Required* javascript error (as it does in the 'real' page): Message: Object required Line: 3 Char: 1 Code: 0 URI: <http://localhost/repair_system/javascript_test.php> Why is this? Am I not correctly referencing the form element? Apologies if I'm being a "div" (deliberate bad pun intended!), I'm yet to learn about the fun and games of javascript!
Because your javascript is not wrapped inside a function, the browser is executing it as soon as it "gets to it". In this case, the JS is being executed before the browser has reached the html declaring your form. The simplest fix therefore is to move the Javascript to after your form. A more robust solution would be to wrap you code in a function, and have that triggered somehow - from what you appear to be trying to do, in this case it'll be the onLoad event of the body tag: ``` <head> <script language="JavaScript"> function showHelpDiv() { if (document.getElementById('complete_yes').checked) { document.getElementById('repair_complete').style.display = 'block'; } else { document.getElementById('repair_complete').style.display = 'none'; } } </script> </head> <body onload="showHelpDiv()"> <form action="javascript_test.php" method="POST"> <input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes <input id="complete_no" type="radio" name="complete" value="false"/>No <input type="submit" value="Save"> <div id="repair_complete"> I'm a div! </div> ```
Your code is being executed as the document is being loaded, and the DOM tree isn't ready yet. So it is trying to access an element that doesn't exist yet. You probably want to instead write an event handler that toggles the div whenever the checkbox is checked. I prefer [jQuery](http://jquery.com/), which abstracts away things like cross-browser event handling, provides lots of nice helpers and generally makes code look cleaner (when written properly). Something like this should work: ``` $(document).ready(function() { $('#repair_complete').toggle($('#complete_yes').is(':checked')); } ``` The above can be roughly translated as: * When the document loads, perform the following: * Add an event handler for the '`change`' event to any elements of type '`input`' with a name of '`complete`' * When the event handler fires, toggle the visibility of the element with ID '`repair_complete`' where it should be visible if the element with ID '`complete_yes`' is checked Update: The JS above now actually does what you want, originally I had it written as an onclick
Automatically making a div appear based on status of radio button with JavaScript
[ "", "javascript", "forms", "dom", "" ]
I know that local variables and paramters of methods live in stack, but I not able to figure out where does actually methods live in case of Java? If I declare any Thread object like: ``` Thread t=new Thread(); t.start(); ``` So it means I've created a separate calling of methods apart from main method. What does it mean? Does it mean calling of separate sequence of methods over Stack memory? Am I right?
Each thread is allocated its own stack. [This article](http://www.javaworld.com/javaworld/jw-07-1997/jw-07-hood.html) has a good introduction to the memory separation within a Java process. > Inside the Java virtual machine, each > thread is awarded a Java stack, which > contains data no other thread can > access, including the local variables, > parameters, and return values of each > method the thread has invoked. The > data on the stack is limited to > primitive types and object references. > In the JVM, it is not possible to > place the image of an actual object on > the stack. All objects reside on the > heap. I've seen many scenarios where clients have implemented hugely threaded servers on the basis that each thread does very little, and they run into problems with memory. That's because each thread is allocated its own stack, and this (obviously) adds up. I *think* the default value is 512k per thread, but I've not found a canonical source for that.
If I remember correctly, the method code itself will live in the code portion of memory, while the variables declared internally will live in the stack, and the objects will be created on the heap. In Java, the variable pointers and primitives live on the stack, while any created objects live in the heap. For a (poor) ASCII representation: ``` ------- |STACK| ------- |FREE | ------- |HEAP | ------- |CODE | ------- ``` Where the STACK represents the stack, FREE represents free memory, HEAP represents the heap, and CODE represents the code space. This is what my memory says - some of the details might be wrong.
Where methods live? Stack or in Heap?
[ "", "java", "jvm", "heap-memory", "stack-memory", "" ]
Im Looking for a simple solution to stop a login form from submitting with empty input fields. The code for the form is below. I would like to use a simple Javascript soluiton if possible. ``` <form id="login" method="post" action=""> <input type="text" name="email" id="email" /> <input type="password" name="pwd" id="pwd" /> <button type="submit" id="submit">Login</button> </form> ``` If possible I would also like to change the border of the empty field(s). Thanks in advance.
Sample code with dummy checks: ``` <script type="text/javascript"> function checkForm(form) { var mailCheck = checkMail(form.elements['email']), pwdCheck = checkPwd(form.elements['pwd']); return mailCheck && pwdCheck; } function checkMail(input) { var check = input.value.indexOf('@') >= 0; input.style.borderColor = check ? 'black' : 'red'; return check; } function checkPwd(input) { var check = input.value.length >= 5; input.style.borderColor = check ? 'black' : 'red'; return check; } </script> <style type="text/css"> #login input { border: 2px solid black; } </style> <form id="login" method="post" action="" onsubmit="return checkForm(this)"> <input type="text" name="email" id="email" onkeyup="checkMail(this)"/> <input type="password" name="pwd" id="pwd" onkeyup="checkPwd(this)"/> <button type="submit" id="submit">Login</button> </form> ```
Possible approach: * setting action to `#` * adding handler to the submit button or the `onsubmit` of the form * change the action of the form, if text fields are not empty **Edit:** To make this even work for non-javascript users insert the `#`-action when page is loaded.
Stop Submit With Empty Input Values
[ "", "javascript", "forms", "authentication", "user-input", "" ]
I have the following code: ``` class myClass { private delegate string myDelegate(Object bj); protected void method() { myDelegate build = delegate(Object bj) { var letters= string.Empty; if (someCondition) return build(some_obj); //This line seems to choke the compiler else string.Empty; }; ...... } } ``` Is there another way to set up an anonymous method in C# such that it can call itself?
You can break it down into two statements and use the magic of captured variables to achieve the recursion effect: ``` myDelegate build = null; build = delegate(Object bj) { var letters= string.Empty; if (someCondition) return build(some_obj); else string.Empty; }; ```
If you're creating a recursive function, I'd recommend avoiding anonymous delegates. Just create a method and have it call itself recursively. Anonymous methods are meant to be anonymous - you shouldn't be calling them by name (non-anonymously).
Can an anonymous method in C# call itself?
[ "", "c#", "recursion", "anonymous-methods", "" ]
Are there any DB engines that are implemented entirely in .NET and Mono compatible? I would like to have a DB solution that will run on all platforms via Mono so that I don't have to worry about having separate native binaries for each platform.
**[VistaDB](http://www.vistadb.net/)** is fully .NET and supported on Mono. You can embed your DB server into your app with it so there's no extra setup the only issue is this isn't a free product. **[Firebird](http://firebirdsql.org/dotnetfirebird/index.html)** has a .NET version, and is opensource, which runs on Mono as well. There's also a Lucene adaptor for it incase you want to use that for searches. Can also give this page a look that lists the supported data providers etc. under Mono <http://www.mono-project.com/Database_Access>
[db4o](http://db4o.com/ "db4o") is an object database engine (written in both Java and C#) that compiles/runs smoothly under Mono.
.NET / Mono Database Engine
[ "", "c#", ".net", "database", "mono", "" ]
I set the modification date of a file created in Java to a specific number. When I read out that value on Windows, I get the same value out. However, on Linux (ubuntu) I get a different value. The value for File.lastModified() is off by 9 hours, yet when I look a the file properties I see that it's off by 1 hour only. I am expecting the same value across the board. Am I wrong to depend on this being compatible and consistent? The [javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#setLastModified(long)) is pretty unambiguous on the meaning of the method and does not mention potential incompatibilities.
It's almost certainly a time zone issue. The Java method uses/expects GMT, the OS will display local time, which accounts for the difference there. Now the real question is: how is the time stored in the file system? What file system are you using? Probably FAT32 - which stores timestamps in local time, thus making it hard to keep them consistent across OSs. I'm not sure where exactly things go wrong, but it may be an OS configuration issue or a JVM bug - which JVM are you using on Linux?
did you check the return value of `setLastModified`? **Returns:** ``` true if and only if the operation succeeded; false otherwise ```
File modification date in Java
[ "", "java", "file", "compatibility", "" ]
What is the best practice to follow when you need to throw an exception which was not defined in an interface that you are implementing? Here is an example: ``` public interface Reader { public abstract void read() throws IOException; } public class CarrotReader implements Reader { public void read() throws IOException {} } public class CupcakeReader implements Reader { public void read() throws IOException, CupcakeException {} } ``` In this case, you have a specific exception that occurs when reading cupcakes, so you want to throw an exception related to this. However, *Reader* doesn't define this type of exception in its interface, so what do you do? Furthermore, it doesn't make sense to add *CupcakeException* to the *throws* clause in the *Reader* interface, because this type of exception is specific to *CupcakeReader*. One way around this is to have *Reader* define *read* such that it throws some parent type, like *Exception*, but then you lose the context for the exception. What should you do in this situation? Thanks! --- Another interesting situation that has been brought up involves an interface over which you have no control. In this case, what is the best way to indicate that a problem has occurred? For illustrative purposes, here is another example: ``` public interface Reader { public abstract void read(); } public class CupcakeReader implements Reader { public void read() throws CupcakeException {} } ``` In this case, you cannot change *Reader*, but you want to indicate that a problem has occurred in *CupcakeReader*'s *read* method.
You may have to create an exception of the expected type instead. ``` ... catch(CupcakeException e) { throw new IOException("The sky is falling", e); } ```
Use something called ReaderException that will serve as the root interface of your exception hierarchy. ReaderException will also provides a link to other exceptions that get thrown due to lower level exceptions.
Throwing an Exception Not Defined in the Interface
[ "", "java", "exception", "interface", "throw", "" ]
When you want a certain task to be executed by another thread, you can extend Thread or implement Runnable. I've made an attempt to create a class which runs a class entirely in the second thread. This means that you can call anyMethod() which returns immediately and which is executed by the second thread. Here is my attempt: ``` import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * Extend this class to run method calls asynchronously in the second thread implemented by this class. * Create method(type1 param1, type2 param2, ...) and let it call this.enqueueVoidCall("method", param1, param2, ...) * * The thread executing the run-method will automatically call methodAsync with the specified parameters. * To obtain the return-value, pass an implementation of AsyncCallback to this.enqueueCall(). * AsyncCallback.returnValue() will automatically be called upon completion of the methodAsync. * */ public class ThreadedClass extends Thread { private static Object test; private Queue<String> queue_methods = new ConcurrentLinkedQueue<String>(); private Queue<Object[]> queue_params = new ConcurrentLinkedQueue<Object[]>(); private Queue<AsyncCallback<? extends Object>> queue_callback = new ConcurrentLinkedQueue<AsyncCallback<? extends Object>>(); private volatile boolean shutdown = false; /** * The run method required by Runnable. It manages the asynchronous calls placed to this class. */ @Override public final void run() { test = new Object(); while (!shutdown) { if (!this.queue_methods.isEmpty()) { String crtMethod = queue_methods.poll(); Object[] crtParamArr = queue_params.poll(); String methodName = crtMethod + "Async"; Method method; try { method = this.getClass().getMethod(methodName); try { Object retVal = method.invoke(this, crtParamArr); AsyncCallback<? extends Object> crtCallback = queue_callback.poll(); crtCallback.returnValue(retVal); } catch (Exception ex) {} } catch (SecurityException ex) { } catch (NoSuchMethodException ex) {} } else { try { synchronized(test ) { test.wait(); } } catch (InterruptedException ex) { System.out.println("READY"); } catch (Exception ex) { System.out.println("READY, but " + ex.getMessage()); } } } } /** * Asynchronously adds a method-call to the scheduler, specified by methodName with passed parameters * @param methodName The name of the currently called method. methodName + "Async" is being called * @param parameters Parameters you may want to pass to the method */ protected final void enqueueVoidCall(String methodName, Object... parameters) { List<Object> tmpParam = new ArrayList<Object>(); for (Object crt : parameters) { tmpParam.add(crt); } queue_methods.add(methodName); queue_params.add(parameters); queue_callback.add(null); test.notifyAll(); } /** * Asynchronously adds a method-call to the scheduler, specified by methodName with passed parameters * @param methodName The name of the currently called method. methodName + "Async" is being called * @param callBack An instance of AsyncCallback whose returnValue-method is called upon completion of the task. * @param parameters Parameters you may want to pass to the method */ protected final void enqueueCall(String methodName, AsyncCallback<? extends Object> callBack, Object... parameters) { List<Object> tmpParam = new ArrayList<Object>(); for (Object crt : parameters) { tmpParam.add(crt); } queue_methods.add(methodName); queue_params.add(parameters); queue_callback.add(callBack); test.notifyAll(); } /** * Complete the currently running task, optionally return values and eventually shut down. The instance of this object becomes unusable after this call. */ public void shutdown() { shutdown=true; } } ``` Now i have two classes to test things: ``` public class MySecondTask extends ThreadedClass { public void test1() { this.enqueueVoidCall("test1", null); } public void test1Async() { System.out.println("Start"); try { // do big job here } catch (Exception ex) { } System.out.println("Done"); } } ``` And the main-method starting the stuff: ``` public class TestingClass { public static void main(String[] args) { MySecondTask test = new MySecondTask(); test.start(); System.out.println("1. Thread [1]"); // CORRECTION, SHOULD BE: test.test1(); // INSTEAD OF: // test.test1Async(); for(int q=0; q<=100000; q++) { System.out.println("1:"+ new Date().getTime()+":"+ q); if ((q % 1000) == 0) { System.out.flush(); } } System.err.println("1. Thread [2]"); } } ``` Somehow, the output of the second thread always appears first (entirely), and then the rest puts out on the console. If the threads were running concurrently (which is the intended result), the console-output should be mixed?! Any idea is appreciated as well as comments to improve my coding style. --- **EDIT**: The problem cited is quite solved. Now I receive an IllegalMonitorStateException on the line where i call: ThreadedClass.notifyAll(). Maybe i got that one with the lock wrong. But a) why is it required to use synchronized() around wait() and how can i make the notifyAll()-call to unblock wait()? --- thanks in advance and best regards p.s.: you all do a good job on stack overflow. you already helped me many times without knowing it, thanks for that. keep it up!
> This means that you can call > anyMethod() which returns immediately > and which is executed by the second > thread. This sounds suspiciously like working with callables, futures and executors: * <http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html> * <http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html> * <http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html> * <http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html> Hate to break it to you, but you might really want to look into this stuff.. **Edit** to address comment below Just make your methods in your object look like this: ``` private ExecutorService executorService = Executors.newCachedThreadPool(); public Future<SomeObject> yourMethodName(String anyArguments) { return executorService.submit( new Callable<SomeObject>() { public SomeObject call() { SomeObject obj = new SomeObject(); /* Your Code Here*/; return obj; } } ); } ```
You're never calling your "threaded" dispatch mechanism ( the one that uses the queue etc ) I guess you attempt to call: ``` test.test1(); ``` Which in turn enqueue the call to *test1Async*, but by mistake you called: ``` test.test1Async(); ``` Directly making the whole execution in a single thread. Replace: ``` .... System.out.println("1. Thread [1]"); test.test1Async(); for(int q=0; q<=100000; q++) { ... ``` With: ``` .... System.out.println("1. Thread [1]"); test.test1(); for ( int q=0; q<=100000 ; q++ ) { .... ``` On the coding style, pleeeeease use the opening brace in the same line as the statement when coding in Java ( and JavaScript ) In C# , C++ and C is better as the way you have it. Also use camelCase instead of separete\_with\_underscore. Here's a document with more about [Java's coding conventions](http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html).
Java: Class entirely run in second thread / IllegalMonitorStateException
[ "", "java", "multithreading", "concurrency", "" ]
I was doing a code review and I saw assignment of single quoted strings to enum values: ``` enum { Option_1 = 'a', Option_2 = 'b' } ; ``` While this makes for slightly more readable code (though the enum's meaning should be pretty much in the name of the num), it looks silly to me. I didn't know you COULD do that and after studying it, I can see that all that happens is the binary value of the "characters" you're using gets thrown into an int. Does anyone else do this in practice? Or is this a bad practice?
It is definitely perfectly legal according to ISO C and C++ standards. And it is a fairly reasonable practice if those enum values are serialized to text (e.g. CSV) files as those characters. Otherwise, I don't see much point. I guess it could give some debugging benefits, but all good C/C++ debuggers I know can resolve enum values to corresponding symbols anyway.
That is **not** a single-quoted string — it's a character literal. Using a character literal in an enum is essentially the same as assigning a `char` to an `int` — it's totally legal and can be quite useful in many situations.
Assigning int x = 'abc' ;
[ "", "c++", "" ]
I know there are many different standards for PHP code inline documentation. Here's what I mean by inline documentation, and please correct me if there is a better term: ``` /** * This is the description for the class below. * * @package my-package * @subpackage my-subpackage * @author my-name * @version my-version * ... */ class orderActions { ... ``` What is the best and most widely-accepted form of inline documentation? In other words, what are those forms of inline documentation that everyone agrees on, and are not significantly based on opinions; the universally accepted forms of PHP in-line documentation that everyone should know about, but as a questioner, I'm not sure of yet, but after this question is answered, I will have a good overview of, not involving any particular opinions. Are there any tools to auto-generate such documentation, or does it have to be done by hand? I'm not interested in generating manuals -- I want to know how to generate the type of code commenting above, or "inline documentation."
[PHPDoc](http://manual.phpdoc.org/HTMLframesConverter/default/), like what you've posted, is a widely accepted form of PHP documentation. You can use [Doxygen](http://www.doxygen.nl/) to auto-generate the docs. Edit: In terms of generating in-line documentation in your code, I have never come across a tool that will go back and do this externally for a project. It's generally left in the realm of the IDE to generate a template while you code. Eclipse actually does a decent job of this (it's one of the few things I like about Eclipse) and I believe Netbeans does as well. Any major IDE will likely have functionality to assist with this type of template generation.
Choose from: * [Doxygen](http://www.doxygen.nl/) * [phpDocumentator](http://phpdoc.org/) * [Sami](https://github.com/FriendsOfPHP/Sami) * [ApiGen](http://www.apigen.org/) * [CakePHP API docs](https://github.com/cakephp/cakephp-api-docs) * [phpDox](http://phpdox.de/) See also the [Wikipedia article, "Comparison of documentation generators", section "by Language"](https://en.wikipedia.org/wiki/Comparison_of_documentation_generators#Language_support).
How do you document your PHP functions and classes inline?
[ "", "php", "documentation", "comments", "" ]
The following code will retrieve the body content of a url retrieved using CURL in php but not https. Can anyone tell me how I edit the code as I need to get the data returned not just the header. From the test I did here is the result. You can see it has a content-length, I just don't know how to access it. Thanks Stephen Errors: 0 string(1457) "HTTP/1.1 200 OK Date: Sat, 01 Aug 2009 06:32:11 GMT Server: Apache/1.3.41 (Darwin) PHP/5.2.4 mod\_ssl/2.8.31 OpenSSL/0.9.7l Cache-Control: max-age=60 Expires: Sat, 01 Aug 2009 06:33:11 GMT Last-Modified: Thu, 23 Nov 2006 17:44:53 GMT ETag: "97d620-44b-4565de15" Accept-Ranges: bytes Content-Length: 1099 Connection: close Content-Type: text/html " ``` <?php $curl_handle=curl_init(); $username = ""; $password = ""; $fullurl = "http://www.queensberry.com"; $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_FAILONERROR, 0); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_URL, $fullurl); $returned = curl_exec($ch); curl_close ($ch); var_dump($returned); ?> ```
Here is the solution: Try this, just keep rest of the coding same as above... ``` $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_VERBOSE, 1); //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_FAILONERROR, 0); // curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_URL, $fullurl); $returned = curl_exec($ch); curl_close ($ch); var_dump($returned); ``` Changing CURLOPT\_HEADER to 0 makes it so that only the page content is returned.
I look for the length of the header using the curl's getinfo. Then substring the response: ``` $info = curl_getinfo($ch); $start = $info['header_size']; $body = substr($result, $start, strlen($result) - $start); ```
How to Get Body content of HTTPS using CURL
[ "", "php", "curl", "https", "" ]
**BACKGROUND** I need to write a tool using .NET version 2.0 at highest (using something off the shelf is not an option for this client for political, commercial, and confidentiality/trust reasons) to migrate files from one server to another over the network. The servers are file servers for local teams, and certain team folders need to be migrated to other servers to facilitate a reorganisation. The basic idea is we read each file and stream it over the network out of hours and after a few days the data will be migrated. File permissions need to be preserved. As this will take a few days (we are talking up to several gigabytes of data, for some teams), we need to iterate over the files each night and compare the modification dates and update those that have changed. The theory is that eventually the new server will have an up to date copy of the files and the users can switch over to the new server. It is of course not quite this simple, but we have a design we think should work :) **THE PROBLEM** So in theory we just open the file, stream it over the network, and write it at the other end, right? :) Unfortunately, on the servers themselves, the file shares were created at folder paths such as: > D:\Data\Team Shares\DIVISION\DEPARTMENT\NAME OF TEAM - COULD BE FAIRLY LONG\ For each user, this path is mapped to a drive, for example it would be shared as \\SERVER\TEAMNAME and mapped to the T: drive. This has caused the situation where the files as visible from the T: drive are within the `MAX_PATH` limitation, however when viewed locally on the server itself, they go way beyond it. We cannot access the files using the network shares as this tool needs to be generic, to run on hundreds of these servers, and there is no standard way to tell which file shares are ones we should be moving and those which are not - there is no naming convention standard even. Also, occasionally there are sub-shares of other shares and so we exceed the `MAX_PATH` limit twice over! I am aware of the workaround to specify paths using the "\\?\" prefix, which treats the path as a UNC path and allows a theoretical maximum of 32k characters. This workaround is implemented at the Win32 API level, the System.IO namespace is (mostly) basically just a thin wrapper around native Win32 API functions, however Microsoft have "helpfully" implemented extra (incorrect) validation before handing the call off to the API. In this case, the .NET Framework is rejecting the path because it claims that '?' is an invalid path character. So my question is... is there a way I haven't thought of that will allow me to work around this without having to completely rewrite the almost the whole System.IO namespace, making a load of P/Invoke calls, just to remove this annoying validation?
The BCL team did a 3 part series on exactly why these choices were made and what the work arounds are. If you haven't read that yet I suggest you do as it's a great source of information on the subject * <http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx>
I ran into one third-party solution that may help: [AlphaFS](http://www.codeplex.com/alphafs "AlphaFS").
Accessing files beyond MAX_PATH in C#/.NET
[ "", "c#", "winapi", "pinvoke", "fileshare", "max-path", "" ]
using jQuery I have the following code: ``` var selectedIdsArray = $("#selectId option:selected").map(function(){return this.value;}); var selectedIdsStr = $.map(selectedIdsArray, function(val){ return "" + val + "";}); ``` It successfully retrieves a string of ids eg. selectedIdsStr = "2,45,245,1" from an `<select multiple='multiple'>` element. I was wondering if there is a more efficient way (less code) to achieve this? Thanks!
You could change the second line like this: ``` var selectedIdsStr = selectedIdsArray.get().join(','); ```
``` var selectedIdsStr = $("#selectId option:selected").map(function(){ return $(this).val(); }).get().join(","); ``` adapted from <http://docs.jquery.com/Traversing/map#callback>
JQuery: Turn array input values into a string optimization
[ "", "javascript", "jquery", "string", "select", "" ]
It's been a while since I've installed PHP for Windows, but every guide I've seen online tells me to set IIS to recognize .PHP files with php5isapi.dll. However, I can't seem to find php5isapi.dll anywhere after installing PHP 5.3.0 and PHP 5.2.10. If I recall correctly it should be in C:\InstallDir Am I missing something important?
I would try downloading the binaries (rather than the installer). I found php5isapi.dll in those zips, but the .exe/.msi doesn't seem to install that dll.
[FastCGI](http://www.fastcgi.com/drupal/) replaced `php5isapi.dll`
Why is php5isapi.dll missing after installing PHP for Windows?
[ "", "php", "installation", "" ]
I am in the process of converting an in-house **web app** to a **winform** **app** for disconnected reasons and I hit the following snag. In the `Function SaveMe()` on the webapp there is the following code on the Person.ascx.vb page --> ``` //get dataset from session Dim dsPerson As Data.DataSet = CType(Session.Item("Person" & Me.UniqueID), DataSet) //if no rows in dataset, add If dsPerson.Tables(0).Rows.Count = 0 Then Dim rowPerson As Data.DataRow = dsPerson.Tables(0).NewRow dsPerson.Tables(0).Rows.Add(FillPersonRow(rowPerson)) Else //otherwise update ....more code here ``` The part I am stuck on is how to logically create a dataset on a WinForm app? Should I just scrape all the fields and throw them into a DataSet? How(*this is what I will research/try while waiting for advice from **SO***)? --- **EDIT** The Session is getting created/populated in the `LoadMe()` Sub, like so --> ``` //load person Dim dsTemp As Data.DataSet = BLL.Person.GetPerson(PersonID) //save to session state Session.Add("Person" & Me.UniqueID, dsTemp) ``` --- **EDIT** What I am trying to do is create a Form level variable --> `private DataSet _personInfo;` to hold the DataSet then in my `FormPaint(int personID)` I call the following: ``` _personInfo = ConnectBLL.BLL.Person.GetPerson(personID); ``` I then use that to populate the various fields on the Form. Next, on `btnUpdate_Click()` I try the following but to no avail: ``` void btnUpdate_Click(object sender, EventArgs e) { var areChanges = _personInfo.HasChanges(); if (areChanges) { var whatChanged = _personInfo.GetChanges(); var confirmChanges = MessageBox.Show( "Are you sure you want to make these changes: " + whatChanged.Tables[0].Rows[0].ItemArray.ToString(), "Confirm Member Info Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Hand); if (confirmChanges == DialogResult.Yes) { _personInfo.AcceptChanges(); ConnectBLL.BLL.Person.Update(_personInfo); } } FormPaint(HUD.PersonId); } ``` I am unclear what I am doing wrong? Am I missing a step? Thank you
First, If you want a good explanation of the issue that Jacob raised read the following article... <http://www.knowdotnet.com/articles/datasetmerge.html> And I agree with the others that you seem to be making it harder than it needs to be. You are not clear what the ConnectBLL class is...is that a custom bizness object or a strongly typed dataset. To do databinding which will automatically save would be a very long post so in lieu of that here are a couple of links. <http://www.codeguru.com/columns/vb/article.php/c10815> <http://support.microsoft.com/kb/313482> <http://msdn.microsoft.com/en-us/library/aa984336(VS.71).aspx> Those were the first links I found on google using (step by step instruction on winforms databinding with a strongly typed dataset) as the search string. You might find a better one. The codeguru link looked pretty good. The other to are more thorough at the expense of being more technical. Best of all...if you can spring for Chris Sells book in winforms development, the chapters on data binding are excellent (along with all of the other chapters.) [http://www.amazon.com/Windows-Forms-Programming-Microsoft-Development/dp/0321267966/ref=sr\_1\_1?ie=UTF8&qid=1249525202&sr=8-1](https://rads.stackoverflow.com/amzn/click/com/0321267966) Hope this helps.
In that snippet, the DataSet comes from session. When is it set ? You certainly can use a DataSet in a WinForms application. Is it the databinding, you are having trouble with ?
Trying to maintaining a DataSet in WinForm App
[ "", "c#", ".net", "vb.net", "winforms", "dataset", "" ]
In Java EE 1.4 using JAX-RPC 1.1, how can i expose web service, so the wsdl has a complex type (person) where one of the properties of the person is a date which is shown in the WSDL/XSD as only a date (such as a birthdate) instead of a dateTime (where the time is not wanted) in the WSDL/XSD? i would like the xsd referenced in the wsdl to have ``` <xs:element name="birthdate" type="xs:date"/> ``` instead of ``` <xs:element name="birthdate" type="xs:dateTime"/> ``` java.util.Calendar and java.util.Date both seem to cause the xsd datatype to be dateTime when rendered in in wsdl/xsd. I know java EE 1.4 doesnt have the annotations like java EE 5, but is there any way to tell the web service to use the xs:date datatype?
I actually did figure out how to do this properly. in the WEB-INF/wsdl/(schemaname).xsd I changed the datatype to date from dateTime and redeploy the service and it works with my existing java.util.Calendar types.
I don't think you'll be able to achieve this, JAX-RPC just doesn't have the flexibility (which is why it was killed in JavaEE 5). In general, I usually find that WSDL generators do not have the expressive power to generate the exact WSDl I want, and so I tend to use them to generate a WSDL as a starting point, and then modifying the result. You then server up the WSDL as a static file rather than as a generated one. It's not ideal, but it's not a big deal either.
Java web service, xsd date instead of dateTime
[ "", "java", "web-services", "xsd", "wsdl", "jax-rpc", "" ]
In SQLAlchemy, it appears I'm supposed to pass an expression to [`filter()`](http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators) in certain cases. When I try to implement something like this myself, I end up with: ``` >>> def someFunc(value): ... print(value) >>> someFunc(5 == 5) True ``` **How do I get the values passed to `==` from inside the function?** I'm trying to achieve something like this ``` >>> def magic(left, op, right): ... print(left + " " + op + " " + right) >>> magic(5 == 5) 5 == 5 ``` What about if one of the parameters was an object?
You can achieve your example if you make "op" a function: ``` >>> def magic(left, op, right): ... return op(left, right) ... >>> magic(5, (lambda a, b: a == b), 5) True >>> magic(5, (lambda a, b: a == b), 4) False ``` This is more Pythonic than passing a string. It's how functions like [`sort()`](http://wiki.python.org/moin/HowTo/Sorting) work. Those SQLAlchemy examples with `filter()` are puzzling. I don't know the internals about SQLAlchemy, but I'm guessing in an example like `query.filter(User.name == 'ed')` what's going on is that `User.name` is a SQLAlchemy-specific type, with an odd implementation of the `__eq()` function that generates SQL for the `filter()` function instead of doing a comparison. Ie: they've made special classes that let you type Python expressions that emit SQL code. It's an unusual technique, one I'd avoid unless building something that's bridging two languages like an ORM.
An even more pythonic variant of Nelson's solution is to use the operator functions from the [operator](http://docs.python.org/library/operator.html) module in the standard library; there is no need to create your own lambdas. ``` >>> from operator import eq >>> def magic(left, op, right): ... return op(left, right) ... >>> magic(5, eq, 5) True ```
Passing expressions to functions
[ "", "python", "function", "arguments", "operators", "" ]
I have this rather complex query that grabs data from three tables, and now I want it to be even more complicated (Oh dear)! I'd like the last posted feature to be displayed in it's own section of the page, and that's pretty easy by selecting the last entry in the table. However, for the complex query (the main page of the site), I'd like to be able to NOT have this feature displayed. I'd like to `union` the following query to my previous query, but it isn't returning the correct results: ``` SELECT features.featureTitle AS title, features.featureSummary AS body, features.postedOn AS dummy, DATE_FORMAT( features.postedOn, '%M %d, %Y' ) AS posted, NULL, NULL, staff.staffName, features.featureID FROM features LEFT JOIN staff ON features.staffID = staff.staffID WHERE features.postedOn != MAX(features.postedOn) ORDER BY dummy DESC LIMIT 0,15 ``` This query returns the following error: > MySQL error: #1111 - Invalid use of group function Is there any way around this?
The `max` query needs to be in its own subquery, so your final SQL should be:: ``` SELECT features.featureTitle AS title, features.featureSummary AS body, features.postedOn AS dummy, DATE_FORMAT( features.postedOn, '%M %d, %Y' ) AS posted, NULL, NULL, staff.staffName, features.featureID FROM features LEFT JOIN staff ON features.staffID = staff.staffID WHERE features.postedOn != (select max(features.postedOn) from features) ```
the problem you have is that is that you need to find the max (latest) feature from the table, while going over each row, but MAX() is a group function - you have to group all rows to use it. you can use a sub-select to get the id of the last feature: ``` WHERE featureId <> (SELECT featureId From features ORDER BY postedOn DESC LIMIT1) ``` there is a problem with this approach - the subselect is run for every row, but it is not that expensive.
SQL Query to Select Everything Except the Max Value
[ "", "mysql", "sql", "mysql-error-1111", "" ]
I've got a program that is tailing a growing file. I'm trying to avoid grabbing a partial line from the file (e.g. reading before the line is completely written by the other process.) I know it's happening in my code, so I'm trying to catch it specifically. Is there a sane way to do this? Here's what I'm trying: ``` if (getline (stream, logbuffer)) { if (stream.eof()) { cout << "Partial line found!" << endl; return false; } return true; } return false; ``` However, I can't easily reproduce the problem so I'm not sure I'm detecting it with this code. std::getline strips off newlines, so I can't check the buffer for a trailing newline. My log message (above) is NEVER tripping. Is there some other way of trying to check what I want to detect? Is there a way to know if the last line I read hit EOF without finding a EOL character? Thanks.
This will never be true: ``` if (getline (stream, logbuffer)) { if (stream.eof()) { /// will never get here ``` If [`getline()`](http://en.cppreference.com/w/cpp/string/basic_string/getline) worked, the stream cannot be in an eof state. The [`eof()`](http://en.cppreference.com/w/cpp/io/basic_ios/eof) and related state tests only work on the results of a previous read operation such as `getline()`- they do not predict what the next read will do. As far as I know, there is no way of doing what you want. However, if the other process writes a line at a time, the problems you say you are experiencing should be very rare (non -existent in my experience), depending to some extent on the OS you are are using. I suspect the problem lies elsewhere, probably in your code. Tailing a file is a very common thing to do, and one does not normally need to resort to special code to do it. However, should you find you do need to read partial lines, the basic algorithm is as follows: ``` forever do wait for file change read all possible input using read or readsome (not getline) chop input into lines and possible partial line process as required end ```
An `istream` object such as `std::cin` has a [`get` function](http://www.cplusplus.com/reference/iostream/istream/get/) that stops reading when it gets to a newline without extracting it from the stream. You could then `peek()` or `get()` it to see if indeed it is a newline. The catch is that you have to know the maximum length of a line coming from the other application. Example (untested) code follows below: ``` char buf[81]; // assumes an 80-char line length + null char memset(buf, 0, 81); if (cin.get(buf, 81)) { if (cin.peek() == EOF) // You ran out of data before hitting end of line { cout << "Partial line found!\n"; } } ```
std::getline and eol vs eof
[ "", "c++", "file-io", "" ]
How to encrypt file with public key, that was added to current keyring, with using c# and command line? Thanks.
You can use my implementation i wrote one year ago. I know that it's a bit ugly. You need pgp.exe and some background about it. see [my blog post](http://www.ercueser.com/post/2009/02/17/PGP-File-Encrypt-Decrypting-in-C.aspx). ``` /// <summary> /// Encryps given file using PGP Public Key /// </summary> /// <param name="filename"></param> public string Encrypt(string filename, bool isBinary, ref string outstr){ string outputfilename = filename; //We use stringbuilder for performance considerations StringBuilder sb = new StringBuilder(); sb.Append("/c "); sb.Append(""); sb.Append(PGPLocation); sb.Append(" +force -es "); sb.Append("\""); sb.Append(filename); sb.Append("\" "); sb.Append(ToUserName); sb.Append(" -u "); sb.Append(MyUserName); sb.Append(" -z "); sb.Append(PassPhrase); sb.Append(" "); // Use binary indicator because PGP produces different outputs for binary and plain text files if (isBinary) sb.Append("-a"); proc.StartInfo.Arguments = sb.ToString(); //proc.StartInfo.Arguments = "/c pgp +force -es "+filename+" cumacam -u bugra"; proc.Start(); if (WaitForInfinity) proc.WaitForExit(); else proc.WaitForExit(WaitTime); //string res = proc.StandardOutput.ReadToEnd(); outstr = proc.StartInfo.Arguments; if (proc.HasExited) { int ab = proc.ExitCode; if (ab != 0) { FireError(Convert.ToInt32(ErrorTypes.PGPEncryptError), "Erro No: " + ab.ToString() + "in PGP. Details: "+" "+proc.StandardOutput.ReadToEnd()); return null; } else if (!isBinary) return outputfilename+".pgp"; return outputfilename + ".asc"; } return null; } ```
Well, the [bouncy castle cryptography library](http://www.bouncycastle.org/csharp/) for C# can be used to encrypt and decrypt PGP; it's what we use internally for PGP crypto work. It's entirely self-contained, so no dependencies on existing programs or libraries. Keep in mind, however, that it's a library not a command line program. The source code comes with some example command line program utilities you can build if you need to use it CLI.
PGP Freeware and c#
[ "", "c#", "encryption", "pgp", "" ]
I have some JavaScript code that looks like: ``` function statechangedPostQuestion() { //alert("statechangedPostQuestion"); if (xmlhttp.readyState==4) { var topicId = xmlhttp.responseText; setTimeout("postinsql(topicId)",4000); } } function postinsql(topicId) { //alert(topicId); } ``` I get an error that `topicId` is not defined Everything was working before I used the `setTimeout()` function. I want my `postinsql(topicId)` function to be called after some time. What should I do?
``` setTimeout(function() { postinsql(topicId); }, 4000); ``` You need to feed an anonymous function as a parameter instead of a string. The latter method shouldn't even work - per the ECMAScript specification - but browsers are just lenient. This is the proper solution. Don't ever rely on passing a string as a 'function' when using `setTimeout()` or `setInterval()`. It is slower, because it has to be evaluated and it just isn't right. ## UPDATE: As Hobblin said in his [comments](https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback#comment8933108_1190642) to the question, now you can pass arguments to the function inside setTimeout using [`Function.prototype.bind()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_objects/Function/bind). **Example:** ``` setTimeout(postinsql.bind(null, topicId), 4000); ```
In modern browsers (ie IE11 and beyond), the "setTimeout" receives a third parameter that is sent as parameter to the internal function at the end of the timer. Example: ``` var hello = "Hello World"; setTimeout(alert, 1000, hello); ``` More details at [setTimeout() global function - MDN](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout)
How can I pass a parameter to a setTimeout() callback?
[ "", "javascript", "parameters", "callback", "settimeout", "" ]
I am trying to rearchitect my build technique for creating Java jar files which depend on common 3rd party jar files. (GlazedLists, Apache Commons, etc.) I had been chucking them all into {Java JRE dir}/lib/ext so they would automatically be seen by the JRE, but that led to problems like not remembering that I need to distribute certain jar files, so I'd like to learn to be more explicit. So I moved them all into c:\appl\java\common\, added them to the Eclipse build path, aand defined this in my ant file: ``` <path id="javac_classpath"> <fileset dir="${libDir}"> <include name="*.jar"/> </fileset> <fileset dir="c:/appl/java/common"> <include name="*.jar"/> </fileset> </path> ``` I have my Class-Path manifest header set to "." in my `jar` task but that doesn't seem to work even if I put the relevant jar files into the same directory as my application jar file. I can add them all manually one-by-one to the Class-Path header, but I'm wondering, is there an easier way to get the Class-Path header setup properly?
This is all you need: ``` <path id="build-classpath"> <fileset dir="${dist}/lib"> <include name="*.jar"/> </fileset> </path> <manifestclasspath property="lib.list" jarfile="${dist}/lib/myprog.jar"> <classpath refid="build-classpath"/> </manifestclasspath> <jar jarfile="${dist}/lib/myprog.jar" basedir="${build}" includes="com/my/prog/**" > <manifest> <attribute name="Main-Class" value="com.my.prog.MyProg"/> <attribute name="Class-Path" value="${lib.list}"/> </manifest> </jar> ``` As you can probably see, it assumes you've compiled your Java classes and output them to `${build}`. It also assumes you've copied your jarfiles to `${dist}/lib`. That said, it would be worth looking into other build systems which have built-in support for dependencies, such as Maven and Gradle. These other build systems have already thought through many common project structures and build operations, so you don't have to script everything down to the last detail.
What you want is a [mapper](http://ant.apache.org/manual/Types/mapper.html). Flattenmapper is probably the easiest, but essentially you need to create a path element which specifies your classpath, then use a pathconvert on it to turn it into a string that can be included in your manifest. Edit: you can use include rules to build the path element, so everything in a directory ending with jar would be `**/*.jar`
ant, jar files, and Class-Path oh my
[ "", "java", "ant", "jar", "" ]
I have a database with several tables, 5 of which are dedicated to specific publication types. Each of these 5 have a one->many relationship with a status table and a people table. All of these tables are tied together using a unique "pubid". I have a view which includes the pubid (for all 5 types), along with their associated keywords. When a user does a keyword search and the results span across more than 1 of those 5 publication type tables I am really not sure how to handle it. If there was only a single publication type (so just one table that had a 1->many) it would be very easy to accomplish with a nested join, something like: ``` SELECT * FROM articles INNER JOIN status ON articles.spubid = status.spubid INNER JOIN people ON articles.spubid = people.spubid WHERE people.saffil = 'ABC' ORDER BY people.iorder, articles.spubid; ``` In that example 'articles' is one of the 5 tables I mentioned that has a 1->many relationship. Lets say that the keyword search brings back results that include articles, books and papers. How can I achieve this same end with that many different tables? If I were to figure out how to use a JOIN in that case the Cartesian product would be so large that I think the overhead to parse it out into a usable format would be too high. What are my other options in this case?
Why are they in separate tables? Are the columns that different? And what columns do you want to return (never ever use select \* in production especially with joins), are they different between the different types in your query? If you can get the columns to be the same I suggest you use UNION ALL. Even if the columns are different by supplying all that you need in each part of the union statement (giving the value of null for those columns that set of tables doesn't have), you can still get what you want. Simplified code follows: ``` SELECT articlename, articlestatus, author, ISBN_Number FROM articles INNER JOIN status ON articles.spubid = status.spubid INNER JOIN people ON articles.spubid = people.spubid WHERE people.saffil = 'ABC' UNION ALL SELECT papername, paperstatus, author, null FROM papers INNER JOIN status ON papers.spubid = status.spubid INNER JOIN people ON papers.spubid = people.spubid WHERE people.saffil = 'ABC' ```
You could create a view that was the union of all the various tables. The tricky bit is to make sure that all the queries being UNIONed have the same fields, so you'll need to stub a few in each one. Here's a simplified example with only two tables: ``` CREATE VIEW AllTables AS SELECT Afield1, Afield2, NULL as Bfield1, NULL as Bfield2 FROM Atable UNION SELECT NULL as Afield1, NULL as Afield2, Bfield1, Bfield2 FROM Btable; ``` You could use something other than NULL as the stub value if necessary, of course. Then you run your query against the view. If you need to vary the formatting according to the publication type, you could include the originating table as part of the view (ie, add `"'magazine' AS publication_type"` or something similar to each of your selects).
How to handle multiple one->many relationships?
[ "", "sql", "database", "select", "join", "" ]
I tried to create a custom .NET attribute with the code below but accidentally left off the subclass. This generated an easily-fixed compiler error shown in the comment. ``` // results in compiler error CS0641: Attribute 'AttributeUsage' is // only valid on classes derived from System.Attribute [AttributeUsage(AttributeTargets.Class)] internal class ToolDeclarationAttribute { internal ToolDeclarationAttribute() { } } ``` My question is how does the compiler know the `[AttributeUsage]` attribute can only be applied to a subclass of `System.Attribute`? Using .NET Reflector I don't see anything special on the `AttributeUsageAttribute` class declaration itself. Unfortunately this might just be a special case generated by the compiler itself. ``` [Serializable, ComVisible(true), AttributeUsage(AttributeTargets.Class, Inherited=true)] public sealed class AttributeUsageAttribute : Attribute { ... ``` I would like to be able to specify that my custom attribute can only be placed on subclasses of a particular class (or interface). Is this possible?
> I would like to be able to specify that my custom attribute can only be placed on subclasses of a particular class (or interface). Is this possible? Actually, there is a way to do this for subclasses (but not interfaces) using `protected` - see [Restricting Attribute Usage](http://marcgravell.blogspot.com/2009/06/restricting-attribute-usage.html). To reproduce the code (but not the discussion): ``` abstract class MyBase { [AttributeUsage(AttributeTargets.Property)] protected sealed class SpecialAttribute : Attribute {} } class ShouldBeValid : MyBase { [Special] // works fine public int Foo { get; set; } } class ShouldBeInvalid { // not a subclass of MyBase [Special] // type or namespace not found [MyBase.Special] // inaccessible due to protection level public int Bar{ get; set; } } ```
`AttributeUsageAttribute` is just a magic class (like `Attribute` itself is). This is a built-in compiler rule, and you cannot do something like that for your own attributes.
Specify required base class for .NET attribute targets
[ "", "c#", ".net", "attributes", "custom-attributes", "" ]
There is a family of methods ([birddog, shadow, and follow](http://apiwiki.twitter.com/Streaming-API-Documentation#birddog))in the Twitter API that opens a (mostly) permanent connection and allows you to follow many users. I've run the sample connection code with cURL in bash, and it works nicely: when a user I specify writes a tweet, I get a stream of XML in my console. My question is: **how can I access data with PHP that isn't returned as a direct function call, but is streamed?** This data arrives sporadically and unpredictably, and it's not something I've ever dealt with nor do I know where to begin looking for answers. Any advice and descriptions of libraries or pitfalls would be appreciated.
[fopen](http://www.php.net/manual/en/function.fopen.php) and [fgets](http://www.php.net/manual/en/function.fgets.php) ``` <?php $sock = fopen('http://domain.tld/path/to/file', 'r'); $data = null; while(($data = fgets($sock)) == TRUE) { echo $data; } fclose($sock); ``` This is by no means great (or even good) code but it ***should*** provide the functionality you need. You will need to add error handling and data parsing among other things.
I'm pretty sure that your script will time out after ~30 seconds of listening for data on the stream. Even if it doesn't, once you get a significant server load, the sheer number of open and listening connections will bring the server to it's knees. I would suggest you take a look at an AJAX solution that makes a call to a script that just stores a Queue of messages. I'm not sure how the Twitter API works exactly though, so I'm not sure if you can have a script run when requested to get all the tweets, or if you have to have some sort of daemon append the tweets to a Queue that PHP can read and pass back via your AJAX call.
How to deal with streaming data in PHP?
[ "", "php", "streaming", "twitter", "" ]
I have a complex object that I create in a PHP script. I am looking for a way to store this object such that subsequent requests do not have to recreate it, or spend time unserializing and rebuilding it. Using xdebug I find that I spend half of the entire request time building this object. Even when I store the object explicitly in APC (or memcache), the time to unserialize it and load all of the classes takes almost as long as creating the object in the first place. I do not know if it is possible to store and later load a "compiled" object in PHP. Is this possible? Are there other solutions? I am not sure that this is possible, but I thought I should ask the community. EDIT: The object is a binary tree, and used as a decision tree. The code is basically an API that is required to quickly return an answer from the tree. This all needs to perform at an ever increasing rate so I am trying to maximize the performance wherever possible.
As far as I'm aware, it's not possible to cache objects in PHP without serializing. In general, however, caching mechanisms (APC, Memcache, etc) are really trying to remove the db connection(s) more than improve performance (and thereby decrease the overall DB strain). This is *definitely* how memcache, et al are employed with regards to Drupal. In other words, the caching mechanisms should allow you to scale, though they may not particularly improve performance. Implementing a caching mechanism should allow you to more easily scale outward, even if the performance per machine is no better than before for a single connection. At a certain threshold, DB performance will degrade sharply, and the caching mechanisms should help alleviate that issue.
Look into the [Igbinary](http://opensource.dynamoid.com/) PHP extension. It is a drop in replacement for serialize and unserialize and it may suit your needs. It stores objects in a binary format instead of a string which decreases memory usage and also decreases the time to serialize and unserialize objects. Although this does go through the process of unserializing an object, the binary format may increase performance enough to make this process reasonable for use in your application.
Cache Object in PHP without using serialize
[ "", "php", "caching", "serialization", "" ]
I want to retrieve the most recent `requestid` from table tblquoteproposal` for perticular customerId here 3, in this example ID 2 & ID 4. table tblrequest requestid Customerid 6 2 7 4 8 3 9 3 Table `tblquoteproposal` ``` id requestid QuotePraposalLink comment 1 6 jgj mghm 2 7 jhgj hjgj 3 8 xyz1 rifsf *4 8 xyz2 ri2sf* 5 9 xyz3 ri3sf *6 9 xyz4 ri4sf* ``` In this table `requestid` is foreign key. There is also another table `tblrequest` which has `requestid` as primary key. I have written the following query but it doesn't give me the right results: ``` SELECT r.RequestId,r.ConsultantId,(SELECT concat(FirstName,' ',LastName) FROM tbluser WHERE UserId = v_userId) as "Customer", r.RequestDate,r.QuoteDetailsFileLink,r.Requestcomment,r.CustomerId, qp.QuotePraposalLink,qp.Comment FROM tblrequest r LEFT OUTER JOIN tblquoteproposal qp ON r.RequestId=qp.RequestId WHERE r.customerid=v_userId GROUP BY r.RequestId ORDER BY qp.id ; ```
Why not try: ``` SELECT MAX(id) FROM tblquoteproposal GROUP BY requestid ``` And feed the results of this query to whatever you need? (This can be a subquery). For example, your complete solution may be as follows (I'm using LEFT OUTER JOIN because you did so, I'm not sure it's the right way, maybe INNER JOIN is more suitable): ``` SELECT ... your fields ... FROM tblquoteproposal p LEFT OUTER JOIN tblrequest r on p.requestid = r.requestid WHERE p.id IN ( SELECT MAX(id) FROM tblquoteproposal GROUP BY requestid ) ```
``` SELECT * FROM ( SELECT requestid, MAX(id) AS mid FROM tblquoteproposal GROUP BY requestid ) m JOIN tblrequest tr ON tr.id = tm.requestid JOIN tblquoteproposal tqp ON tqp.id = m.mid ```
Retrieve last (latest) distinct highest value
[ "", "sql", "mysql", "" ]
I have a question about the result of LINQ and Lambda query. For example, I have the following codes: ``` class ClassA<T> { public string Name { get; set; } public T ObjectT { get; set; } } List<ClassA<T>> list; // list is populated // First way to get instance from list, reference type? ClassA<T> instance1 = list.Select(x=> x).Where(x=>x.Name == "A"). FirstOrDefault(); // Second way to clone or copy instance from the list ClassA<T> instance2 = list.Select(x=> new ClassA<T> { Name = x.Name, ObjectT = x.ObjectT}). Where( x=> x.Name = "A").FirstOrDefault(); ``` It is obviously that instance2 is a clone or copy of an instance found in list. How about instance1? Is this one a new instance or just a reference to an instance in the list? If instance1 is an object reference to list's item, any change to its property may change the same object in the list. Is that right? If that's the case and I don't want to have any implicit effect on objects in the list, I think I should use the second strategy. However, if I do want any changes in the retrieved instances also have the same changes in the list, I should use strategy 1. Not sure if my understanding is correct. Any comments?
Since your `ClassA<T>` is a `class` (not a `struct`), `instance1` is a reference to the same object that is inside the `list`. About the strategy, if you didn't want the users of your list to be able to mess around the list elements, I would suggest these alternatives: * Make `ClassA<T>` a `struct`. This way any query will return copy of the elements in the list; * Make `ClassA<T>` implement `IClonable` like below, and clone it before passing to a untrustworthy code. Beware that the `ObjectT` property might be a class. So, even after you clone the `ClassA<T>` object, the `ObjectT` property will be a reference to the same object, and any user code will be able to modify it. Maybe, you'll need to clone `ObjectT` too; --- ``` class ClassA<T> : ICloneable { public string Name { get; set; } public T ObjectT { get; set; } public ClassA<T> Clone() { return (ClassA<T>)this.MemberwiseClone(); } object ICloneable.Clone() { return this.Clone(); } } ``` --- As suggested, you could use an extension method to avoid null reference problems. As you can see, there are several solutions to the problem. You should choose the one that better fit to your specific problem. ``` static class CloneableExt { public static T CloneNull<T>(this T obj) where T : class, ICloneable { if (obj == null) return null; return (T)obj.Clone(); } } ``` **EDIT 1**: CloneableExt added
it will be a reference to the object in the list. What you could do, is create a copy using a Clone() function that returns a duplicate resulting in the code ``` list.Where(x => x.Name == "A").FirstOrDefault().Clone() ``` Note that Select(x => x) is unnecessary. Clone would be an extension method along the lines of ``` public static ClassA<T> Clone<T>(this ClassA<T> self) { if (self == null) return null; return new ClassA { Name = self.Name, ObjectT = self.ObjectT } } ```
Question about LINQ and Lambda requery
[ "", "c#", "linq", "lambda", "" ]
my problem is as follows: Im building a console application which asks the user for the numbers of objects it should create and 4 variables that have to be assigned for every object. The new objects name should contain a counting number starting from 1. How would you solve this? Im thinking about a class but im unsure about how to create the objects in runtime from userinput. Is a loop the best way to go? What kind of class, struct, list, array .... would you recommend. The variables in the object are always the same type but i need to name them properly so I can effectivly write methods to perform operations on them in a later phase of the program. Im just learning the language and I would be very thankful for a advice on how to approach my problem.
If I understand your problem correctly: ``` class MyClass { public int ObjectNumber { get; set; } public string SomeVariable { get; set; } public string AnotherVariable { get; set; } } // You should use keyboard input value for this int objectsToCreate = 10; // Create an array to hold all your objects MyClass[] myObjects = new MyClass[objectsToCreate]; for (int i = 0; i < objectsToCreate; i++) { // Instantiate a new object, set it's number and // some other properties myObjects[i] = new MyClass() { ObjectNumber = i + 1, SomeVariable = "SomeValue", AnotherVariable = "AnotherValue" }; } ``` This doesn't quite do what you described. Add in keyboard input and stuff :) Most of this code needs to be in some kind of `Main` method to actually run, etc. In this case, I've chosen a `class` to hold your 4 variables. I have only implemented 3 though, and I've implemented them as *properties*, rather than fields. I'm not sure this is necessary for your assignment, but it is generally a good habit to not have publically accessible fields, and I don't want to be the one to teach you bad habits. See [auto-implemented properties](http://msdn.microsoft.com/en-us/library/bb384054.aspx). You mentioned a `struct`, which would be an option as well, depending on what you want to store in it. Generally though, a class would be a safer bet. A loop would indeed be the way to go to initialize your objects. In this case, a `for` loop is most practical. It starts counting at `0`, because we're putting the objects in an array, and array indexes in C# always start at `0`. This means you have to use `i + 1` to assign to the object number, or the objects would be numbered 0 - 9, just like their indexes in the array. I'm initializing the objects using [object initializer syntax](http://msdn.microsoft.com/en-us/library/bb397680.aspx), which is new in C# 3.0. The old fashioned way would be to assign them one by one: ``` myObjects[i] = new MyClass(); myObjects[i].ObjectNumber = i + 1; myObjects[i].SomeVariable = "SomeValue"; ``` Alternatively, you could define a [constructor](http://msdn.microsoft.com/en-us/library/ace5hbzh.aspx) for `MyClass` that takes 3 parameters. One last thing: some people here posted answers which use a *generic List* (`List<MyClass>`) instead of an array. This will work fine, but in my example I chose to use the most basic form you could use. A List does not have a fixed size, unlike an array (notice how I initialized the array). Lists are great if you want to add more items later, or if you have no idea beforehand how many items you will need to store. However, in this case, we have the keyboard input, so we know exactly how many items we'll have. Thus: array. It will implicitly tell whoever is reading your code, that you do not intend to add more items later. I hope this answered some questions, and raised some new ones. See just how deep the rabbit hole goes :P
Use a list or an array. List example: ``` int numberOfObjects = 3; List<YourType> listOfObjects = new List<YourType>(); for(int i = 0 ; i < numberOfObjects ; i++ ) { // Get input and create object .... // Then add to your list listOfObjects.Add(element); } ``` Here, listOfObjects is a Generic list that can contain a variable number of objects of the type YourType. The list will automatically resize so it can hold the number of objects you add to it. Hope this helps.
how to create multiple objects and enumerate them in c#
[ "", "c#", "" ]
**Prerequisite Detail** 1. Working in .NET 2.0. 2. The code is in a common library that could be called from ASP.Net, Windows Forms, or a Console application. 3. Running in a Windows Domain on a corporate network. **The Question** What is the best way to get the current user's SID? I'm not talking about the identity that is executing the application, but the user who is accessing the interface. In background applications and desktop based applications this should be the identity actually executing the application, but in ASP.Net (without impersionation) this should be the HttpContext.Current.User SID. **The Current Method** This is what I've got right now. It just seems... wrong. It's nasty. Is there a better way to do this, or some built in class that does it for you? ``` public static SecurityIdentifier SID { get { WindowsIdentity identity = null; if (HttpContext.Current == null) { identity = WindowsIdentity.GetCurrent(); } else { identity = HttpContext.Current.User.Identity as WindowsIdentity; } return identity.User; } } ```
I don't think there is a better way at getting at this info--you've got to get at the WindowsPrincipal somehow and .NET's rather clean API abstracts that behind the User object. I'd just leave this nice and wrapped up in a method and call it a day. Well, ok, there is one thing you should do (unless your web users are *always* going to be WindowsIdentity), which would be to check for null identity and handle it according to whatever rules you have.
Without the use of third-party libraries This code will give correct results, if the user changed his user name. ``` String SID = ""; string currentUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); RegistryKey regDir = Registry.LocalMachine; using (RegistryKey regKey = regDir.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\SessionData", true)) { if (regKey != null) { string[] valueNames = regKey.GetSubKeyNames(); for (int i = 0; i < valueNames.Length; i++) { using (RegistryKey key = regKey.OpenSubKey(valueNames[i], true)) { string[] names = key.GetValueNames(); for (int e = 0; e < names.Length; e++) { if (names[e] == "LoggedOnSAMUser") { if (key.GetValue(names[e]).ToString() == currentUserName) SID = key.GetValue("LoggedOnUserSID").ToString(); } } } } } }MessageBox.Show(SID); ```
What is the best way to get the current user's SID?
[ "", "c#", ".net", "asp.net", "" ]
I seem to have misunderstanding here. I need to implement public/private key encryption (PKCS) with digital signing. I've found the following classes in .Net framework. 1. RSACryptoServiceProvider 2. DSACryptoServiceProvider I want to encrypt files then digitally sign them, and at the receiver verify the signature and then decrypt. The class DSACryptoServiceProvider has the function VerifySignature which takes both the signed signed value and the un-signed value! My question here is whether to encrypt-then-sign or sign-then-encrypt? If i send the un-signed key (along with the signed key) of the encryption key, then any third party will be able to decrypt the text
Signing means: 1. Sender calculates a hash from the data before sending 2. Sender encrypts that hash with senders private key 3. Receiver calculates hash from the received data 4. Receiver decrypts senders signature with senders public key 5. Receiver compares the locally calculated hash and the decrypted signature I suppose VerifySignature() does steps 4) and 5) In steps 1) and 3) you create the hash for the encrypted or unencrypted data, your choice as long as sender and receiver do it exactly the same. Note that this is independent of the actual encryption of the data, you can even sign unencrypted data. Also note that the use of the keys is reversed, normally you encrypt with the receivers public key.
You always encrypt then sign. Doing it this way means that the receiving party can check the encrypted data has not been changed during transmission without having to unencrypt, which can be a lengthy process.
DSACryptoServiceProvider vs. RSACryptoServiceProvider
[ "", "c#", ".net", "encryption", "" ]
Is there a JavaScript library that models [3D polyhedra](http://wiki.tcl.tk/14283) using the canvas tag or SVG? Say I wanted to produce renderings of the [Platonic solids](http://en.wikipedia.org/wiki/Platonic_solid), how would I best achieve this? FWIW, I'm only concerned with WebKit-based web browsers such as Safari and Chrome. I've seen this cool demo of how to render [3D triangles](http://www.uselesspickles.com/triangles/demo.html), but how might I extend it to polyhedra with an arbitrary number of sides?
Take a look at this library: [SVG-VML-3D](http://www.lutanho.net/svgvml3d/index.html) It uses SVG and falls back to VML on MSIE. They do have a demo with platonic solids. I don't have a Webkit-browser handy, but presume it should work there as well.
Not a direct answer to your question, but seeing as you mentioned WebKit-only I thought I'd point out the new [3D CSS Transform](http://webkit.org/blog/386/3d-transforms/) support which was added to webkit pretty recently. This allows you to do what you want without using any Javascript. I've not seen an example of 3D polyhedra, but there are examples of cubes etc out there - for example [here](http://www.fofronline.com/2009-04/3d-cube-using-css-transformations/). There's a slightly more complex demo [here](http://webkit.org/blog-files/3d-transforms/morphing-cubes.html) which has a ring of rectangles. For a real taste of what you could do (although this does use Javascript for animation) - see the [Snow Stack](http://www.satine.org/archives/2009/07/11/snow-stack-is-here/) demo.
Using JavaScript to model 3D polyhedra
[ "", "javascript", "canvas", "svg", "polyhedra", "" ]
i have some codes having the **\x00** and **\x04** ***hex codes***, what does it means? ``` $str= implode("\x00", $var['message']); //line 1 $id= $var['message'] . "\x04" . $id; //line 2 ``` what will happen in the **line1 and line2** I want to write these into a external file as **binary format**. where do i get all information like this.
`\x` indicates hexadecimal notation. See: [PHP strings](http://ch.php.net/manual/en/language.types.string.php#language.types.string.syntax.double) Have a look at an [ASCII table](http://www.asciitable.com/) to see what 0x00 and 0x04 represent. ``` 0x00 = NULL 0x04 = EOT (End of transmission) ```
\x is a way to indicate that the next two characters represent hexadecimal digits. Two hexadecimal digits (each of them 4 bits) make a byte. If you want to know what the decimal version is, multiply the left numeral by 16 and add it to the right numeral, keeping in mind that "a" is 10, "b" is 11, etc. In other programming languages, a dollar sign or the sequence 0x can also be used to flag hexadecimal numbers. --- The numbers can represent anything. Sometimes they are control codes. Check [an ASCII table](http://www.asciitable.com/).
What is the meaning of \x00 , \x04 in PHP
[ "", "php", "binaryfiles", "" ]
I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA\_ROOT/joe as opposed to having everyone's files go to MEDIA\_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks: ``` class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to='.') ``` So what I want is instead of '.' as the upload\_to, have it be the user's name. I understand that as of Django 1.0 you can define your own function to handle the upload\_to but that function has no idea of who the user will be either so I'm a bit lost. Thanks for the help!
You've probably read [the documentation](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to), so here's an easy example to make it make sense: ``` def content_file_name(instance, filename): return '/'.join(['content', instance.user.username, filename]) class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to=content_file_name) ``` As you can see, you don't even need to use the filename given - you could override that in your upload\_to callable too if you liked.
This really helped. For a bit more brevity's sake, decided to use lambda in my case: ``` file = models.FileField( upload_to=lambda instance, filename: '/'.join(['mymodel', str(instance.pk), filename]), ) ```
Django FileField with upload_to determined at runtime
[ "", "python", "django", "django-models", "" ]
I need to add checkboxes to a JTree. A custom TreeCellRenderer/TreeCellEditor seems like the right approach. So far I used [the CheckBoxNodeRenderer approach in this webpage](http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm). It works OK except for two things: 1. there's additional whitespace above + below the checkbox; I'd like to keep it the same as a regular JTree. 2. I would like to distinguish between clicking on the checkbox itself (which should attempt to toggle the checkbox) and clicking on the text associated with the checkbox (which should allow an event listener to interpret this as clicking on the corresponding tree node and take whatever action is appropriate) is there a way to do these things? I looked around for JTrees with checkboxes, can't find much. JIDE looks good but I need to use free open-source software (GPL is not ok, LGPL is ok) in this case. (or create my own checkbox tree)
As for #2, you could make a panel be the editor/renderer, and add a label along with the checkbox - the label would be the text, and the check box would not have the text added to it.
I know this question has been answered already, but i just want to clear some points: 1) JIDE Common Layer is dual-licensed (GPL with classpath exception and free commercial license). This means that you can use the Common Layer Project without any licensing issues. Please check the following link to confirm: <http://www.jidesoft.com/products/oss.htm>. The Common Layer includes an implementation of a checkable JTree (com.jidesoft.swing.CheckBoxTree). 2) There's a blog dated from 2005 from the Master himself, Santhosh Kumar, where he explains how to implement a JTree with checkboxes with the requirements you mentioned: <http://www.jroller.com/santhosh/entry/jtree_with_checkboxes>. It's worth reading it, in my opinion.
JTree with checkboxes
[ "", "java", "swing", "checkbox", "jtree", "" ]
How can I use GWT together with Visual Studio to create an ASP.NET website? If it is possible.
You can use GWT to generate the client side code writing in Java and use asp.net for the back end. It's a little trickier as you won't get the serialization across the wire for free that you'd get from using Java on the back end too. I wouldn't really recommend this approach it's bound to be a hassle to maintain. I'd recommend using a good javascript toolkit instead, such as jquery and jquery UI.
GWT can be used with any back end with a little work. Out of the box it uses a servlet container but you don't need to keep this container. The key item in the container is the script tag to load the GWT compiled code, for example: ``` <script language='javascript' src='com.abaqus.gwt.GeoApp.nocache.js'></script> ``` GWT takes it from there and is at this point independent of the back-end if you want it to be. The one are that is a source of confusion is the GWT RPC. This does not need to be used as GWT supports general JSON request support. .NET integration using JSON discussed here: <http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/9e1c82cd67e2f27b?hl=en> There are also projects that are tying GWT RPC to .NET see: ``` http://code.google.com/p/gwtrpcnet/ ``` GWT is used pretty successfully with a number of back-ends other than Java servlets so as hassles, other than working out the details of initial setup there shouldn't be many. Even debugging in Eclipse should work (yes .NET'rs will need to use Eclipse to debug)
How can I use GWT together with Visual Studio to create an ASP.NET website?
[ "", "c#", "asp.net", "gwt", "asp.net-ajax", "asp.net-3.5", "" ]
I am working on a new captcha script and it is almost completed except I would like to have a list of words for example lets say I have a list of 300 5 letter words that I would like to use for the captcha image text. What would be the best way for performance on a high traffic site to deal with this list for it? Read the words from a text file on every load Store in an array other?
Using a fixed list of words could make your Captcha weak since it restricts the number of variations to just *n*! / (*n* - *k*)! options. With *n* = 300 words and *k*=2 different words per captcha it would be just 89700 options no matter how long the words are. If you would use a sequence of four random letters (a-z) you would get more options (exactly *n*^*k* = 26^4 = 456976).
If you just want 300 hundred words to choose from, I'd just put them all in an array in straight php code and pull one out randomly. That would be the best performance.
Best way to get a random word for a captcha script in PHP
[ "", "php", "captcha", "" ]
I have a product table that contains thousands of products. Some products are available in different colors. But when somebody searches for example 'mp3 player' i dont want to show him every color, instead just the player with the best selling color. Her is the table layout (simplified): ``` ID | PRODUCT_NAME | COLOR | SALE_COUNT =========================================== 1 | Mp3 player red | red | 2 2 | Mp3 player gold | gold | 1 3 | Mp3 player black | black | 100 ``` But, when a user searches for 'Mp3 player red' i want to show him the red player, instead of the black one. The search is performed using the 'like' operator (yeah, i know lucene, anyway i need to solve this). Any suggestions how to solve this issue? i have a few ideas but none of them seems to be a good solution. thanks, postgreSQL db and jave is used to create the result.
Just order by the SALE\_COUNT descending and select only the first one, if I understand your problem: ``` SELECT TOP 1 ID, PRODUCT_NAME, COLOR, SALE_COUNT FROM table WHERE PRODUCT_NAME LIKE '%' + @searchParam + '%' ORDER BY SALE_COUNT DESC ``` Be sure to sanitize the search parameter first by removing any possible sql injection attacks. EDIT: If you're using postgres, the syntax is to put a "LIMIT n" at the end, so: ``` SELECT ID, PRODUCT_NAME, COLOR, SALE_COUNT FROM table WHERE PRODUCT_NAME LIKE '%' + @searchParam + '%' ORDER BY SALE_COUNT DESC LIMIT 1 ```
it will be something like ``` SELECT TOP 1 (*) FROM table WHERE PRODUCT_NAME LIKE 'mp3 player %' ORDER BY SALE_COUNT DESC ``` So, we are selecting only the top row, ordered, descending by SALE\_COUNT (so that the highest sale count is on the top)
How to filter search results in this example
[ "", "sql", "postgresql", "full-text-search", "filtering", "ranking", "" ]
It must be: * easily skinnable with css * be able to handle forms and not just images * be well documented Any suggestions welcome Many thanks
I've used [Shadowbox.js](http://www.shadowbox-js.com/support.html#adapters) on several large projects and it works great. > Although Shadowbox can be used in > standalone mode, it's just as easy to > use Shadowbox with your JavaScript > library of choice for a given project. > This is accomplished using adapters. > An adapter is a small file that tells > Shadowbox which methods to call on the > underlying framework to achieve some > common purpose such as querying the > DOM or handling events. Shadowbox > comes bundled with adapters for the > following JavaScript frameworks: > > ``` > * Prototype > * jQuery > * MooTools (requires 1.2 Core) > * Dojo Toolkit > * Yahoo! User Interface Library (requires yahoo-dom-event.js) > * Ext (requires ext-core.js) > ```
[Thickbox](http://jquery.com/demo/thickbox/)?
What is a good jQuery lightbox clone?
[ "", "javascript", "jquery", "css", "lightbox", "" ]
I have a piece of code where in I have an if block which when satisfied the flow goes into it and in there are nested if and else, if it does not satisfies any of the if block it should go into the else block but the problem i am facing is that it satisfies one if block and then goes into else as well. this is creating redundancy in my code. it like this ``` if(condition = true) { if(condition1 == true) {} if(condition2 == true) {} else {} } ``` Now it satisfies condition 1 and then after performing if block operations goes into else also. Please help. Code is in C#
get rid of the ==true's its just going to lead to a mistake like you made on the first line. also, add in else statements. ``` if (condition) { if (condition1) { } else if (condition2) { } else { } } ```
You probably need something like this (notice `else if` with condition2): ``` if(condition) { if(condition1) {} else if(condition2) {} else {} } ``` You can skip `'== true'` in conditions.
If else block creating problem
[ "", "c#", "" ]
(this is a .net build server) I'm getting the following error: ``` c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1679,9): error MSB3091: Task failed because "LC.exe" was not found, or the .NET Framework SDK v2.0 is not installed. The task is looking for "LC.exe" in the "bin" subdirectory beneath the location specified in the SDKInstallRootv2.0 value of the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework. You may be able to solve the problem by doing one of the following: 1.) Install the .NET Framework SDK v2.0. 2.) Manually set the above registry key to the correct location. 3.) Pass the correct location into the "ToolPath" parameter of the task. ``` This is because we are using a component that requires LIC.exe to compile. now I can solve the problem by installing the latest Microsoft SDK on the build server, but I thought the **whole point** of a build server is to not have your *dev tools* installed on it. I think I can probably solve this but not after some work figuring some things out (like these guys did) <http://richardsbraindump.blogspot.com/2009/07/some-teambuild-fun-and-games.html> should I install the SDK? and more importantly: **What is the primary purpose of a build server?**
The best way to do it would be to store everything needed to make builds in source control. When doing that you don't need to go through all your build servers when your build chain is updated, it will happen automatically. An added advantage is that you can go back in time and still be able to get everything built without needing to delve into all your old CDs to find the tools you need to build old versions of your product. However, this might not be possible for all build tools. For example we tried to do it with Visual Studio 2005, but we got weird intermittent pdb errors from mspdbsrv when building from a non-installed tool chain. So unfortunately all our build servers all have VS2005 installed (but not the PS3 tool chain, which is really really nice since it's updated quite often). Regards, Sebastiaan
The primary purpose of the build server is to build code. Anything that is needed to build the code needs to be on the build server.
Should I install an SDK on the build server?
[ "", "c#", "msbuild", "build-process", "build-automation", "cruisecontrol.net", "" ]
I have 9 values in the form of a matrix and need to compute the median from these values as part of a simulation process. I use quicksort in C++ (i.e qsort()) which results in the process running slow (as this process iterates several times). Is there a better sorting algorithm that I could use?
Sorting to get a median is very inefficient. You could use STL nth\_element instead: ``` #include <algorithm> // Assuming you keep the elements in a vector v of size len std::nth_element( v.begin(), v.begin()+len/2, v.end() ); median = v[len/2]; //... or, if the elements are in a simple array v[len], then std::nth_element( v, v+len/2, v+len ); median = v[len/2]; ``` Note: the nth\_element will modify the vector/array v. Make a copy first if you need to preserve the original.
Please please please never recommend bubble sort except to masochists! For small values, **insertion** sort is best, and its good for other applications (nearly sorted data of any length). Edit: cleaned up formatting, emphasizing suggested answer.
quicksort in C++ is slow
[ "", "c++", "sorting", "quicksort", "" ]
I'm updating my user's Twitter status using the simple code below. My problem is that the Twitter updates resulting from this code are denoted as ".... ago **from API**". I would like to be able to control the "API" part to say a custom name. How can I do it? Preferably using an alteration to the code below... Thanks ``` /* * A function to post an update to Twitter programmatically * Author: Danny Battison * Contact: gabehabe@hotmail.com */ /// <summary> /// Post an update to a Twitter acount /// </summary> /// <param name="username">The username of the account</param> /// <param name="password">The password of the account</param> /// <param name="tweet">The status to post</param> public static void PostTweet(string username, string password, string tweet) { try { // encode the username/password string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password)); // determine what we want to upload as a status byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet); // connect with the update page HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml"); // set the method to POST request.Method = "POST"; request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change! // set the authorisation levels request.Headers.Add("Authorization", "Basic " + user); request.ContentType = "application/x-www-form-urlencoded"; // set the length of the content request.ContentLength = bytes.Length; // set up the stream Stream reqStream = request.GetRequestStream(); // write to the stream reqStream.Write(bytes, 0, bytes.Length); // close the stream reqStream.Close(); } catch (Exception ex) { // Log the error } } ```
The only way to get "from MyApp" is to use OAuth and set it up through your Twitter developer account. You used to be able to send an HTTP POST parameter with your request (source) but it's since been deprecated.
Just a small suggestion, you might want to take a look at the [TweetSharp](http://code.google.com/p/tweetsharp/) library, which could make your life easier rather than mucking around yourself at the REST API level. Twitter has a list of other libraries you could use for C# [here](http://apiwiki.twitter.com/Libraries#C/NET), if you don't like the look of TweetSharp.
Twitter status update: set source (C#)
[ "", "c#", "twitter", "" ]
I have some web methods that return my objects back as serialized XML. It is only serializing the NHibernate-mapped properties of the object... anyone have some insight? It seems to be that the web methods are actually serializing the NHibernate proxies instead of my classes. I've tried using [XMLInclude] and [XMLElement], but the properties are still not serializing. I have a really horrible hackish way of getting around this, but I wondered if there was a better way! Something like this: ``` <?xml version="1.0" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="StoryManager" assembly="StoryManager"> <class name="Graphic" table="graphics" lazy="false"> <id name="Id" column="id" type="int" unsaved-value="0" > <generator class="identity"/> </id> <property name="Assigned" /> <property name="Due" /> <property name="Completed" /> <property name="UglyHack" insert="false" update="false" /> <many-to-one name="Parent" class="Story" column="story_id"/> </class> </hibernate-mapping> public class Graphic { private int m_id; public virtual int Id { get { return m_id; } set { m_id = value; } } private DateTime? m_assigned; public virtual DateTime? Assigned { get { return m_assigned; } set { m_assigned = value; } } private DateTime? m_due; public virtual DateTime? Due { get { return m_due; } set { m_due = value; } } private DateTime? m_completed; public virtual DateTime? Completed { get { return m_completed; } set { m_completed = value; } } public bool UglyHack { get { return m_due < m_completed; } // return something besides a real mapped variable set {} // trick NHibernate into thinking it's doing something } } ``` This is obviously no way to write code. If I don't have the "fake" mapping in there (UglyHack property), that property won't be serialized. For now I'm looking into using (Data) Transfer Objects, and may be on to something using reflection...
The best way to serialize the NH mapped object is to not serialize it :). If you're sending it across the wire you should really create a DTO for it. If you don't want to create that object you can set [XmlIgnore] on properties you don't want serialized. If you want all properties, you have to load them ALL from the database - for some an eager load will be enough for others(where too many joins will start duplicating data) you'll have to access that property in any way you want to trigger the load. **Edit:** And I'd like to add another thing - sending your domain entities over the wire is **always** a bad idea. In my case I learned it the hard way - I expose some entities over a WebService - and now almost any change(rename a property, remove a property ..etc ) to my domain kills the app using the WS - plus a whole bunch of properties have [XmlIgnore] on them ( don't forget about circular dependencies). We'll do a rewrite soon enough - but rest assure that's not something I'll **ever** do again. :) **Edit 2** You could use [AutoMapper](http://www.codeplex.com/AutoMapper) for transferring the data from your entity to the DTO. They have some examples on the site.
if its a WCF service, you could use a IDataContractSurrogate ``` public class HibernateDataContractSurrogate : IDataContractSurrogate { public HibernateDataContractSurrogate() { } public Type GetDataContractType(Type type) { // Serialize proxies as the base type if (typeof(INHibernateProxy).IsAssignableFrom(type)) { type = type.GetType().BaseType; } // Serialize persistent collections as the collection interface type if (typeof(IPersistentCollection).IsAssignableFrom(type)) { foreach (Type collInterface in type.GetInterfaces()) { if (collInterface.IsGenericType) { type = collInterface; break; } else if (!collInterface.Equals(typeof(IPersistentCollection))) { type = collInterface; } } } return type; } public object GetObjectToSerialize(object obj, Type targetType) { // Serialize proxies as the base type if (obj is INHibernateProxy) { // Getting the implementation of the proxy forces an initialization of the proxied object (if not yet initialized) try { var newobject = ((INHibernateProxy)obj).HibernateLazyInitializer.GetImplementation(); obj = newobject; } catch (Exception) { // Type test = NHibernateProxyHelper.GetClassWithoutInitializingProxy(obj); obj = null; } } // Serialize persistent collections as the collection interface type if (obj is IPersistentCollection) { IPersistentCollection persistentCollection = (IPersistentCollection)obj; persistentCollection.ForceInitialization(); //obj = persistentCollection.Entries(); // This returns the "wrapped" collection obj = persistentCollection.Entries(null); // This returns the "wrapped" collection } return obj; } public object GetDeserializedObject(object obj, Type targetType) { return obj; } public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType) { return null; } public object GetCustomDataToExport(Type clrType, Type dataContractType) { return null; } public void GetKnownCustomDataTypes(Collection<Type> customDataTypes) { } public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData) { return null; } public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit) { return typeDeclaration; } } ``` Implementaion in the host: ``` foreach (ServiceEndpoint ep in host.Description.Endpoints) { foreach (OperationDescription op in ep.Contract.Operations) { var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>(); if (dataContractBehavior != null) { dataContractBehavior.DataContractSurrogate = new HibernateDataContractSurrogate(); } else { dataContractBehavior = new DataContractSerializerOperationBehavior(op); dataContractBehavior.DataContractSurrogate = new HibernateDataContractSurrogate(); op.Behaviors.Add(dataContractBehavior); } } } ```
How do I serialize all properties of an NHibernate-mapped object?
[ "", "c#", "web-services", "nhibernate", "xml-serialization", "proxy-classes", "" ]
I have this tables: Posts (post\_is, title and text), Tags (tag\_id, tag), Post\_tag\_nn (id, tag\_id, post\_id). I want for a specific post having for example 4 tags all the posts with those tags, then all the posts with any three of those tags, then all posts with any two of those tags and so on. How can i build a SQL query for this purpose (in php it seems like a backtracking problem=all the subsets of a given set).
Have a query to find the tags of the current post, something like ``` SELECT tag_id FROM Post_tag_nn WHERE post_id = $post_id; ``` Then using those tag id's, this query should return you the id's of posts with 4,3,2,... matching tags: ``` SELECT post_id, COUNT(post_id) AS tag_count FROM Post_tag_nn WHERE tag_id IN ($array_of_tag_ids) GROUP BY post_id ORDER BY tag_count DESC; ```
If you're going to be pulling down every post with even a single one of the tags regardless, you might be best off just running a single query per tag to pull all of the posts with that tag, and then generating the sets yourself.
finding the posts related by tags with one specific post in mysql
[ "", "sql", "mysql", "tags", "many-to-many", "" ]
I want to write the property names and matching data to a delimited file, I've copied some code from the c# objectdumper help file and it all seems to work OK but I dont understand reflection enough to be confident to use it. What I'm worried about is an incorrect value being placed in the incorrect column, is it possible for this to happen e.g. ``` Field1,Field2 Val1,Val2 Val1,Val2 Val2,Val1 << Could this ever happen ? ``` Also what does this piece of code mean? ``` f != null ? f.GetValue(this) : p.GetValue(this, null) ``` Code below: ``` public string returnRec(bool header, string delim) { string returnString = ""; bool propWritten = false; MemberInfo[] members = this.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (MemberInfo m in members) { FieldInfo f = m as FieldInfo; PropertyInfo p = m as PropertyInfo; if (f != null || p != null) { if (propWritten) { returnString += delim; } else { propWritten = true; } if (header) returnString += m.Name; else { Type t = f != null ? f.FieldType : p.PropertyType; if (t.IsValueType || t == typeof(string)) { returnString += f != null ? f.GetValue(this) : p.GetValue(this, null); } } } } return returnString; } ```
@astander and @Frederik have essentially answered the questions and concerns that you specifically voiced, but I'd like to suggest doing things in a slightly more efficient manner. Depending on the number of object instances that you wish to write to your file, the method that you've presented may end up being quite inefficient. That's because you're gleaning type and value information via reflection on every iteration, which is unnecessary. What you're looking for is something that looks up type information once, and then only uses reflection to get the value of properties and fields, e.g. (.NET 3.5), ``` public static IEnumerable<string> ReturnRecs(IEnumerable items, bool returnHeader, string delimiter) { bool haveFoundMembers = false; bool haveOutputHeader = false; PropertyInfo[] properties = null; FieldInfo[] fields = null; foreach (var item in items) { if (!haveFoundMembers) { Type type = item.GetType(); properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(pi => pi.PropertyType.IsValueType || pi.PropertyType == typeof (string)).ToArray(); fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance) .Where(fi => fi.FieldType.IsValueType || fi.FieldType == typeof(string)).ToArray(); haveFoundMembers = true; } if (!haveOutputHeader) { yield return String.Join(delimiter, properties.Select(pi => pi.Name) .Concat(fields.Select(pi => pi.Name)).ToArray()); haveOutputHeader = true; } yield return String.Join(delimiter, properties.Select(pi => pi.GetValue(item, null).ToString()) .Concat(fields.Select(fi => fi.GetValue(item).ToString())).ToArray()); } ``` The above code only ever performs a `GetProperties` and `GetFields` once per *group of records*--also, because of this, there's no need to explicitly sort the properties and fields as was @Frederik's suggestion.
Type t = f != null ? f.FieldType : p.PropertyType; this is an inline if, asking is f != null then f.FieldType else p.PropertyType can be written as ``` Type t; if (f != null) t = f.FieldType; else t = p.PropertyType; ```
Saving a class to a delim file using reflection
[ "", "c#", "reflection", "" ]
I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this: ``` def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') ``` What I want to accomplish is something like: ``` def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName ``` I get syntax errors when I execute this, any ideas?
You need to use the [`reverse()`](http://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse) utils function. ``` from django.urls import reverse # or Django < 2.0 : from django.core.urlresolvers import reverse def myview(request): return HttpResponseRedirect(reverse('arch-summary', args=[1945])) ``` Where `args` satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.
The right answer from [Django 1.3 onwards](http://web.archive.org/web/20140704183041/https://docs.djangoproject.com/en/1.3/topics/http/shortcuts/#redirect), where the redirect method implicitly does a reverse call, is: ``` from django.shortcuts import redirect def login(request): if request.session.get('user'): return redirect('named_url') ```
Django and urls.py: How do I HttpResponseRedirect via a named url?
[ "", "python", "django", "redirect", "django-urls", "" ]
I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place and scrolls with the page.
You could use simply css, positioning your element as [fixed](https://developer.mozilla.org/en-US/docs/Web/CSS/position): ``` .fixedElement { background-color: #c0c0c0; position:fixed; top:0; width:100%; z-index:100; } ``` **Edit:** You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero. You can detect the top scroll offset of the document with the [scrollTop](http://docs.jquery.com/CSS/scrollTop) function: ``` $(window).scroll(function(e){ var $el = $('.fixedElement'); var isPositionFixed = ($el.css('position') == 'fixed'); if ($(this).scrollTop() > 200 && !isPositionFixed){ $el.css({'position': 'fixed', 'top': '0px'}); } if ($(this).scrollTop() < 200 && isPositionFixed){ $el.css({'position': 'static', 'top': '0px'}); } }); ``` When the scroll offset reached 200, the element will *stick* to the top of the browser window, because is placed as fixed.
You've seen this example on Google Code's [issue page](http://code.google.com/p/chromium/issues/detail?id=575) and (only recently) on Stack Overflow's edit page. CMS's answer doesn't revert the positioning when you scroll back up. Here's the shamelessly stolen code from Stack Overflow: ``` function moveScroller() { var $anchor = $("#scroller-anchor"); var $scroller = $('#scroller'); var move = function() { var st = $(window).scrollTop(); var ot = $anchor.offset().top; if(st > ot) { $scroller.css({ position: "fixed", top: "0px" }); } else { $scroller.css({ position: "relative", top: "" }); } }; $(window).scroll(move); move(); } ``` ``` <div id="sidebar" style="width:270px;"> <div id="scroller-anchor"></div> <div id="scroller" style="margin-top:10px; width:270px"> Scroller Scroller Scroller </div> </div> <script type="text/javascript"> $(function() { moveScroller(); }); </script> ``` And a simple [live demo](http://fiddle.jshell.net/34df1mj7/show/light/). A nascent, script-free alternative is `position: sticky`, which is supported in Chrome, Firefox, and Safari. See the [article on HTML5Rocks](http://updates.html5rocks.com/2012/08/Stick-your-landings-position-sticky-lands-in-WebKit) and [demo](http://html5-demos.appspot.com/static/css/sticky.html), and [Mozilla docs](https://developer.mozilla.org/en-US/docs/Web/CSS/position#Sticky_positioning).
How can I make a div stick to the top of the screen once it's been scrolled to?
[ "", "javascript", "jquery", "css", "scroll", "positioning", "" ]
I have installed PDT 2.1 but i can't switch to the PHP Perspective, any ideas?
I have solved the problem with installation of Eclipse PHP IDE.
PDT 2.1 only supports Eclipse 3.5. It is strange that you didn't see any warning while installing it. If you wish to continue using Eclipse 3.4.x, install PDT 2.0.1
PDT installed but PHP Perspective is missing
[ "", "php", "eclipse", "plugins", "eclipse-pdt", "" ]
I am trying to use Fortify Source Code Analyzer for a research project at my school to test the security for open source Java web applications. I am currently working on Apache Lenya. I am working with the last stable release (Lenya v2.0.2). Inside the root directory there is a file named **`build.sh`**. This file is called to build Lenya using the version of Ant that ships with the release (in the `tools/bin` folder). I can build Lenya just fine when I run `./build.sh`. So, it would be assumed that running the following command in Fortify would work : ``` sourceanalyzer -b lenya -Xmx1200M touchless ./build.sh ``` However, when I try and run: ``` sourceanayzer -b lenya -Xmx1200M -scan -f lenya.fpr ``` I get: > build id Lenya not found. I looked at the **buid.sh** file and noticed that it was just resetting the current ant home, classpath, and ant options variables, running the ant build command, and resetting the values back to their defaults. So I reset all of the variables manually (without the script) instead of running the script and ran: ``` sourceanalyzer -b lenya -Xmx1200M touchless tools/bin/ant -logger org.apache.tools.ant.NoBannerLogger ``` Then I ran : ``` sourceanalyzer -b lenya -Xmx1200M -scan -f lenya.fpr ``` but I got the same error. I'm not sure if this is because I am doing something wrong or if it is something that Fortify is not doing correctly. Any insight will be great.
I'm not sure whether you have access to the Fortify documentation, but that will definitely help. You should refer to the SCA User's Guide to understand how to use the sourceanalyzer executable. To cut things short, there are two ways of getting the FPR file: 1. (The long way) Write a script to translate and analyse the source code by providing the path of the source code and the classpath to the sourceanalyzer executable. 2. (The short way) Use the SCACompiler instead of javac as the compiler. You'll need to modify the build script for this. I prefer the former due to its customizability when handling large code bases. PS: Which version of Fortify is this?
Don't use the touchless command, that is for C/C++ Integration. Since Lenya is written in Java, you're better off with other commands. Try this for your first translation step (run from your base lenya dir): ``` sourceanalyzer -b lenya -Xmx1200M -source 1.5 -cp "**/*.jar" "**/*" ```
Fortify Source Analyzer and Apache Lenya
[ "", "java", "apache", "static-analysis", "fortify", "" ]
I'd like to build a simple web app, which manages some directory on a server. I want to give people the option to use chown and chmod. What is the safest way to give PHP this permission? The quickest thing is just running Apache and PHP as root, but that doesn't seem to be a smart idea. One other thing I thought of, was creating a separate script which has setuid root.. Thanks!
Well, it certainly sounds like a dangerous idea to begin with and I'd prefer sitting down and thinking through the whole strategy of what is trying to be achieved. The danger is privilege escalation of an executable script which a remote user could modify or upload, of course. Full chown/chmod in a web app is equivalent to just pasting your root password on the page. What is it exactly which needs to happen? If the chown needs to happen for some reason but not to root (we hope) then the functionality should be wrapped. I would take the user requests and queue them, then have a separate process (could be shell, php, perl, anything) running as root by cron check this queue, check to see if the request fit the allowed parameters, and make the changes.
One way would be to set up sudo on your machine (assuming it's a Linux box). Sudo allows you to run commands elevated, governed by restrictions set forth in the sudoers.conf file. Use tight rules to limit its use to the required commands in a specific directory for the user your web service is running under (like www-data), and then call the command shell from your PHP script something like tis: ``` shell_exec("sudo chmod 777 dirname"); ``` Do make sure that your sudo config is tight, to ensure that breaking out will be next to impossible.
Allowing PHP to change file and directory ownership and permission
[ "", "php", "linux", "apache", "root", "" ]
I'm looking for a utility similar to gprof that will generate a [call graph](http://en.wikipedia.org/wiki/Call_graph) for PHP code. I'd prefer something that can produce graphical output, or at least text output that can be interpreted by GraphViz or similar, but I'll settle for plain text output. Does anyone know of any tool that can do this?
I would definitely try [Doxygen](http://www.doxygen.nl/). It has support for PHP, and the call graphs and caller graphs it creates have been very useful in exploring "foreign code" for me previously. ![Example of doxygen call graph](https://i.stack.imgur.com/C8Tv7.png)
Not sure there exists anything that can analyse source-code written in PHP to generate that... But there is a possiblity, when you are running the code. You might want to take a look at the [Xdebug](http://xdebug.org/) extension : it brings [profiling](http://xdebug.org/docs/profiler) to PHP, and and generate callgrind-like files, that can be read with [KCacheGrind](http://kcachegrind.sourceforge.net/html/Home.html) on Linux. And this one is able to generate some kind of callgraphs. It can also be integrated with PHPUNit, to generate [code-coverage](http://www.phpunit.de/manual/current/en/code-coverage-analysis.html) when running unit-tests Some time ago, PHPUnit was able to generate some callgraphs with graphviz ; I don't find that option anymore, though :-( --- EDIT : it's the first time I hear about it, but there is a project called [phpCallGraph](http://phpcallgraph.sourceforge.net/) that might be able to help you, too... and it seems there is work going on, if I look at it's [changelog](http://phpcallgraph.svn.sourceforge.net/viewvc/phpcallgraph/trunk/changelog.txt)
PHP call graph utility?
[ "", "php", "visualization", "call-graph", "" ]
I need to draw text VERTICALLY directly on to a Windows Mobile Form. This is a Compact Framework 2.0 application. I have the following test code working in a windows form application, but it does not work with the compact framework because there is NOT a DirectionVertical StringFormatFlag. Is there another way to do the same thing on Windows Mobile? Upgrading to Compact Framework 3.5 did NOT help. It has the same StringFormatFlags as 2.0. ``` private void TestDrawVertically() { Font myFont = new Font(FontFamily.GenericSerif, 10, FontStyle.Bold); System.Drawing.Brush myBrush = new SolidBrush(Color.Black); Rectangle myRect = new Rectangle(10, 10, 200, 200); StringFormat myFormat = new StringFormat(); myFormat.LineAlignment = StringAlignment.Center; myFormat.Alignment = StringAlignment.Center; myFormat.FormatFlags = StringFormatFlags.DirectionVertical; Graphics myGraphic = this.CreateGraphics(); myGraphic.DrawString("Hello", myFont, myBrush, myRect, myFormat); } ``` Thanks.
``` public static Font CreateRotatedFont(string fontname, int height, int angleInDegrees, Graphics g) { LogFont logf = new LogFont(); logf.Height = -1 * height; logf.FaceName = fontname; logf.Escapement = angleInDegrees * 10; logf.Orientation = logf.Escapement; logf.CharSet = LogFontCharSet.Default; logf.OutPrecision = LogFontPrecision.Default; logf.ClipPrecision = LogFontClipPrecision.Default; logf.Quality = LogFontQuality.ClearType; logf.PitchAndFamily = LogFontPitchAndFamily.Default; return Font.FromLogFont(logf); } ``` Then use it like this: ``` Graphics myGraphic = this.CreateGraphics(); Font myFont = CreateRotatedFont("Tahoma", 32, 90, myGraphic); myGraphic.DrawString("Hello", myFont, myBrush, myRect, myFormat); ```
I know this question has already been answered, but I found [this example](http://msdn.microsoft.com/en-us/library/microsoft.windowsce.forms.logfont%28v=vs.90%29.aspx) on the Microsoft website more thorough and useful: ``` using System; using System.Drawing; using System.Windows.Forms; using Microsoft.WindowsCE.Forms; namespace LogFontDemo { public class Form1 : System.Windows.Forms.Form { // Declare objects to draw the text. Font rotatedFont; SolidBrush redBrush; // Specify the text to roate, the rotation angle, // and the base font. private string rTxt = "abc ABC 123"; private int rAng = 45; // Determine the vertial DPI setting for scaling the font on the // device you use for developing the application. // You will need this value for properly scaling the font on // devices with a different DPI. // In another application, get the DpiY property from a Graphics object // on the device you use for application development: // // Graphics g = this.CreateGraphics(); // int curDPI = g.DpiY; private const int curDPI = 96; // Note that capabilities for rendering a font are // dependant on the device. private string rFnt = "Arial"; public Form1() { // Display OK button to close application. this.MinimizeBox = false; this.Text = "Rotated Font"; // Create rotatedFont and redBrush objects in the custructor of // the form so that they can be resued when the form is repainted. this.rotatedFont = CreateRotatedFont(rFnt, rAng); this.redBrush = new SolidBrush(Color.Red); } // Method to create a rotated font using a LOGFONT structure. Font CreateRotatedFont(string fontname, int angleInDegrees) { LogFont logf = new Microsoft.WindowsCE.Forms.LogFont(); // Create graphics object for the form, and obtain // the current DPI value at design time. In this case, // only the vertical resolution is petinent, so the DpiY // property is used. Graphics g = this.CreateGraphics(); // Scale an 18-point font for current screen vertical DPI. logf.Height = (int)(-18f * g.DpiY / curDPI); // Convert specified rotation angle to tenths of degrees. logf.Escapement = angleInDegrees * 10; // Orientation is the same as Escapement in mobile platforms. logf.Orientation = logf.Escapement; logf.FaceName = fontname; // Set LogFont enumerations. logf.CharSet = LogFontCharSet.Default; logf.OutPrecision = LogFontPrecision.Default; logf.ClipPrecision = LogFontClipPrecision.Default; logf.Quality = LogFontQuality.ClearType; logf.PitchAndFamily = LogFontPitchAndFamily.Default; // Explicitly dispose any drawing objects created. g.Dispose(); return Font.FromLogFont(logf); } protected override void OnPaint(PaintEventArgs e) { if(this.rotatedFont == null) return; // Draw the text to the screen using the LogFont, starting at // the specified coordinates on the screen. e.Graphics.DrawString(rTxt, this.rotatedFont, this.redBrush, 75, 125, new StringFormat(StringFormatFlags.NoWrap | StringFormatFlags.NoClip)); } protected override void Dispose(bool disposing) { // Dispose created graphic objects. Although they are // disposed by the garbage collector when the application // terminates, a good practice is to dispose them when they // are no longer needed. this.redBrush.Dispose(); this.rotatedFont.Dispose(); base.Dispose(disposing); } static void Main() { Application.Run(new Form1()); } } } ```
How to Draw Text Vertically with Compact Framework
[ "", "c#", "user-interface", "windows-mobile", "drawing", "" ]
I was having a problem with IE finding both secure and non-secure items on a page. This seems to have been sorted thanks to a solution by David (many thanks!) who suggested altering the JS we use to display a gallery of images at the top of the page. The issue now is that the gallery doesn't work! Here's the error message: Webpage error details Message: 'this.galleryData.0.image' is null or not an object Line: 266 Char: 4 Code: 0 URI: <https://www.droverholidays.co.uk/scripts/jd.gallery.js> The page is: <https://www.droverholidays.co.uk/bikehireform.php> I don't understand JS very well so it would be great if anyone can tell me what I need to do to make this work!
In `bikehireform.php` change the line that says ``` startGallery(); ``` to ``` window.addEvent('domready', startGallery); ```
In looking at [your other question](https://stackoverflow.com/questions/1234990), I personally think CptSkippy's answer is still the correct one. Stick with the onDomReady approach and make sure your external assets are being loaded from http\*\*\*s\*\*\*
Javascript : is null or not an object
[ "", "javascript", "image", "gallery", "" ]
In the following code, I have verified that connecting to a URL from within an applet preserves the browser's session if JDK's URLConnection class is used. However, this is not the case if Apache's HttpClient library is used. Does anyone know why? Alternatively, is there a way for me to set the connection instance to be used by an HttpClient instance? ``` import java.applet.Applet; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import javax.net.ssl.SSLException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; public class HttpClientTesterApplet extends Applet { private static final long serialVersionUID = -1599714556710568947L; public void testHttpClient() throws ClientProtocolException, IOException, URISyntaxException { URL url = new URL(String.format("%s://localhost:%s/%s/testHttpClient", getParameter("protocol"), getParameter("port"), getParameter("context"))); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url.toURI()); System.out.println("Executing request " + post.getURI()); try { System.out .println(client.execute(post, new BasicResponseHandler())); } catch (SSLException e) { System.out.println(e.getMessage()); } System.out.println("Executed request " + post.getURI()); System.out.println("Opening connection " + url); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); System.out.println("Opened connection " + url); urlConnection.setRequestMethod("POST"); System.out.println("Connecting"); urlConnection.connect(); System.out.println("Connected"); InputStream inputStream = urlConnection.getInputStream(); try { while (inputStream.read() != -1) { System.out.println("Reading"); } } finally { inputStream.close(); } } } ```
This is a common problem with libraries implementing their own URL connection via Socket. Apparently, the JRE implementation of the URLConnection class can get to the browser information directly. We had to employ the technique as mentioned by oscargm above, i.e. on the appserver writing the request cookies to be the parameters to the applet AND getting to the browser's document cookies using JavaScript (this is for the case of SSO where the set of cookies may not be the same because of the intermediate agent -- proxy servers). Note that if the cookies are HttpOnly -- the javascript code will fail.
You must send the `jsessionid` cookie or rewrite your URL to use the `jsessionid`. That's the way the server knows your session. If you generate the `applet` tag in a JSP page dynamically you can pass the `jsessionid`value to the applet as a parameter and then use it. ``` post.setHeader("Cookie", "jsessionid=" + jsessionidValue ); ```
Connection to a URL from within an applet using Apache's HttpClient vs using the JDK's URLConnection
[ "", "java", "session", "applet", "httpclient", "urlconnection", "" ]
How can I *intercept* `Ctrl`+`C` (which normally would kill the process) in a CLI (command line interface) Java application? Does a multi-platform solution exist (Linux, Solaris, Windows)? I'm using `Console`'s `readLine()`, but if necessary, I could use some other method to read characters from standard input.
``` Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { /* my shutdown code here */ } }); ``` This should be able to intercept the signal, but only as an intermediate step before the JVM completely shutdowns itself, so it may not be what you are looking after. You need to use a **`SignalHandler`** (`sun.misc.SignalHandler`) to intercept the `SIGINT` signal triggered by a `Ctrl`+`C` (on Unix as well as on Windows). See [this article](https://web.archive.org/web/20170316170243/http://public.dhe.ibm.com/software/dw/java/i-signalhandling-pdf.pdf) (pdf, page 8 and 9).
I am assuming you want to shutdown gracefully, and not do short circuit the shutdown process. If my assumption is correct, then you should look at [Shutdown Hooks](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)).
How can I "intercept" Ctrl+C in a CLI application?
[ "", "java", "command-line", "stdin", "command-line-interface", "copy-paste", "" ]
Sorry if this has been answered, but I couldn't turn up a search for it... a difficult thing to search for, I think! Say I have this: ``` var MyPrototype = function() { this.init(); } $.extend(MyPrototype.prototype, { a: 5, init: function() { var thing = new SomeOtherClass(); thing.meth = this.meth; // thing.meth() is called somewhere within thing; }, meth: function() { alert(this.a); } } ``` Basically, I am dealing with another class which uses its own methods as callbacks, e.g. I am expected to override them with my own functionality. But I need to retain the proper scope of `this` while doing it (the only thing I care about from `SomeOtherClass` is what's passed to the callback; nothing in the state). As you might imagine, this doesn't work because `thing` has no `a` property! I am not familiar enough with the intricacies of Javascript scoping to know how to make `this` refer to what I want, though!
Combining two other answers here, so that you don't have to rewrite your meth function, I'd do this: ``` var me = this; thing.meth = function() { MyPrototype.meth.apply(me, arguments); }; ```
Since you can't control how it's called you could try this: ``` var MyPrototype = function() { this.init(); } $.extend(MyPrototype.prototype, { a: 5, init: function() { var thing = new SomeOtherClass(); // Create an aliad for this var that = this; thing.meth = function() { // You can always access the object using it's "that" alias alert(that.a); }; } } ``` Or... ``` var MyPrototype = function() { this.init(); } $.extend(MyPrototype.prototype, { a: 5, init: function() { var thing = new SomeOtherClass(); // Create an aliad for this var that = this; thing.meth = function() { // You can always access the object using it's "that" alias that.meth(); }; }, meth: { alert(this.a); } } ```
Scoping "this" in Javascript (and jQuery.extend)
[ "", "javascript", "jquery", "this", "" ]
I am not very familiar with databases, and so I do not know how to partition a table using SQLAlchemy. Your help would be greatly appreciated.
It's quite an advanced subject for somebody not familiar with databases, but try Essential SQLAlchemy (you can read the key parts on [Google Book Search](http://books.google.com/books?id=septpU7dELIC&pg=PR5&lpg=PR5&dq=sqlalchemy+partition+table&source=bl&ots=0zv-uP1ckD&sig=gnaIpZPQA05lT6-FwL-BIFd-5Kg&hl=en&ei=NXFRSoGYIobatgPv6dG9Bw&sa=X&oi=book_result&ct=result&resnum=5) -- p 122 to 124; the example on p. 125-126 is not freely readable online, so you'd have to purchase the book or read it on commercial services such as O'Reilly's [Safari](http://my.safaribooksonline.com/) -- maybe on a free trial -- if you want to read the example). Perhaps you can get better answers if you mention whether you're talking about vertical or horizontal partitioning, why you need partitioning, and what underlying database engines you are considering for the purpose.
There are two kinds of partitioning: Vertical Partitioning and Horizontal Partitioning. From the [docs](http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#partitioning-strategies): > # Vertical Partitioning > > Vertical partitioning places different > kinds of objects, or different tables, > across multiple databases: > > ``` > engine1 = create_engine('postgres://db1') > engine2 = create_engine('postgres://db2') > Session = sessionmaker(twophase=True) > # bind User operations to engine 1, Account operations to engine 2 > Session.configure(binds={User:engine1, Account:engine2}) > session = Session() > ``` > > # Horizontal Partitioning > > Horizontal partitioning partitions the > rows of a single table (or a set of > tables) across multiple databases. > > See the “sharding” example in > [`attribute_shard.py`](http://docs.sqlalchemy.org/en/rel_0_9/orm/examples.html#examples-sharding) Just ask if you need more information on those, preferably providing more information about what you want to do.
how to make table partitions?
[ "", "python", "sqlalchemy", "" ]
I have a problem which I already solved using T-SQL(cursor & loop).(SQL server 2005) But I am looking for the solution using SQL. I have a Master Table with a column say MasterRecord(all are unique and type Varchar and PK) ``` MasterRecord ------------ MRecord1 MRecord2 MRecord3 MRecord4 ................ .................. MRecord[n] ``` Now the Master-Detail table has two columns MasterRecord(Varchar & FK) and DetailRecord(Varchar) ``` MasterRecord DetailRecord --------------------------------------------- MRecord1 MRecord1_DetailRecord1 MRecord1 MRecord1_DetailRecord2 MRecord1 MRecord1_DetailRecord3 MRecord1 MRecord1_DetailRecord4 MRecord2 MRecord2_DetailRecord1 MRecord2 MRecord2_DetailRecord2 MRecord2 MRecord2_DetailRecord3 MRecord2 MRecord2_DetailRecord4 ............................................... ................................................ MRecord[n] MRecord[n] _DetailRecord1 MRecord[n] MRecord[n] _DetailRecord2 MRecord[n] MRecord[n] _DetailRecord3 MRecord[n] MRecord[n] _DetailRecord4 ``` where [n] can be any number The problem is that for each unique Master Record, I should fetch the top 2 detail records O/P: ``` MasterRecord DetailRecord --------------------------------------------- MRecord1 MRecord1_DetailRecord1 MRecord1 MRecord1_DetailRecord2 MRecord2 MRecord2_DetailRecord1 MRecord2 MRecord2_DetailRecord2 MRecord3 MRecord3_DetailRecord1 MRecord3 MRecord3_DetailRecord2 ............................................... .............................................. MRecord[n] MRecord[n] _DetailRecord1 MRecord[n] MRecord[n] _DetailRecord2 ``` Hope I clearly explained my problem. Please let me know for further clarification.
Not sure if you wanted just records with two or records with one and two. Have a look here and let me know. ``` DECLARE @Master TABLE( MasterRecordID VARCHAR(20) ) INSERT INTO @Master (MasterRecordID) VALUES ('MASTER1') INSERT INTO @Master (MasterRecordID) VALUES ('MASTER2') INSERT INTO @Master (MasterRecordID) VALUES ('MASTER3') INSERT INTO @Master (MasterRecordID) VALUES ('MASTER4') DECLARE @MasterDetail TABLE( MasterRecordID VARCHAR(20), MasterDetailRecord VARCHAR(50) ) INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER4','MASTERDETAIL10') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER3','MASTERDETAIL09') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER3','MASTERDETAIL08') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER3','MASTERDETAIL07') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER2','MASTERDETAIL06') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER2','MASTERDETAIL05') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER2','MASTERDETAIL04') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER1','MASTERDETAIL03') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER1','MASTERDETAIL02') INSERT INTO @MasterDetail (MasterRecordID,MasterDetailRecord) VALUES ('MASTER1','MASTERDETAIL01') DECLARE @MaxRecords INT SELECT @MaxRecords = 2 SELECT md.MasterRecordID, md.MasterDetailRecord FROM @MasterDetail md INNER JOIN --this section ensures that we only return master records with at least MaxRecords as specified (2 in your case) --if you wish to display al master records, with 1, 2 or MaxRecords, romove this section or see below ( SELECT MasterRecordID FROM @MasterDetail GROUP BY MasterRecordID HAVING COUNT(MasterRecordID) >= @MaxRecords ) NumberOfRecords ON md.MasterRecordID = NumberOfRecords.MasterRecordID INNER JOIN @MasterDetail mdSmaller ON md.MasterRecordID = mdSmaller.MasterRecordID WHERE mdSmaller.MasterDetailRecord <= md.MasterDetailRecord GROUP BY md.MasterRecordID, md.MasterDetailRecord HAVING COUNT(mdSmaller.MasterDetailRecord) <= @MaxRecords ORDER BY md.MasterRecordID, md.MasterDetailRecord SELECT md.MasterRecordID, md.MasterDetailRecord FROM @MasterDetail md INNER JOIN --this will ensure that all master records will return with 1, 2 or MaxRecords @MasterDetail mdSmaller ON md.MasterRecordID = mdSmaller.MasterRecordID WHERE mdSmaller.MasterDetailRecord <= md.MasterDetailRecord GROUP BY md.MasterRecordID, md.MasterDetailRecord HAVING COUNT(mdSmaller.MasterDetailRecord) <= @MaxRecords ORDER BY md.MasterRecordID, md.MasterDetailRecord ``` Hope that helps
Try this: ``` WITH cteCount as ( Select ROW_NUMBER() OVER(PARTITION BY MRecord ORDER BY MR_DETAIL_COLUMN) as TopCnt, MR_DETAIL_COLUMN FROM MASTER_DETAIL_TABLE ) SELECT * FROM MASTER_TABLE as MT JOIN cteCount as MDT ON MDT.MRecord = MT.MRecord WHERE TopCnt <= 2 ``` Edit: corrected spelling typo Edit: corrected really dumb mistakes
Display records from Master/Master-Detail Table using SQL query only
[ "", "sql-server-2005", "sql", "" ]
I am using Quartz with Java to schedule jobs. One thing is that i store cron expressions on a database and i would like to present them to a user but in a more readable form. So i was wondering if there is a utility that could convert a cron expression into a human readable string. Something like : ""0 30 10-13 ? \* WED,FRI" will become "Fires at 10:30, 11:30, 12:30, and 13:30, on every Wednesday and Friday."
A Java library that converts cron expressions into human readable strings: <https://github.com/RedHogs/cron-parser>
Well yes I did understand your question. But I should have explained my answer a little better. No I don’t know any tool that will help you get a cron expression in “human” readable form. But by getting access to the CronExpression you can create you own. Try calling ``` cronTrigger.getExpressionSummary() ``` on the cron expression: ``` "0/2 * * 4 * ?" ``` it returns the following String: ``` seconds: 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58 minutes: * hours: * daysOfMonth: 4 months: * daysOfWeek: ? lastdayOfWeek: false nearestWeekday: false NthDayOfWeek: 0 lastdayOfMonth: false calendardayOfWeek: false calendardayOfMonth: false years: * ``` By having access to the CronExpression object, you can create your own "human" explenation.
Cron to human readable string
[ "", "java", "cron", "quartz-scheduler", "" ]
I'm writing server using boost.asio. I have read and write buffer for each connection and use asynchronized read/write function (`async_write_some` / `async_read_some`). With read buffer and `async_read_some`, there's no problem. Just invoking `async_read_some` function is okay because read buffer is read only in read handler (means in same thread usually). But, write buffer need to be accessed from several threads so it need to be locked for modifying. FIRST QUESTION! **Are there any way to avoid LOCK for write buffer?** I write my own packet into stack buffer and copy it to the write buffer. Then, call `async_write_some` function to send the packet. In this way, if I send two packet in serial, is it okay invoking `async_write_some` function two times? SECOND QUESTION! **What is common way for asynchronized writing in socket programming?** Thanks for reading.
## Answer #1: You are correct that locking is a viable approach, but there is a much simpler way to do all of this. Boost has a nice little construct in ASIO called a `strand`. Any callback that has been wrapped using the strand will be serialized, guaranteed, no matter which thread executes the callback. Basically, it handles any locking for you. This means that you can have as many writers as you want, and if they are all wrapped by the **same** strand (so, share your single strand among all of your writers) they will execute serially. One thing to watch out for is to make sure that you aren't trying to use the same actual buffer in memory for doing all of the writes. For example, this is what to avoid: ``` char buffer_to_write[256]; // shared among threads /* ... in thread 1 ... */ memcpy(buffer_to_write, packet_1, std::min(sizeof(packet_1), sizeof(buffer_to_write))); my_socket.async_write_some(boost::asio::buffer(buffer_to_write, sizeof(buffer_to_write)), &my_callback); /* ... in thread 2 ... */ memcpy(buffer_to_write, packet_2, std::min(sizeof(packet_2), sizeof(buffer_to_write))); my_socket.async_write_some(boost::asio::buffer(buffer_to_write, sizeof(buffer_to_write)), &my_callback); ``` There, you're sharing your actual write buffer (`buffer_to_write`). If you did something like this instead, you'll be okay: ``` /* A utility class that you can use */ class PacketWriter { private: typedef std::vector<char> buffer_type; static void WriteIsComplete(boost::shared_ptr<buffer_type> op_buffer, const boost::system::error_code& error, std::size_t bytes_transferred) { // Handle your write completion here } public: template<class IO> static bool WritePacket(const std::vector<char>& packet_data, IO& asio_object) { boost::shared_ptr<buffer_type> op_buffer(new buffer_type(packet_data)); if (!op_buffer) { return (false); } asio_object.async_write_some(boost::asio::buffer(*op_buffer), boost::bind(&PacketWriter::WriteIsComplete, op_buffer, boost::asio::placeholder::error, boost::asio::placeholder::bytes_transferred)); } }; /* ... in thread 1 ... */ PacketWriter::WritePacket(packet_1, my_socket); /* ... in thread 2 ... */ PacketWriter::WritePacket(packet_2, my_socket); ``` Here, it would help if you passed your strand into WritePacket as well. You get the idea, though. ## Answer #2: I think you are already taking a very good approach. One suggestion I would offer is to use `async_write` instead of `async_write_some` so that you are guaranteed the whole buffer is written before your callback gets called.
Sorry but you have two choices: 1. Serialise the write statement, either with locks, or better start a separate writer thread which reads requests from a queue, other threads can then stack up requests on the queue without too much contention (some mutexing would be required). 2. Give each writing thread its own socket! This is actually the better solution if the program at the other end of the wire can support it.
About write buffer in general network programming
[ "", "c++", "networking", "sockets", "boost-asio", "" ]
I am using SQL Server 2008. I have a table which has a datetime type column called CreateTime. I need to select all the records from this table whose CreateTime is more than 3 days and half an hour from current time (UTC time). I am using T-SQL store procedure. BTW: The CreateTime column is some time in the past time. I have taken quite some time to learn and search for help from MSDN for DateDiff, but cannot figure out. Could anyone show me a sample please? thanks in advance, George
You can select and add a WHERE clause with a DATEDIFF using minutes: ``` SELECT (fields) FROM (table) WHERE DATEDIFF(MINUTE, CREATETIME, getutcdate()) <= (3*24*60 + 30) ``` And of course, if you only wants those rows which are **MORE** than 3 days and 30 minutes away, just use the opposite: ``` WHERE DATEDIFF(MINUTE, CREATETIME, getutcdate()) > (3*24*60 + 30) ``` A sample: ``` SELECT DATEDIFF(MINUTE, '2009-08-01 08:00:00', getutcdate()), DATEDIFF(MINUTE, '2009-07-31 20:00:00', getutcdate()), DATEDIFF(MINUTE, '2009-07-23 20:00:00', getutcdate()) ``` gives as result: ``` 96 816 12337 ``` So the first two dates are still within your 4350 minute bracket (less than 3 days and 30 minutes ago), while the third date is further away. Marc
You need [DATEADD](http://msdn.microsoft.com/en-us/library/ms186819.aspx): ``` WHERE DATEADD(minute, 4350, CreateTime) <= getutcdate() ``` Or, as you mentioned, you can use [DATEDIFF](http://msdn.microsoft.com/en-us/library/ms189794.aspx): ``` WHERE DATEDIFF(minute, CreateTime, getutcdate()) <= 4350 ``` (4350 is '3 days and 30 minutes' in minutes)
DateDiff in SQL Server asking for help
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "stored-procedures", "" ]
As far as I can tell it is impossible to access the ViewState of a parent page from a popup. What is the best approach to accomplish passing this information? I have considered the following: Using the Session but this may have memory implications on the server. Passing data in querystring but this may have security implications exposing data and access method in page Any other ideas or recommendations? Thanks in advance
You don't want to use Viewstate - as that is tied to the parent page and not meant to be passed around. You can try passing some info via a querystring that has been encrypted. In a sense, this would be equal to what you were trying to accomplish via passing the viewstate. The viewstate is essentially data encrypted within your page - accessible just the same as the querystring. You could also use cookies, or session as well. If you have memory concerns with using session, I think storing state in a database would be more advantageous.
You could store the information in a database and then pass the row ID to the popup window in the query string.
Passing Viewstate Data to Popup Window
[ "", "c#", "asp.net", "popup", "viewstate", "" ]
I need to determine the number of files/subdirectories in a directory. I don't care which files/directories are actually in that directory. Is there a more efficient way than using ``` _directoryInfo.GetDirectories().Length + _directoryInfo.GetFiles().Length ``` Thanks.
That's probably about as good as it gets, but you should use [`GetFileSystemInfos()`](http://msdn.microsoft.com/en-us/library/806sc8c5.aspx) instead which will give you both files and directories: ``` _directoryInfo.GetFileSystemInfos().Length ```
``` string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); ``` then just take the size of the filePaths array code from: [C#-Examples](http://www.csharp-examples.net/get-files-from-directory/ "C#-Examples")
Determine number of files in a directory
[ "", "c#", ".net", "" ]
For example: MyApp is a web app that contains a properties file (server.properties) that describes config data (e.g. server names) for the app. In the development phase, server.properties is located in its own IDE project folder (a logical spot for it). Now it's time to deploy MyApp. The IDE makes it quite trivial to jar up the class files as well as the supporting config files. Now we just drop the Jar in the appropriate web container and away we go.... A week later... the server config data that MyApp uses needs to change. Which makes more sense? A. Modify the server.properties file back in IDE land and generate a completely new jar file. Redeploy. (which means bouncing the app for a simple configuration change). B. Crack open the already deployed Jar and modify the server.properties file? (may have to call a refresh function in MyApp if server.properties is cached... but should not require a full app bounce. Also need to remember to modify source server.properties as well so future deploys don't revert server.properties to the old server names). C. Make server.properties external to the jar file in the first place. Very similar to B's process, with the minor difference of keeping config data external to the jar (introduces different paths between development and production deploys) D. Other: Thanks!
I'd go with D. Try to load the properties files from outside the .jar then, if that fails, load the properties built into the jar. This lets you push out a "ready made" configuration with each build (also reduces the complexity of a deployment, if by just one file), while also making overriding configurations possible and reasonably simple.
If you are using Spring then you can make use of the property placeholder to do the work. ``` <!-- try and resolve the config from the filesystem first and then fallback to the classpath --> <context:property-placeholder location="file:config.properties, classpath:config.properties" ignore-resource-not-found="true"/> ``` You can specify a resource on the filesystem and also on the classpath, Spring will first try and resolve all of the properties from the filesystem and then fallback to the classpath. By specifying the "ignore-resource-not-found" attribute as "true" it will prevent Spring from throwing an exception if the file isn't present on the filesystem and allow it to resolve the properties from the classpath instead. Using this combination also allows you to split the properties over two files, for example you might never want to specify passwords in the file on the classpath and expect them to be specified externally on the filesystem. Any properties missing from the filesystem will be resolved from the classpath. In a folder containing: ``` application.jar config.properties ``` You should be able to use: ``` java -jar application.jar ``` This is a sample config.properties for reference: ``` # This file contains properties that are used to configure the application database.url=127.0.0.1 database.port=3306 database.user=root database.pass=p4ssw0rd ```
Is it bad practice to include properties/configuaration files within jars?
[ "", "java", "configuration", "properties", "jar", "" ]
In the simplest possible terms (I'm an occasional programmer who lacks up-to-date detailed programming knowledge) can someone explain the simplest way to make use of the registry in codegear C++ (2007). I have a line of code in an old (OLD!) program I wrote which is causing a significant delay in startup... DLB->Directory=pIniFile->ReadString("Options","Last Directory","no key!"); The code is making use of an ini file. I would like to be able to use the registry instead (to write variables such as the last directory the application was using) But the specifics are not important. I'd just like a generic how-to about using the registry that's specific to codegear c++ builder. I've googled this, but as usual with this type of thing I get lots of pages about c++ builder and a few pages about the windows registry, but no pages that explain how to use one with the other.
Use the TRegistry class... (include registry.hpp) ``` //Untested, but something like... TRegistry *reg = new TRegistry; reg->RootKey = HKEY_CURRENT_USER; // Or whatever root you want to use reg->OpenKey("theKey",true); reg->ReadString("theParam",defaultValue); reg->CloseKey(); ``` Note, opening and reading a ini file is usually pretty fast, so maybe you need to test your assumption that the reading of the ini is actually your problem, I don't think that just grabbing your directory name from the registry instead is going to fix your problem.
Include the Registry.hpp file: ``` #include <Registry.hpp> ``` Then in any function you have, you can write the following to read the value: ``` String __fastcall ReadRegistryString(const String &key, const String &name, const String &def) { TRegistry *reg = new TRegistry(); String result; try { reg->RootKey = HKEY_CURRENT_USER; if (reg->OpenKeyReadOnly(key)) { result = reg->ReadString(name, def); reg->CloseKey(); } } __finally { delete reg; } return result; } ``` So reading the value should be as easy as: ``` ShowMessage(ReadRegistryString("Options", "Last Directory", "none")); ``` You can use the following to write the value: ``` void __fastcall WriteRegistryString(const String &key, const String &name, const String &value) { TRegistry *reg = new TRegistry(); try { reg->RootKey = HKEY_CURRENT_USER; if (reg->OpenKey(key, true)) { reg->WriteString(name, value); reg->CloseKey(); } } __finally { delete reg; } } ``` Should be self explaining, remembering the try ... finally is actually really helpful when using the VCL TRegistry class. **Edit** I've heard that .ini files are stored in the registry in Windows, so if you want the speed advantage of ini files you should call them something else - like .cfg This is something I've heard from an although reliable source, I haven't tested it myself.
How do I use the registry?
[ "", "c++", "registry", "c++builder", "" ]
Using LINQ TO SQL as the underpinning of a Repository-based solution. My implementation is as follows: IRepository ``` FindAll FindByID Insert Update Delete ``` Then I have extension methods that are used to query the results as such: ``` WhereSomethingEqualsTrue() ... ``` My question is as follows: My Users repository has N roles. Do I create a Roles repository to manage Roles? I worry I'll end up creating dozens of Repositories (1 per table almost except for Join tables) if I go this route. Is a Repository per Table common?
If you are building your Repository to be specific to one Entity (table), such that each Entity has the list of methods in your IRepository interface that you listed above, then what you are really doing is an implementation of the [Active Record](http://en.wikipedia.org/wiki/Active_record_pattern) pattern. You should *definitely not* have one Repository per table. You need to identify the Aggregates in your domain model, and the operations that you want to perform on them. Users and Roles are usually tightly related, and generally your application would be performing operations with them in tandem - this calls for a single repository, centered around the User and it's set of closely related entities. I'm guessing from your post that you've [seen this example](http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx). The problem with this example is that all the repositories are sharing the same CRUD functionality at the base level, but he doesn't go beyond this and implement any of the domain functions. All the repositories in that example look the same - but in reality, real repositories don't all look the same (although they should still be interfaced), there will be specific domain operations associated with each one. Your repository domain operations should look more like: ``` userRepository.FindRolesByUserId(int userID) userRepository.AddUserToRole(int userID) userRepository.FindAllUsers() userRepository.FindAllRoles() userRepository.GetUserSettings(int userID) ``` etc... These are specific operations that your application wants to perform on the underlying data, and the Repository should provide that. Think of it as the Repository represents the set of atomic operations that you would perform on the domain. If you choose to share some functionality through a generic repository, and extend specific repositories with extension methods, that's one approach that may work just fine for your app. A good rule of thumb is that it should be *rare* for your application to need to instantiate multiple repositories to complete an operation. The need does arise, but if every event handler in your app is juggling six repositories just to take the user's input and correctly instantiate the entities that the input represents, then you probably have design problems.
> Is a Repository per Table common? No, but you can still have several repositiories. You should build a repository around an aggregate. Also, you might be able to abstract some functionality from all the repositories... and, since you are using Linq-to-Sql, you probably can... You can implement a base repository which in a generic way implements all this common functionality. The following example serves only to prove this point. It probably needs a lot of improvement... ``` interface IRepository<T> : IDisposable where T : class { IEnumerable<T> FindAll(Func<T, bool> predicate); T FindByID(Func<T, bool> predicate); void Insert(T e); void Update(T e); void Delete(T e); } class MyRepository<T> : IRepository<T> where T : class { public DataContext Context { get; set; } public MyRepository(DataContext context) { Context = Context; } public IEnumerable<T> FindAll(Func<T,bool> predicate) { return Context.GetTable<T>().Where(predicate); } public T FindByID(Func<T,bool> predicate) { return Context.GetTable<T>().SingleOrDefault(predicate); } public void Insert(T e) { Context.GetTable<T>().InsertOnSubmit(e); } public void Update(T e) { throw new NotImplementedException(); } public void Delete(T e) { Context.GetTable<T>().DeleteOnSubmit(e); } public void Dispose() { Context.Dispose(); } } ```
Loading Subrecords in the Repository Pattern
[ "", "c#", "linq-to-sql", "repository", "domain-driven-design", "design-patterns", "" ]
Is it possible to return an object from a static method in C++ like there is in Java? I am doing this: ``` class MyMath { public: static MyObject calcSomething(void); private: }; ``` And I want to do this: ``` int main() { MyObject o = MyMath.calcSomething(); // error happens here } ``` There are only static methods in the MyMath class, so there's no point in instantiating it. But I get this compile error: > MyMath.cpp:69: error: expected primary-expression before '.' token What am I doing wrong? Do I *have* to instantiate MyMath? I would rather not, if it is possible.
Use `::` instead of `.` `MyObject o = MyMath::calcSomething();` When you are calling the method without the object of the class you should use `::` notation. You may also call static method via class objects or pointers to them, in this case you should use usual `.` or `->` notation: ``` MyObject obj; MyObject* p = new MyObject(); MyObject::calcSomething(); obj.calcSomething(); p->calcSomething(); ```
> What am I doing wrong? You are simply using incorrect syntax... the `::` operator ([scope resolution operator](http://en.wikipedia.org/wiki/Scope_resolution_operator#C.2B.2B)) is how you would access classes or members in different namespaces: ``` int main() { MyObject o = MyMath::calcSomething(); // correct syntax } ``` > Do I have to instantiate MyMath? No.
How to call C++ static method
[ "", "c++", "static-methods", "" ]
I have a column that looks something like this: ``` CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product ``` And I would like to put it in my GROUP BY clause, but this seems to cause problems because there is an aggregate function in column. Is there a way to GROUP BY a column alias such as `some_product` in this case, or do I need to put this in a subquery and group on that?
My guess is that you don't really want to `GROUP BY` some\_product. The **answer to:** "Is there a way to `GROUP BY` a column alias such as some\_product in this case, or do I need to put this in a subquery and group on that?" **is:** You can not `GROUP BY` a column alias. The `SELECT` clause, where column aliases are assigned, is not processed until after the `GROUP BY` clause. An inline view or common table expression (CTE) could be used to make the results available for grouping. Inline view: ``` select ... from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product from ... group by col1, col2 ... ) T group by some_product ... ``` CTE: ``` with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product from ... group by col1, col2 ... ) select ... from T group by some_product ... ```
While [Shannon's answer](https://stackoverflow.com/a/1209151/241211) is technically correct, it looks like overkill. The simple solution is that you need to put your summation outside of the `case` statement. This should do the trick: ``` sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product ``` Basically, your old code tells SQL to execute the `sum(X*Y)` for each line individually (leaving each line with its own answer that can't be grouped). The code line I have written takes the sum product, which is what you want.
SQL GROUP BY CASE statement with aggregate function
[ "", "sql", "sql-server", "sql-server-2005", "group-by", "" ]
I'm creating a blog, and am storing user permissions (to post/edit/delete blog posts) in a mysql table. Should I create one column per permission, or combine all percussions into a string in one column such as 101 would mean that a user could post and delete but not edit. The reason I ask is that I am worried about having too many column in my table.
First of all, I would rule out combining all permissions into a single field. It seems economical at first, but it can turn into a bit of a problem if you will ever need to expand or modify your permissions structure. Creating a column for each permission in the user table is a good design for a simple system, but *may* limit your future expandability. I recommend implementing a many-to-many relationship between users and permissions. This allows you to add as many types of permissions you want without changing the schema. It is very easy to query with a simple join, and is portable to other databases. You accomplish this by creating two new tables. Assuming the following schema: ``` CREATE TABLE `users` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` VARCHAR(100), -- other user fields -- ); ``` We can add the m2m permissions schema like this: ``` CREATE TABLE `permissions` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(50) NOT NULL UNIQUE, ); CREATE TABLE `users_permissions` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY_KEY, `user_id` INT NOT NULL, `permission_id` INT NOT NULL ); ``` You might then add some sample users and permissions: ``` INSERT INTO `users` (DEFAULT, 'joe'); INSERT INTO `users` (DEFAULT, 'beth'); INSERT INTO `users` (DEFAULT, 'frank'); INSERT INTO `permissions` (DEFAULT, 'Administrator'); INSERT INTO `permissions` (DEFAULT, 'Write Blog'); INSERT INTO `permissions` (DEFAULT, 'Edit Blog'); INSERT INTO `permissions` (DEFAULT, 'Delete Blog'); ``` And finally you can associate users with permissions like so: ``` -- joe gets all permissions INSERT INTO `permissions` (DEFAULT, 1, 1); INSERT INTO `permissions` (DEFAULT, 1, 2); INSERT INTO `permissions` (DEFAULT, 1, 3); INSERT INTO `permissions` (DEFAULT, 1, 4); -- beth can write and edit INSERT INTO `permissions` (DEFAULT, 2, 2); INSERT INTO `permissions` (DEFAULT, 2, 3); -- frank can only write INSERT INTO `permissions` (DEFAULT, 3, 2); ``` For a smaller blog, you may not need a flexible schema like this, but it is a proven design. If you like, you can also take this one step further and create a role system. This works by giving each user a role (one-to-many), and each role has a number of permissions (many-to-many). This way permissions don't need to be set on a per-user basis, and you can simply assign them a role like "Administrator", or "Editor" or "Contributor", along with the associated permissions for that role.
My choice would be separate columns. Makes it easier to query later on if you are looking for specific permissions. You might want to check out some standard designs on permissions, no need to invent the wheel for the 4th time :)
MYSQL - one column per piece of data or combine into one column
[ "", "php", "mysql", "" ]
I'm teaching myself Python and I see the following in [Dive into Python](http://www.diveintopython.net/) [section 5.3](http://www.diveintopython.net/object_oriented_framework/defining_classes.html): > By convention, the first argument of any Python class method (the reference to the current instance) is called `self`. This argument fills the role of the reserved word `this` in C++ or Java, but `self` is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but `self`; this is a very strong convention. Considering that `self` is *not* a Python keyword, I'm guessing that it can sometimes be useful to use something else. Are there any such cases? If not, why is it *not* a keyword?
The only case of this I've seen is when you define a function outside of a class definition, and then assign it to the class, e.g.: ``` class Foo(object): def bar(self): # Do something with 'self' def baz(inst): return inst.bar() Foo.baz = baz ``` In this case, `self` is a little strange to use, because the function could be applied to many classes. Most often I've seen `inst` or `cls` used instead.
No, unless you want to confuse every other programmer that looks at your code after you write it. `self` is not a keyword because it is an identifier. It *could* have been a keyword and the fact that it isn't one was a design decision.
is it ever useful to define a class method with a reference to self not called 'self' in Python?
[ "", "python", "naming-conventions", "" ]
How can I accept strings like "$1,250.00" and convert it to a decimal in C#? Do I just do a replace("$", "") and (",", "") or is there a different way I should handle this kind of input?
Have you tried Decimal.Parse with the AllowCurrencySymbol option (and other supporting options)? ``` var d = Decimal.Parse(input, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands); ```
now with formatting :) ``` decimal val = Decimal.Parse( Value.Replace(" ", ""), NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol ); ``` <http://www.codeproject.com/KB/cs/Eduardo_Sierra.aspx>
How can I accept strings like "$1,250.00" and convert it to a decimal in C#?
[ "", "c#", "string", "decimal", "currency", "" ]
I'm attempting to compare two strings with **is**. One string is returned by a function, and the other is just declared in the comparison. **is** tests for object identity, but according to [this page](http://zetcode.com/tutorials/pythontutorial/keywords/), it also works with two identical strings because of Python's memory optimization. But, the following doesn't work: ``` def uSplit(ustring): #return user minus host return ustring.split('!',1)[0] user = uSplit('theuser!host') print type(user) print user if user is 'theuser': print 'ok' else: print 'failed' user = 'theuser' if user is 'theuser': print 'ok' ``` The output: ``` type 'str' theuser failed ok ``` I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use **==**, but I'm just curious.
The site you quote says this: > If two string literals are equal, they have been put to same memory location. But ``` uSplit('theuser!host') ``` is not a string literal -- it's the result of an operation on the literal `'theuser!host'`. Anyway, you usually shouldn't check for string equality using `is`, because this memory optimization in any case is just an implementation detail you shouldn't rely on. --- Also, You should use `is` for things like `is None`. Use it for checking to see if two objects -- of classes that you designed -- are the same instance. You can't easily use it for strings or numbers because the rules for creation of those built-in classes are complex. Some strings are interned. Some numbers, similarly, are interned.
That page you quoted says "If two string **literals** are equal, they have been put to same memory location" (emphasis mine). Python interns literal strings, but strings that are returned from some arbitrary function are separate objects. The `is` operator can be thought of as a pointer comparison, so two different objects will not compare as identical (even if they contain the same characters, ie. they are equal).
comparing two strings with 'is' -- not performing as expected
[ "", "python", "string-comparison", "string-literals", "" ]
I'm trying to migrate a bunch of tests from SimpleTest to [PHPUnit](https://en.wikipedia.org/wiki/PHPUnit) and I was wondering if there is an equivalent for SimpleTest's [partial mocks](http://www.simpletest.org/en/partial_mocks_documentation.html). I can't seem to find anything in the documentation which suggests that this feature is available, but it occurred to me that I could just use a subclass. Is this a good or bad idea? ``` class StuffDoer { protected function doesLongRunningThing() { sleep(10); return "stuff"; } public function doStuff() { return $this->doesLongRunningThing(); } } class StuffDoerTest { protected function doesLongRunningThing() { return "test stuff"; } } class StuffDoerTestCase extends PHPUnit_Framework_TestCase { public function testStuffDoer() { $sd = new StuffDoerTest(); $result = $sd->doStuff(); $this->assertEquals($result, "test stuff"); } } ```
From reading the linked page, a SimpleTest partial mock seems to be a mock where only some of the methods are overridden. If this is correct, that functionality is handled by a normal PHPUnit mock. Inside a `PHPUnit_Framework_TestCase`, you create a mock with ``` $mock = $this->getMock('Class_To_Mock'); ``` Which creates an mock instance where all methods do nothing and return null. If you want to only override some of the methods, the second parameter to `getMock` is an array of methods to override. ``` $mock = $this->getMock('Class_To_Mock', array('insert', 'update')); ``` will create an mock instance of `Class_To_Mock` with the `insert` and `update` functions removed, ready for their return values to be specified. This information is in the [phpunit docs](https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects). **Note**, [this answer](https://stackoverflow.com/a/43083956/1319821) shows more up to date code examples, for PHPUnit versions starting 5.4
[`PHPUnit_Framework_TestCase::getMock` is deprecated since phpunit 5.4](https://github.com/sebastianbergmann/phpunit/blob/aa47f767c5ecadab9df0862c34398e4ee582bb56/ChangeLog-5.4.md). We can use `setMethods` instead. > setMethods(array $methods) can be called on the Mock Builder object to specify the methods that are to be replaced with a configurable test double. The behavior of the other methods is not changed. If you call setMethods(null), then no methods will be replaced. <https://phpunit.de/manual/current/en/test-doubles.html> ``` $observer = $this->getMockBuilder(Observer::class) ->setMethods(['update']) ->getMock(); ``` Note that the above `getMock` is `PHPUnit_Framework_MockObject_MockBuilder::getMock`. (phpunit5.6)
Is there an equivalent of SimpleTest's "partial mocks" in PHPUnit?
[ "", "php", "phpunit", "simpletest", "" ]
I'm trying to install indefero on a CentOS 5.3 VMware 'box' and I ran into a problem. Quite early in the installation I get an error that I've been able to narrow down to this: ``` [root@code /var/www/html]# cat x.php <?php mb_internal_encoding("UTF-8"); ?> [root@code /var/www/html]# php x.php PHP Fatal error: Call to undefined function mb_internal_encoding() in /var/www/html/x.php on line 2 ``` I get the same error when calling this script via http through Apache. Now according to the [PHP manual the mb\_internal\_encoding function](http://php.net/manual/en/function.mb-internal-encoding.php) should be a builtin in PHP 5. I have CentOS 5.3 i386 (Linux code 2.6.18-53.1.21.el5 #1 SMP Tue May 20 09:34:18 EDT 2008 i686 i686 i386 GNU/Linux) and I've installed PHP 5.2.9. ``` [root@code /var/www/html]# php -v PHP 5.2.9 (cli) (built: Jul 8 2009 06:03:36) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies ``` I double checked: selinux has been disabled (for now). How do i fix this?
mbstring is a "non-default" extension, that is not enabled by default ; see [this page](http://www.php.net/manual/en/mbstring.installation.php) of the manual : > **Installation** > > mbstring is a non-default extension. > This means it is not enabled by > default. You must explicitly enable > the module with the configure option. > See the Install section for details So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account) I don't use CentOS, but you may have to install the extension first, using something like this *(see [this page](http://www.electrictoolbox.com/mbstring-php-extension-not-found-phpmyadmin/), for instance, which seems to give a solution)* : ``` yum install php-mbstring ``` *(The package name might be a bit different ; so, use yum search to get it :-) )*
For Debian/Ubuntu: `sudo apt-get install php7.0-mbstring`
Unable to call the built in mb_internal_encoding method?
[ "", "php", "mbstring", "" ]
I want to get the total number of items in the `List`s in the following `Dictionary`: ``` Dictionary<int, List<string>> dd = new Dictionary<int, List<string>>() { {1, new List<string> {"cem"}}, {2, new List<string> {"cem", "canan"}}, {3, new List<string> {"canan", "cenk", "cem"}} }; // This only returns an enumerated array. var i = (from c in dd select c.Value.Count).Select(p=>p); ```
I believe this will get you the count you want efficiently and clearly. Under the hood it has to iterate through the lists, but to get a total count, there is no way to avoid this. ``` var i = dd.Values.Sum(x => x.Count); ```
``` var i = dd.Values.SelectMany(v => v).Count(); ```
How do I get the sum of the Counts of nested Lists in a Dictionary without using foreach?
[ "", "c#", "linq", "dictionary", "" ]
Thanks to [this](https://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum) question I managed to work out how to constrain my generic method to accept only enums. Now I'm trying to create a generic method so that I can bind a drop-down to any enum I choose, displaying the description in the drop-down, with the value equal to the **numeric** value of the enum value. ``` public static object EnumToDataSource<T>() where T : struct, IConvertible { if (!typeof(T).IsEnum) // just to be safe throw new Exception(string.Format("Type {0} is not an enumeration.", typeof(T))); var q = Enum.GetValues(typeof(T)).Cast<T>() .Select(x => new { ID = DataUtil.ToByte(x), Description = x.ToString() }) // ToByte() is my own method for safely converting a value without throwing exceptions .OrderBy(x => x.Description); return q; } ``` Looks nice, but ToByte() always returns 0, even if my enumeration has values explicitly set, like so: ``` public enum TStatus : byte { Active = 1, Inactive = 0, } ``` Outside the generic method, if I cast a value of type `TStatus` to `byte`, it works perfectly. Inside the generic method, if I try cast something of type `T` to `byte` I get a compiler error. I can't find anything in the Enum static interface to do this, either. So, how do I get the numeric value of the enum inside the generic? (I'll also accept any other advice about optimizing my code gratefully...) **Edit:** Um, er... turns out that the thing wasn't working... because there was a bug in my ToByte() method... (blush). Oh well, thanks anyway - I learned a lot from this!
You can do it like this (change DataUtil.ToByte(x) to x.ToByte(null)): ``` public static object EnumToDataSource<T>() where T : struct, IConvertible { if (!typeof (T).IsEnum) throw new Exception(string.Format("Type {0} is not an enumeration.", typeof (T))); var q = Enum.GetValues(typeof (T)).Cast<T>().Select(x => new {ID = x.ToByte(null), Description = x.ToString()}).OrderBy( x => x.Description).ToArray(); return q; } ```
I think the simplest thing to do is use the Convert class instead of a cast: ``` T someValueThatIsAnEnum; byte enumValue = Convert.ToByte( (object)someValueThatIsAnEnum ); ``` Alternatively, you can rely on the fact that enums can convert themselves to a string representation, and parse themselves back as well: ``` T someValueThatIsAnEnum; string enumAsString = someValueThatIsAnEnum.ToString(); byte enunValue = (byte)Enum.Parse( typeof(T), enumAsString ); ```
How to get the data value of an enum in a generic method?
[ "", "c#", "linq", "generics", "enums", "" ]
I have a winform application and a list of logins to some web-service. Upon checking 'remember me' I serialize a dictionary into a file along with the encrypted password, but I wonder if this is the best practice to do such a thing or not.. Here's my code ``` public void LoginsInit() { FileStream file = new FileStream(loginsFilePath, FileMode.OpenOrCreate); try { BinaryFormatter formatter = new BinaryFormatter(); loginsDictionary = (Dictionary<string, string>)formatter.Deserialize(file); string[] allusers = loginsDictionary.Keys.ToArray(); int usersCount = allusers.Length; userNameTextBox.Text = allusers[usersCount - 1]; } catch (SerializationException ex) { loginsDictionary = new Dictionary<string, string>(); Console.WriteLine("Failed to open file: " + ex.Message); } finally { file.Close(); } } private void login_Click(object sender, EventArgs e) { //LoginToService(); string username; string password; username = serviceClientReference.UserLogin = userNameTextBox.Text; password = serviceClientReference.Password = EncryptDecrypt.Encrypt(this.passwordTextBox.Text, EncryptDecrypt.c_strEncryptkey1, EncryptDecrypt.c_strEncryptkey2); if (rememberMe.Checked) { if (loginsDictionary.ContainsKey(username)) loginsDictionary[username] = password; else loginsDictionary.Add(username, password); } FileStream file = new FileStream(loginsFilePath, FileMode.Create); try { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(file, loginsDictionary); file.Flush(); } catch (SerializationException ex) { Console.WriteLine("Failed to open file: " + ex.Message); } finally { file.Close(); } string errorStr; int errorNo; try { bool res = serviceClientReference.EstablishConnection(out errorStr, out errorNo); if (!res) { MessageBox.Show(errorStr); } } catch (Exception exception) { Logger.Log(TraceLevel.Error, "", exception); MessageBox.Show("Fatal Error Unable to login to MU"); } } private void usernameTextBox_TextChanged(object sender, EventArgs e) { if (loginsDictionary.ContainsKey(userNameTextBox.Text)) passwordTextBox.Text = EncryptDecrypt.Decrypt(loginsDictionary[userNameTextBox.Text], EncryptDecrypt.c_strEncryptkey1, EncryptDecrypt.c_strEncryptkey2); } ```
If you are trying to preserve user specific **Settings** across application instances then you should check the [Application Settings Architecture](http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx) that is built into .NET. That gives you persisting and reloading capabilities (some configuration required). There is also [Isolated Storage](http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.aspx) for additional security and features. Regardless of what you use continue to encrypt the Password.
You might want to consider using [DPAPI](http://blogs.msdn.com/shawnfa/archive/2004/05/05/126825.aspx) to manage your keys.
How to save logins in a winform application?
[ "", "c#", "winforms", "web-services", "authentication", "" ]
I need to validate a Canadian postal code (for example, `M4B 1C7`) using C# (.NET) regular expressions.
Canadian postal codes can't contain the letters D, F, I, O, Q, or U, and cannot start with W or Z: ``` [ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9] ``` If you want an optional space in the middle: ``` [ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9] ```
Here are the rules <http://en.wikipedia.org/wiki/Postal_code#Reserved_characters> ``` ABCEGHJKLMNPRSTVXY <-- letter used DFIOQU <-- letters not used because it mixes up the reader WZ <-- letters used but not in the first letter With that in mind the following in the proper regex @[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][\s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9] ```
Canadian postal code validation
[ "", "c#", ".net", "regex", "" ]
I want to write a method which can take an arbitrary array of a numeric type and return the sum of all the elements between startIndex and endIndex. This is what I have: ``` private static T SumArrayRange<T>(T[] scores, int startIndex, int endIndex) { T score = 0; for (int i = startIndex; i <= endIndex; i++) { score += scores[i]; } return score; } ``` But the compilation fails with these 2 errors. * Cannot implicitly convert type 'int' to 'T'. * Operator '+=' cannot be applied to operands of type 'T' and 'T' Is there any way I can force T to be only one of the numeric types (long, double etc.)? Or is their a more elegant way of solving this?
No, there's no way to constrain generic type parameters to use operators, and there are no good workarounds for that, either. A proper one would be an interface such as `INumeric` or `IArithmetic` with methods such as `Add`, `Subtract` etc, implemented by all primitive types such as `int` and `long`. There is a [5-year old feature request for that](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94264) in MS Connect, which is still Active. The latest word on that is: > Unfortunately, we've had to cut our plans to solve this problem in the .NET Framework 4.0. Until then, you are relegated to either: * using Reflection yourself - messy and very slow * using any of the existing wrappers that will use Reflection for you (e.g. [Microsoft.VisualBasic.CompilerServices.Operators](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators_members.aspx) class, with methods such as `AddObject`, `SubtractObject` etc which use reflection and implement VB semantics for the corresponding operators) - easy to use, but still very slow * hardcoding types you want to handle (i.e. no support for overloaded arithmetic operators on user-defined types), and using a giant `if (x is int) ... else if (x is double) ...` statement.
Another approach is to use the LINQ tools that are already available, rather than writing your own. For example: ``` var mySum = myCollection.Skip(startIndex).Take(count).Sum(); ``` Since the Sum extension method exists for all of the built-in numeric types, you don't have to worry about writing your own. Of course, this won't work if your code's "myCollection" variable is already of a generic collection type.
Get sum of elements of an Array in C# using generics
[ "", "c#", "arrays", "generics", "" ]
I want to run my .sql script file using my ASP.NET website through ADO.NET. How it could be it is not working? When I try ``` 'dbScript is a string and contains contents of the .sql file' Dim cmd As New SqlCommand(dbScript, con) Try con.Open() cmd.ExecuteNonQuery() Catch ex As Exception Finally con.Close() cmd.Dispose() End Try ``` I get exceptions when GO statement executed in script. How can I fix this problem?
See my blog post about [Handling GO Separators in SQL - The Easy Way](http://weblogs.asp.net/jgalloway/archive/2006/11/07/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-_2D00_-the-easy-way.aspx). The trick is to use [SMO's ExecuteNonQuery()](http://msdn2.microsoft.com/en-us/library/microsoft.sqlserver.management.common.serverconnection.executenonquery.aspx) method. For example, here's some code that will run all scripts in a directory, regardless of GO separators: ``` using System; using System.IO; using System.Data.SqlClient; using System.Collections.Generic; //Microsoft.SqlServer.Smo.dll using Microsoft.SqlServer.Management.Smo; //Microsoft.SqlServer.ConnectionInfo.dll using Microsoft.SqlServer.Management.Common; public class RunAllSqlSriptsInDirectory { public static void Main() { string scriptDirectory = "c:\\temp\\sqltest\\"; string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; DirectoryInfo di = new DirectoryInfo(scriptDirectory); FileInfo[] rgFiles = di.GetFiles("*.sql"); foreach (FileInfo fi in rgFiles) { FileInfo fileInfo = new FileInfo(fi.FullName); string script = fileInfo.OpenText().ReadToEnd(); SqlConnection connection = new SqlConnection(sqlConnectionString); Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } } } ```
GO is not a Transact-SQL statement, is a tools batch delimiter. The server rightfully complain of a syntax error when GO is encountered in a batch. You need to split the file into batches and then execute individual batches. Use a regular expression that splits the file inot batches and recognizes GO case insensitive on a single line.
How do I run my .sql script file through ADO.NET?
[ "", "asp.net", "sql", "ado.net", "" ]
I'm comparing dates with something like this: ``` var dt = new Date(); dt.setDate("17"); dt.setMonth(06); dt.setYear("2009"); var date = new Date(); console.log("dt(%s) == date(%s) == (%s)", dt, date, (dt == date) ); if( now == dt ) { .... } ``` The string values are dynamic of course. In the logs I see: ``` dt(Fri Jul 17 2009 18:36:56 GMT-0500 (CST)) == date(Fri Jul 17 2009 18:36:56 GMT-0500 (CST) == (false) ``` I tried .equals() but it didn't work ( I was trying the Java part of JavaScript :P ) How can I compare these dates so they return true?
The following code should solve your problem: ``` (myDate.getTime() == myOtherDate.getTime()) ``` The problem is that when you write: ``` (myDate == myOtherDate) ``` ...you're actually asking "Is `myDate` pointing to the same object that `myOtherDate` is pointing to?", not "Is `myDate` identical to `myOtherDate`?". The solution is to use `getTime` to obtain a number representing the Date object (and since `getTime` returns the number of milliseconds since epoch time, this number will be an *exact* representation of the Date object) and then use this number for the comparison (comparing numbers will work as expected).
The problem with your code is that you are comparing time/date part instead of only the date. Try this code: ``` var myDate = new Date(); myDate.setDate(17); myDate.setMonth(7); myDate.setYear(2009); //Delay code - start var total = 0; for(var i=0; i<10000;i++) total += i; //Delay code - end var now = new Date(); console.log(now.getTime() == myDate.getTime()); ``` If you keep the for loop code (identified by 'Delay code -start'), console will show 'false' and if you remove the for loop code, console will log 'true' even though in both the cases myDate is 7/17/2009 and 'now' is 7/17/2009. The problem is that JavaScript date object stores both date **and time**. If you only want to compare the date part, you have to write the code. ``` function areDatesEqual(date1, date2) { return date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate(); } ``` This function will print 'true' if the two javascript 'date part' is equal ignoring the associated time part.
Compare javascript dates
[ "", "javascript", "date-comparison", "" ]
Yes this is an exact duplicate of [this question](https://stackoverflow.com/questions/1007547/finding-mp3-length-in-c), but the link given and accepted as answer is not working for me. It is returning incorrect values (a 2 minutes mp3 will be listed as 1'30, 3 minutes as 2'20) with no obvious pattern. So here it is again: how can I get the length of a MP3 using C# ? *or* What am I doing wrong with the [MP3Header class](http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=79): ``` MP3Header mp3hdr = new MP3Header(); bool boolIsMP3 = mp3hdr.ReadMP3Information("1.mp3"); if(boolIsMP3) Response.Write(mp3hdr.intLength); ```
Apparently this class computes the duration using fileSize / bitRate. This can only work for constant bitrate, and I assume your MP3 has variable bitRate... EDIT : have a look at [TagLib Sharp](https://github.com/mono/taglib-sharp), it can give you the duration
How have you ascertained the lengths of the MP3s which are "wrong"? I've often found that the header information can be wrong: there was a particular version of LAME which had this problem, for example. If you bring the file's properties up in Windows Explorer, what does that show?
How to get the length of a MP3 in C#
[ "", "c#", ".net", "mp3", "duration", "" ]
Is there a way in PHP to find out what object called what method in another object. Exmaple: ``` class Foo { public function __construct() { $bar = new Bar(); $bar->test(); } } class Bar { public function test() { } } $foo = new Foo(); ``` Would there be a way for me to find out that the test method was called from the foo object?
you could use [`debug_backtrace`](http://php.net/manual/en/function.debug-backtrace.php), a bit like this : *BTW, take a look at the comments on the manual page : there are some useful functions and advices given ;-)* ``` class Foo { public function __construct() { $bar = new Bar(); $bar->test(); } } class Bar { public function test() { $trace = debug_backtrace(); if (isset($trace[1])) { // $trace[0] is ourself // $trace[1] is our caller // and so on... var_dump($trace[1]); echo "called by {$trace[1]['class']} :: {$trace[1]['function']}"; } } } $foo = new Foo(); ``` The `var_dump` would output : ``` array 'file' => string '/home/squale/developpement/tests/temp/temp.php' (length=46) 'line' => int 29 'function' => string '__construct' (length=11) 'class' => string 'Foo' (length=3) 'object' => object(Foo)[1] 'type' => string '->' (length=2) 'args' => array empty ``` and the `echo` : ``` called by Foo :: __construct ``` But, as nice as it might look like, I am not sure it should be used as a "normal thing" in your application... Seems odd, actually : with a good design, a method should not need to know what called it, in my opinion.
Here is one liner solution ``` list(, $caller) = debug_backtrace(false, 2); ``` As of PHP7 this won't work based on the docs: <http://php.net/manual/en/function.list.php> as we cannot have empty properties, here is a small update: ``` list($childClass, $caller) = debug_backtrace(false, 2); ```
Find out which class called a method in another class
[ "", "php", "" ]
Here is the case: I want to find the elements which match the regex... > targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext" and I use the regex in javascript like this ``` reg = new RegExp(/e(.*?)e/g); var result = reg.exec(targetText); ``` and I only get the first one, but not the follow.... I can get the T1 only, but not T2, T3 ... ...
``` function doSomethingWith(result) { console.log(result) } const targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext" const reg = /e(.*?)e/g; let result; while ((result = reg.exec(targetText)) !== null) { doSomethingWith(result); } ```
Three approaches depending on what you want to do with it: * Loop through each match: [`.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/match) ``` targetText.match(/e(.*?)e/g).forEach((element) => { // Do something with each element }); ``` * Loop through and replace each match on the fly: [`.replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/replace) ``` const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => { // Return the replacement leveraging the parameters. }); ``` * Loop through and do something on the fly: [`.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) ``` const regex = /e(.*?)e/g; // Must be declared outside the while expression, // and must include the global "g" flag. let result; while(result = regex.exec(targetText)) { // Do something with result[0]. } ```
How to loop all the elements that match the regex?
[ "", "javascript", "regex", "" ]
Essentially I want some simple reflection where I have an arbitrary DependencyProperty as a parameter. I'd have a special case (in an if statement, for example) if DependencyProperty is defined by / property of a PlaneProjection. I've done some simple fandangling of GetType() but no luck with the expected getters like MemberType. ``` public void SomeFunc(DependencyProperty dp) { // if dp is a dependency property of plane projection, do something // would maybe look like PlaneProjection.hasProperty(dp) } ```
Try this code with extension methods: ``` public static class Helpers { public static DependencyProperty FindDependencyProperty(this DependencyObject target, string propName) { FieldInfo fInfo = target.GetType().GetField(propName, BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); if (fInfo == null) return null; return (DependencyProperty)fInfo.GetValue(null); } public static bool HasDependencyProperty(this DependencyObject target, string propName) { return FindDependencyProperty(target, propName) != null; } public static string GetStaticMemberName<TMemb>(Expression<Func<TMemb>> expression) { var body = expression.Body as MemberExpression; if (body == null) throw new ArgumentException("'expression' should be a member expression"); return body.Member.Name; } } ``` Usage: ``` planeProjection1.HasDependecyProperty( Helpers.GetStaticMemberName(() => PlaneProjection.CenterOfRotationXProperty)); ```
Does this condition catch it? Edit: Only in WPF - not SilverLight. ``` dp.OwnerType.IsAssignableFrom(typeof(PlaneProjection)) ```
How to check if a dependency object contains a dependency property?
[ "", "c#", "silverlight", "" ]
I want to delete an item in a list when it matches some critera using UpdateListItems web service. I dont know the ID of the list item that I want to delete but do know the criteria. For example in SQL I could do: ``` DELETE FROM listName WHERE LastName='Bauer' AND FirstName='Jack' ``` How would you write a Batch Element to do this? **Update** Would it be something like this? ``` <Batch PreCalc='TRUE' OnError='Continue'> <Method ID='1' Cmd='Delete'> <Field Name='LastName'>Bauer</Field> <Field Name='FirstName'>Jack</Field> </Method> </Batch> ``` Is the ID for the Method or the ID of the thing you wish to delete? **Update** I have tried the following code and the error that is returned is ``` Invalid URL Parameter The URL provided contains an invalid Command or Value. Please check the URL again. ``` My guessing is that it is not possible to do without the ID...
This does not look possible. My way round this was to query the list and get the id's. Loop for the response pull out the id's then create a method for each ID to delete it.
As an addition to ChrisB's answer (formatting a CAML query in a comment didn't seem to work out), you'd make the query something like this: ``` SPQuery query = new SPQuery(); query.Query = "<Where><And>"+ "<Eq><FieldRef Name='LastName'/><Value Type='Text'>Bauer</Value></Eq>" "<Eq><FieldRef Name='FirstName'/><Value Type='Text'>Jack</Value></Eq>" "</And></Where>"; SPListItemCollection items = list.GetItems(query); ``` (this is the object model specification, but it extends naturally into the webservices call) Then you'd loop through the listitems and build up your batch.
Batch Element in Sharepoint to Delete a List item when you do not know the ID
[ "", "c#", "xml", "sharepoint", "moss", "caml", "" ]
I have method that transforms some input value by the user passing it a Func delegate wich returns the new value (very over simplified for what I am trying to achieve) ``` public L Coerce<L>(string value, Func<string, L> coercer) { return coercer(value); } Coerce<int>("123", v => int.Parse(v)); ``` This is fine however I also want to be able to write methods that override the behaviour for a specific type eg... ``` public int Coerce<int>(string value) { return Coerce<int>(value, v => int.Parse(v)); } ``` So basically calling ``` Coerce<int>("123"); // equivalent Coerce<int>("123", v => int.Parse(v)); ``` will save me having to re-write the int.Parse for every Coerce. Of course this should then extend to handle ``` public decimal Coerce<decimal>(string value) { return Coerce<decimal>(value, v => int.Parse(v)); } ``` Etc etc. Can this be done neatly? James
Well, if you *really* don't want to do ``` Convert.ToInt32(value) ``` Then this will do what you are asking: ``` public T Coerce<T>(string value) where T : IConvertible { return (T)(((IConvertible)value).ToType(typeof(T), CultureInfo.InvariantCulture)); } ``` Hence: ``` int x = Coerce<int>("123"); ``` or ``` byte b = Coerce<byte>("123"); ``` This will give you a compile-time error if you try to coerce to a non-convertible type, for example: ``` var x = Coerce<MyClass>("123"); //compile-time error ``` In which case you force the caller to use your `Coerce(string value, Func<string,T> coercer)` overload.
You could use a non-generic version: ``` public int CoerceInt32(string value) { return Coerce(value, int.Parse); } ```
Overload Generic Method for Specific Data Type
[ "", "c#", "" ]
One thing I have noticed with php, is that nothing is output to the screen until the script has stopped working. For the project I am working on I feed in a list of over 100 items and it performs a HTTP request for each item and when finished, shows a page with the status of each item, success failure etc. What I want to know is if there is a way to output the results of each 'foreach' loop as they happen? So the user watching the screen sees the magic happening one line at a time or after say 5 lines. I have only ever seen this done with Ajax type requests, is that what I should be looking to do instead maybe? Can anyone point me to a php function that does this or is it not possible?
It may be better to store all script output in a buffer then flush the buffer when required. For example: ``` <?php if (ob_get_level() == 0) ob_start(); $test = Array('one','two','three','four'); foreach ($test as $key=>$val) { echo $test; ob_flush(); flush(); } ob_end_flush(); ?> ``` Make sure you have mod\_gzip disabled!
[`flush()`](http://php.net/flush) should do it, or you can look at [all the output buffering functions](https://www.php.net/manual/en/ref.outcontrol.php)
PHP showing output of foreach to screen, for each item
[ "", "php", "ajax", "foreach", "" ]