Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am using a CList in a multithreaded environment and I keep having problem with the GetHead method. I have one thread that add data to the list, and an other thread who read and remove data from the list. Here is the reading part : ``` value_type get_next() { T t; if(!queue.IsEmpty()) { t = queue.GetHead(); } return t; //If the queue is empty we return an empty element } ``` Here is the inserting part : ``` inline void insert(T &_in) { queue.AddTail(_in); } ``` Here is the removing part ``` inline void pop_next() { if(!queue.IsEmpty()) { queue.RemoveHead(); } } ``` Why do I get a runtime error when I run this. It always fail at ``` t = queue.GetHead(); ``` With this assertion : ``` template<class TYPE, class ARG_TYPE> AFX_INLINE TYPE& CList<TYPE, ARG_TYPE>::GetHead() { ENSURE(m_pNodeHead != NULL); return m_pNodeHead->data; } ``` While the m\_pNodeHead value is : > * pNext 0x00000000 {pNext=??? pPrev=??? data={...} > } CList > >,ATL::CStringT > > &>::CNode \* > * pPrev 0x00000000 {pNext=??? pPrev=??? data={...} > } CList > >,ATL::CStringT > > &>::CNode \* > * data "" TESTSETSE ATL::CStringT > >
You have a race condition between inserting and retrieving the value. Add a lock that includes the entire body of get\_next(), insert(), and pop\_next().
`CList` is not thread safe - you'll need to use critical sections around those bits of code that check the status of the queue then do something with it. Also, why do you have the bit that works with an item on the queue a different thread than the bit that removes items from the queue?
Using CList in a multithreaded environment
[ "", "c++", "winapi", "mfc", "atl", "" ]
I have an XML DB and I have been able to parse the XML using DOM with JS. The thing I am unable to figure out is, how can I change a value in my XML db? I tried using: ``` xmlDoc.getElementsByTagName("COMMENT")[0].childNodes[0].nodeValue="text"; ``` But this does not changes the actual DB. When I refresh my page, it gives me the same old value again. What am I doing wrong? --- ### Edit: I am making changes only on the client page and not sending the data back to make relevant changes in database itself. I understand I should use AJAX or something, but could you please give me directions on what I should read or some examples where I can learn?
You cannot write to XML with JavaScript, only load a copy of the XML DOM into memory and manipulate that copy. Obviously that is destroyed when the JS instance restarts (reloading the page) or you re-load from the original file. If the XML is on the server, you will need a server-side language such as PHP, ASP.NET, Ruby on Rails, etc. to write anything to disk on the server. That code executes on the server, not in the browser. * [Reading and Writing XML in c#](http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTutMellli21.aspx) * [XML for PHP developers, Part 1](http://www.ibm.com/developerworks/library/x-xmlphp1.html) * [Ruby on Rails and XML](http://www.ibm.com/developerworks/edu/x-dw-x-rubyonrailsxml.html) To communicate between your JavaScript code and your server-side code, AJAX is the answer. [A List Apart has a good resource for getting started](http://www.alistapart.com/articles/gettingstartedwithajax). The simplest model that comes to mind is using AJAX to send the complete, modified XML chunk to server-side code, which simply saves it. If you are dealing with huge files and frequent updates, you may want to consider using AJAX to send manipulation instructions to the server-side code, which execute the changes and save the file.
You've told us basically no relevant info, but most likely you're just changing the client page, and making no effort to send back (e.g. with a form or AJAX) the changes.
How can I change an XML element value from JavaScript?
[ "", "javascript", "xml", "dom", "" ]
What does `%s` mean in Python? And what does the following bit of code do? For instance... ``` if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) ```
It is a string formatting syntax (which it borrows from C). Please see ["PyFormat"](https://pyformat.info/): > Python supports formatting values into > strings. Although this can include > very complicated expressions, the most > basic usage is to insert values into a > string with the `%s` placeholder. Here is a really simple example: ``` #Python 2 name = raw_input("who are you? ") print "hello %s" % (name,) #Python 3+ name = input("who are you? ") print("hello %s" % (name,)) ``` The `%s` token allows me to insert (and potentially format) a string. Notice that the `%s` token is replaced by whatever I pass to the string after the `%` symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
[Andrew's answer](https://stackoverflow.com/questions/997797/what-does-s-mean-in-a-python-format-string/997807#997807) is good. And just to help you out a bit more, here's how you use multiple formatting in one string: ``` "Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike". ``` If you are using ints instead of string, use %d instead of %s. ``` "My name is %s and I'm %d" % ('john', 12) #My name is john and I'm 12 ```
What does %s mean in a Python format string?
[ "", "python", "string-formatting", "" ]
In Visual Studio 2005 and prior you could export your code to Visio and view the relationships between the objects and what methods, properties and fields it had. This was great as it allowed you to tweak the appearance to improve the look. In VS 2008 that option is gone, replaced (supposedly) with the class diagram system. It is functional but not pretty. What I am looking for is some software that allows me to visualise in a prettier way or at least provide me with enough options to filter, arrange and so on so that I could touch it up in something else.
Do you require the software to be free? If not, you might consider a UML tool like [Sparx Enterprise Architect](http://www.sparxsystems.com). It can import your code, and has two add-ons that go further in terms of Visual Studio integration.
Not quite what you're asking for but it's worth checking out some of the [add-ins](http://www.codeplex.com/reflectoraddins) for [.Net Reflector](http://www.red-gate.com/products/reflector/) E.g. * [Graph](http://reflectoraddins.codeplex.com/Wiki/View.aspx?title=Graph) * [Dependency Structure Matrix PlugIn for .NET Reflector](http://tcdev.free.fr/) * [100% Reflective Class Diagram Creation Tool](http://www.codeproject.com/KB/cs/AutoDiagrammer.aspx)
C# Class/Object visualisation software
[ "", "c#", "class", "object", "visualization", "" ]
How to delete a given directory recursively in C# ? A directory containing files. Should the [System.IO.Directory.Delete](https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.delete) with the second parameter `true` do the trick? --- EDIT: So, I actually did answer my own question, although the answers here were a little more clarifying. The reason for me asking this in the first place was that the code that has exactly that invocation of `Delete` (2nd param set to `true`) was not doing what it was supposed to be doing. As it turned out the cause of that was that there was a file somewhere down in the the directory hierarchy with `RO` attribute set, and the *Polish* version of `Windows XP` was throwing a really strange message for that.
Yup, that's the point of that parameter. Did you try it and have any problems? (I've just double-checked, and it works fine for me.)
The only solution that worked for me if the subdirectories also contains files is by using a recursive function: ``` public static void RecursiveDelete(DirectoryInfo baseDir) { if (!baseDir.Exists) return; foreach (var dir in baseDir.EnumerateDirectories()) { RecursiveDelete(dir); } baseDir.Delete(true); } ``` It appears that Directory.Delete(dir, true) only delete files of the current directory, and subdirectories if they are empty. Hope it helps someone. btw, example: `RecursiveDelete( new DirectoryInfo(@"C:\my_dir") );`
Recursive delete of files and directories in C#
[ "", "c#", "" ]
I have a fairly large mysql database and I would like to count all the equal values, to explain myself better: I have a country field which has several countries values (USA, UK, MEX, etc..) and I want to get the number of countries without duplicate (if I have 100 USA and 2 UK and 1000 MEX the result would be 3). The only way I could come up with is: ``` $i="0"; $query = "SELECT DISTINCT country FROM table"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $i++; } echo $i; ``` I really do think there are better ways to achieve this, maybe directly trought a sql statement? As always thank you for your kind replies.
You've got mostly the right select statement, you just need to have MySQL do the counting for you: ``` SELECT COUNT(DISTINCT country) FROM table ```
SELECT country, COUNT(country) FROM table GROUP BY country
What is the best practice to count equal values in a database?
[ "", "php", "mysql", "" ]
I have the following code: ``` XmlSerializer SerializeObj = new XmlSerializer(dirs.GetType()); TextWriter WriteFileStream = new StreamWriter(@"G:\project\tester.xml"); SerializeObj.Serialize(WriteFileStream, dirs); WriteFileStream.Close(); ``` I'm trying to put a date/time stamp in FRONT of the xml file name. Therefore, using this example, i'd have something like 0615\_Tester.xml Any ideas on how to do this? I want to make sure i can do date/time\_\_[filename].xml and still specify it to be on my G:\ Thanks in advance.
Use string.Format - for example: ``` string dateString = "0615"; string fileName = string.Format(@"G:\project\{0}_tester.xml", dateString); ... = new StreamWriter(fileName); ``` Building up "dateString" should be trivial from DateTime.Now.
This is Simply achieved with System.IO.Path: ``` string path = "G:\\projects\\TestFile.xml"; string NewPath = System.IO.Path.GetDirectoryName(path) + System.IO.Path.DirectorySeperatorChar + DateTime.Now.ToString() + System.IO.Path.GetFileName(path); ``` You can add a using Reference to keep the Typing down, or Format the Date in any way you want as long as its a string. Using the DirectorySeperator Variable is reccommended, although you are probably programming for Windows If using .NET (Mono?)
Putting date in front of xml file name
[ "", "c#", "xml", "" ]
I'm trying to make a function that takes a character, then returns a pointer to a function depending on what the character was. I just am not sure how to make a function return a pointer to a function.
``` #include <iostream> using namespace std; int f1() { return 1; } int f2() { return 2; } typedef int (*fptr)(); fptr f( char c ) { if ( c == '1' ) { return f1; } else { return f2; } } int main() { char c = '1'; fptr fp = f( c ); cout << fp() << endl; } ```
``` int f(char) { return 0; } int (*return_f())(char) { return f; } ``` No, seriously, use a typedef :)
How to make a function return a pointer to a function? (C++)
[ "", "c++", "return-value", "function-pointers", "" ]
I'm tring to get a string from a DataSet *without* using GetXml. I'm using WriteXml, instead. How to use it to get a string? Thanks
``` string result = null; using (TextWriter sw = new StringWriter()) { dataSet.WriteXml(sw); result = sw.ToString(); } ```
Write to a [`StringWriter`](http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx), and then call `ToString` on that. Note that if you want the generated XML declaration to specify UTF-8 instead of UTF-16, you'll need something like my [`Utf8StringWriter`](https://stackoverflow.com/questions/955611/xmlwriter-to-write-to-a-string-instead-of-to-a-file/955698#955698#).
DataSet.WriteXml to string
[ "", "c#", ".net", "dataset", "" ]
Except for CPython, which other Python implementations are currently usable for production systems? The questions * [What are the pros and cons of the various Python implementations?](https://stackoverflow.com/questions/86134/what-are-the-pros-and-cons-of-the-various-python-implementations) * [I have been trying to wrap my head around the PyPy project. So, fast-foward 5-10 years in the future what will PyPy have to offer over CPython, Jython, and IronPython?](https://stackoverflow.com/questions/619437/i-have-been-trying-to-wrap-my-head-around-the-pypy-project-so-fast-foward-5-10) and * [Migrating from CPython to Jython](https://stackoverflow.com/questions/420792/migrating-from-cpython-to-jython/847629#847629) already shed some light on the pros/cons on the topic. I am wondering now, if those more exotic implementations are actually used in systems that have to run reliably. (possible examples? open-source?) **EDIT:** I'm asking for code that needs the Python version >= 2.5
**CPython** Used in many, many products and production systems **Jython** I am aware of production systems and products (a transactional integration engine) based on Jython. In the latter case the product has been on the market since the early 2000's. Jython is a bit stagnant (although it seems to have picked up a bit lately) but it is mature and stable. **IronPython** This is the new kid on the block, although it does have some track record in products. It (particularly version 1.x) can be viewed as stable and ready for production use, and development is officially funded by Microsoft, who appear to have an interest in dynamic languages on top of the CLR. It is the greenest of the major python implementations, but appears to be reasonably stable. **Stackless Python** This is used extensively in [EVE Online](http://eve-online.com), and they seem to view it as production ready. Bear in mind that Stackless Python has been around for something like 10 years.
At least one product, [Resolver One](http://www.resolversystems.com/), is said to be production-level and is totally based on [IronPython](http://www.codeplex.com/IronPython/). > Resolver One is a program that blends a familiar spreadsheet-like interface with the powerful Python programming language, giving you a tool with which to better analyse and present your data.
Production ready Python implementations besides CPython?
[ "", "python", "ironpython", "jython", "cpython", "pypy", "" ]
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the `workon` command. ``` me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ ``` How do I exit all virtual environments and work on my system environment again? Right now, the only way I have of getting back to `me@mymachine:~$` is to exit the shell and start a new one. That's kind of annoying. Is there a command to work on "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?
Usually, activating a virtualenv gives you a shell function named: ``` $ deactivate ``` which puts things back to normal. I have just looked specifically again at the code for `virtualenvwrapper`, and, yes, it too supports `deactivate` as the way to escape from all virtualenvs. If you are trying to leave an [*Anaconda*](https://en.wikipedia.org/wiki/Anaconda_(Python_distribution)) environment, the command depends upon your version of `conda`. Recent versions (like 4.6) install a `conda` function directly in your shell, in which case you run: ``` conda deactivate ``` Older conda versions instead implement deactivation using a stand-alone script: ``` source deactivate ```
Use: ``` $ deactivate ``` If this doesn't work, try ``` $ source deactivate ``` Anyone who knows how [Bash `source`](https://superuser.com/a/46146/3376) works will think that's odd, but some wrappers/workflows around virtualenv implement it as a complement/counterpart to `source activate`. Your mileage may vary.
How to leave/exit/deactivate a Python virtualenv
[ "", "python", "virtualenv", "exit", "virtualenvwrapper", "" ]
I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class. I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway). The following solution seems to work. ``` # This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # <-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #>Hi, my name is Joel. #>I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #>Hi, my name is Jeff A. #>The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #>Hi, my name is Jeff A. #>I'll have to remember malloc and free and pointer arithmetic and curly braces. ``` However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical `__class__` just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this. Is there? --- Edit: Thanks everyone for your answers. Here is what I get from them: * Although the idea of reclassing an instance by assigning to `__class__` is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments & votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general. * None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming. As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (`import this`), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way. * Using `{has,get,set}attr` seems more explicit, as we are explicitly making our changes to the object instead of using magic. * Using `__class__ = newclass` seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class. Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far. P.S. The actual use case is a UI data control object that needs to grow additional functionality *at runtime*. However, the question is meant to be very general.
Reclassing instances like this is done in [Mercurial](http://selenic.com/mercurial/) (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called `repo` and is initially a `localrepo` instance. It is passed to each extension in turn and, when needed, extensions will define a new class which is a subclass of `repo.__class__` and *change* the class of `repo` to this new subclass! It looks [like this](http://www.selenic.com/hg/index.cgi/file/d19ab9a56bf4/hgext/bookmarks.py#l229) in code: ``` def reposetup(ui, repo): # ... class bookmark_repo(repo.__class__): def rollback(self): if os.path.exists(self.join('undo.bookmarks')): util.rename(self.join('undo.bookmarks'), self.join('bookmarks')) return super(bookmark_repo, self).rollback() # ... repo.__class__ = bookmark_repo ``` The extension (I took the code from the bookmarks extension) defines a module level function called `reposetup`. Mercurial will call this when initializing the extension and pass a `ui` (user interface) and `repo` (repository) argument. The function then defines a subclass of whatever class `repo` happens to be. It would *not* suffice to simply subclass `localrepo` since extensions need to be able to extend each other. So if the first extension changes `repo.__class__` to `foo_repo`, the next extension should change `repo.__class__` to a subclass of `foo_repo` and not just a subclass of `localrepo`. Finally the function changes the instanceø's class, just like you did in your code. I hope this code can show a legitimate use of this language feature. I think it's the only place where I've seen it used in the wild.
I'm not sure that the use of inheritance is best in this case (at least with regards to "reclassing"). It seems like you're on the right track, but it sounds like composition or aggregation would be best for this. Here's an example of what I'm thinking of (in untested, pseudo-esque code): ``` from copy import copy # As long as none of these attributes are defined in the base class, # this should be safe class SkilledProgrammer(Programmer): def __init__(self, *skillsets): super(SkilledProgrammer, self).__init__() self.skillsets = set(skillsets) def teach(programmer, other_programmer): """If other_programmer has skillsets, append this programmer's skillsets. Otherwise, create a new skillset that is a copy of this programmer's""" if hasattr(other_programmer, skillsets) and other_programmer.skillsets: other_programmer.skillsets.union(programmer.skillsets) else: other_programmer.skillsets = copy(programmer.skillsets) def has_skill(programmer, skill): for skillset in programmer.skillsets: if skill in skillset.skills return True return False def has_skillset(programmer, skillset): return skillset in programmer.skillsets class SkillSet(object): def __init__(self, *skills): self.skills = set(skills) C = SkillSet("malloc","free","pointer arithmetic","curly braces") SQL = SkillSet("SELECT", "INSERT", "DELETE", "UPDATE") Bob = SkilledProgrammer(C) Jill = Programmer() teach(Bob, Jill) #teaches Jill C has_skill(Jill, "malloc") #should return True has_skillset(Jill, SQL) #should return False ``` You may have to read more about [sets](http://docs.python.org/library/stdtypes.html#set) and [arbitrary argument lists](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) if you aren't familiar with them to get this example.
Reclassing an instance in Python
[ "", "subclass", "python", "" ]
I am getting the warning ``` Warning: sendmailpm.jsp modified in the future. ``` What does this mean?
You aren't allowed to modify anything in the past if doing so might change the future. You might cause a temporal paradox, which could corrupt the time stream and cause our entire reality to cease to exist. Please do not modify that file.
JSP files are compiled. Many servers also allow you to replace the files on a running server. It then compares the timestamp of the compiled source and the timestamp of the jsp file to determine if it needs to recompile. If the file is dated in the future, the jsp file will always be newer than the class. This gives you a warning. Check the timestamp on the file. Perhaps someone created it on a computer with an incorrect clock, and now it appears to be "created in the future". Or perhaps the server has the incorrect date (check timezone settings). Are there remote file servers involved? Clock drift between a web server and a file server can cause this error too. To diagnose this further, you'd have to give us some hints - what jsp server, what OS, what filesystem?
Warning: modified in the future
[ "", "java", "jsp", "" ]
I use the following method in a piece of production code: ``` private void DownloadData(Uri uri) { WebClient webClient = new WebClient(); DownloadDataCompletedEventHandler eh = null; eh = delegate(object sender, DownloadDataCompletedEventArgs e) { webClient.DownloadDataCompleted -= eh; ((IDisposable) webClient).Dispose(); OnDataDownloaded(); }; webClient.DownloadDataCompleted += eh; webClient.DownloadDataAsync(uri); } ``` I am now worried that a hard to reproduce bug might be caused by the `WebClient` instance being garbage collected before the `DownloadDataCompleted` event is called: after exiting my `DownloadData()` method, there are no obvious references to the `WebClient` object, so that could plausibly happen. So my question is: can this realistically happen? I can not reproduce the problem, so there might be some internal things happening that prevents the `WebClient` object from being garbage collected (e.g. the object might register itself with a global object somewhere while waiting for the response). The code is running on .NET 2.0 if that makes any difference.
No, your object won't be GC-ed until the callback completes. According to [Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?](https://stackoverflow.com/questions/421547/does-the-garbage-collector-destroy-temporarily-unreferenced-objects-during-async), "*the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) and so it won't be garbage collected until it completes.*" But, your code is also doing stuff it doesn't need to: you don't need to detach the event handler and don't need to call Dispose on the webclient. (Dispose() is actually not implemented by WebClient-- you can can see this in the .NET Framework reference source at <http://referencesource.microsoft.com/netframework.aspx>). So you don't actually need to refer to the webclient instance in your callback. In other words, the following code will work just as well, and avoid any potential issues (discussed above) of referencing external local variables from inside a delegate. ``` private void DownloadData(Uri uri) { WebClient webClient = new WebClient(); DownloadDataCompletedEventHandler eh = null; eh = delegate(object sender, DownloadDataCompletedEventArgs e) { OnDataDownloaded(); }; webClient.DownloadDataCompleted += eh; webClient.DownloadDataAsync(uri); } ``` Anyway, you probably want to look elsewhere for the source of your bug. One place I'd look is at the results of the HTTP calls-- you may be running out of memory, may be running into server errors, etc. You can look at e.Error to see if the calls are actually working.
I don't know for sure whether the `WebClient` can normally be garbage collected or not while an async operation is in progress, because there may be internal references - but the bigger question is: does it matter? So long as enough of the `WebClient` stays "alive" to service the request and call your handler, does it matter whether the main `WebClient` object itself is garbage collected? The `WebClient` documentation doesn't mention anything about having to hold onto a reference (unlike the [`System.Threading.Timer` docs](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx), for instance) so I think it's reasonable to assume this is okay. In this particular case, your delegate has a reference to the `WebClient`, so as long as the delegate itself is referenced, the `WebClient` can't be. My educated guess is that some part of the system *somewhere* needs to hold a callback to know what to do when network traffic arrives, and that callback will eventually (indirectly) lead to your delegate, so you're okay.
.NET: Do I need to keep a reference to WebClient while downloading asynchronously?
[ "", "c#", ".net", "asynchronous", "garbage-collection", "webclient", "" ]
I've just received a new data source for my application which inserts data into a [Derby](http://db.apache.org/derby/) database only when it changes. Normally, missing data is fine - I'm drawing a line chart with the data (value over time), and I'd just draw a line between the two points, extrapolating the expected value at any given point. The problem is that as missing data in this case means "draw a straight line," the graph would be incorrect if I did this. There are two ways I could fix this: I could create a new class that handles missing data differently (which could be difficult due to the way prefuse, the drawing library I'm using, handles drawing), or I could duplicate the rows, leaving the *y* value the same while changing the *x* value in each row. I could do this in the Java that bridges the database and the renderer, or I could modify the SQL. My question is, given a result set like the one below: ``` +-------+---------------------+ | value | received | +-------+---------------------+ | 7 | 2000-01-01 08:00:00 | | 10 | 2000-01-01 08:00:05 | | 11 | 2000-01-01 08:00:07 | | 2 | 2000-01-01 08:00:13 | | 4 | 2000-01-01 08:00:16 | +-------+---------------------+ ``` Assuming I query it at 8:00:20, how can I make it look like the following using SQL? Basically, I'm duplicating the row for every second until it's already taken. `received` is, for all intents and purposes, unique (it's not, but it will be due to the `WHERE` clause in the query). ``` +-------+---------------------+ | value | received | +-------+---------------------+ | 7 | 2000-01-01 08:00:00 | | 7 | 2000-01-01 08:00:01 | | 7 | 2000-01-01 08:00:02 | | 7 | 2000-01-01 08:00:03 | | 7 | 2000-01-01 08:00:04 | | 10 | 2000-01-01 08:00:05 | | 10 | 2000-01-01 08:00:06 | | 11 | 2000-01-01 08:00:07 | | 11 | 2000-01-01 08:00:08 | | 11 | 2000-01-01 08:00:09 | | 11 | 2000-01-01 08:00:10 | | 11 | 2000-01-01 08:00:11 | | 11 | 2000-01-01 08:00:12 | | 2 | 2000-01-01 08:00:13 | | 2 | 2000-01-01 08:00:14 | | 2 | 2000-01-01 08:00:15 | | 4 | 2000-01-01 08:00:16 | | 4 | 2000-01-01 08:00:17 | | 4 | 2000-01-01 08:00:18 | | 4 | 2000-01-01 08:00:19 | | 4 | 2000-01-01 08:00:20 | +-------+---------------------+ ``` Thanks for your help.
It seems like in this case you really don't need to generate all of these datapoints. Would it be correct to generate the following instead? If it's drawing a straight line, you don't need go generate a data point for each second, just two for each datapoint...one at the current time, one right before the next time. This example subtracts 5 ms from the next time, but you could make it a full second if you need it. ``` +-------+---------------------+ | value | received | +-------+---------------------+ | 7 | 2000-01-01 08:00:00 | | 7 | 2000-01-01 08:00:04 | | 10 | 2000-01-01 08:00:05 | | 10 | 2000-01-01 08:00:06 | | 11 | 2000-01-01 08:00:07 | | 11 | 2000-01-01 08:00:12 | | 2 | 2000-01-01 08:00:13 | | 2 | 2000-01-01 08:00:15 | | 4 | 2000-01-01 08:00:16 | | 4 | 2000-01-01 08:00:20D | +-------+---------------------+ ``` If that's the case, then you can do the following: ``` SELECT * FROM (SELECT * from TimeTable as t1 UNION SELECT t2.value, dateadd(ms, -5, t2.received) from ( Select t3.value, (select top 1 t4.received from TimeTable t4 where t4.received > t3.received order by t4.received asc) as received from TimeTable t3) as t2 UNION SELECT top 1 t6.value, GETDATE() from TimeTable t6 order by t6.received desc ) as t5 where received IS NOT NULL order by t5.received ``` The big advantage of this is that it is a set based solution and will be much faster than any iterative approach.
Due to the set based nature of SQL, there's no simple way to do this. I have used two solution strategies: a) use a cycle to go from the initial to end date time and for each step get the value, and insert that into a temp table b) generate a table (normal or temporary) with the 1 minute increments, adding the base date time to this table you can generate the steps. Example of approach b) (SQL Server version) Let's assume we will never query more than 24 hours of data. We create a table **intervals** that has a dttm field with the minute count for each step. That table must be populated previously. ``` select dateadd(minute,stepMinutes,'2000-01-01 08:00') received, (select top 1 value from table where received <= dateadd(minute,dttm,'2000-01-01 08:00') order by received desc) value from intervals ```
Is it possible to temporarily duplicate and modify rows on the fly in an SQL SELECT query?
[ "", "sql", "derby", "" ]
I have a enum containing the following (for example): * UnitedKingdom, * UnitedStates, * France, * Portugal In my code I use **Country.UnitedKingdom** but I want to have the value be **UK** if I assign it to a **string** for example. Is this possible?
You can't assign an enum value to a string to start with. You'd have to call `ToString()`, which would convert `Country.UnitedKingdom` to "UnitedKingdom". Two options suggest themselves: * Create a `Dictionary<Country, string>` * A switch statement * Decorate each value with an attribute, and load that with reflection Comments about each of them... **Sample code for `Dictionary<Country,string>`** ``` using System; using System.Collections.Generic; enum Country { UnitedKingdom, UnitedStates, France, Portugal } class Test { static readonly Dictionary<Country, string> CountryNames = new Dictionary<Country, string> { { Country.UnitedKingdom, "UK" }, { Country.UnitedStates, "US" }, }; static string ConvertCountry(Country country) { string name; return (CountryNames.TryGetValue(country, out name)) ? name : country.ToString(); } static void Main() { Console.WriteLine(ConvertCountry(Country.UnitedKingdom)); Console.WriteLine(ConvertCountry(Country.UnitedStates)); Console.WriteLine(ConvertCountry(Country.France)); } } ``` You might want to put the logic of `ConvertCountry` into an extension method. For example: ``` // Put this in a non-nested static class public static string ToBriefName(this Country country) { string name; return (CountryNames.TryGetValue(country, out name)) ? name : country.ToString(); } ``` Then you could write: ``` string x = Country.UnitedKingdom.ToBriefName(); ``` As mentioned in the comments, the default dictionary comparer will involve boxing, which is non-ideal. For a one-off, I'd live with that until I found it was a bottleneck. If I were doing this for multiple enums, I'd write a reusable class. **Switch statement** I agree with [yshuditelu's answer](https://stackoverflow.com/questions/1008090/c-enum-values/1008116#1008116) suggesting using a `switch` statement for relatively few cases. However, as each case is going to be a single statement, I'd personally change my coding style for this situation, to keep the code compact but readable: ``` public static string ToBriefName(this Country country) { switch (country) { case Country.UnitedKingdom: return "UK"; case Country.UnitedStates: return "US"; default: return country.ToString(); } } ``` You can add more cases to this without it getting too huge, and it's easy to cast your eyes across from enum value to the return value. **`DescriptionAttribute`** The point [Rado made](https://stackoverflow.com/questions/1008090/c-enum-values/1008139#1008139) about the code for `DescriptionAttribute` being reusable is a good one, but in that case I'd recommend against using reflection every time you need to get a value. I'd probably write a generic static class to hold a lookup table (probably a `Dictionary`, possibly with a custom comparer as mentioned in the comments). Extension methods can't be defined in generic classes, so you'd probably end up with something like: ``` public static class EnumExtensions { public static string ToDescription<T>(this T value) where T : struct { return DescriptionLookup<T>.GetDescription(value); } private static class DescriptionLookup<T> where T : struct { static readonly Dictionary<T, string> Descriptions; static DescriptionLookup() { // Initialize Descriptions here, and probably check // that T is an enum } internal static string GetDescription(T value) { string description; return Descriptions.TryGetValue(value, out description) ? description : value.ToString(); } } } ```
I prefer to use the [DescriptionAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.descriptionattribute.aspx) on my enums. Then, you can use the following code to grab that description from the enum. ``` enum MyCountryEnum { [Description("UK")] UnitedKingdom = 0, [Description("US")] UnitedStates = 1, [Description("FR")] France = 2, [Description("PO")] Portugal = 3 } public static string GetDescription(this Enum value) { var type = value.GetType(); var fi = type.GetField(value.ToString()); var descriptions = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; return descriptions.Length > 0 ? descriptions[0].Description : value.ToString(); } public static SortedDictionary<string, T> GetBoundEnum<T>() where T : struct, IConvertible { // validate. if (!typeof(T).IsEnum) { throw new ArgumentException("T must be an Enum type."); } var results = new SortedDictionary<string, T>(); FieldInfo[] fieldInfos = typeof(T).GetFields(); foreach (var fi in fieldInfos) { var value = (T)fi.GetValue(fi); var description = GetDescription((Enum)fi.GetValue(fi)); if (!results.ContainsKey(description)) { results.Add(description, value); } } return results; } ``` And then to get my bound enum list, its simply a call to ``` GetBoundEnum<MyCountryEnum>() ``` To get a single enum's description, you'd just use the extension method like this ``` string whatever = MyCountryEnum.UnitedKingdom.GetDescription(); ```
C# Getting Enum values
[ "", "c#", ".net", "string", "enums", "" ]
OK I have 2 different version of Java install on my machine (CentOS 5), the system defaults to 1.5.0\_14 but I need to run a command on the command line with the newer version of Java. How can I pass the newer version in the command line? Sorry this is such a n00b question but I googled and didn't find anything, thanks.
Just use the full pathname for your java executable, rather than allowing the OS to pick one based on your PATH.
Use the absolute path to the java executable: `/opt/java-1.4/bin/java`
How to use a different version of Java on the command line
[ "", "java", "linux", "command-line", "" ]
For example, lets say you have two classes: ``` public class TestA {} public class TestB extends TestA{} ``` I have a method that returns a `List<TestA>` and I would like to cast all the objects in that list to `TestB` so that I end up with a `List<TestB>`.
Simply casting to `List<TestB>` almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning): ``` List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA; ```
Casting of generics is not possible, but if you define the list in another way it is possible to store `TestB` in it: ``` List<? extends TestA> myList = new ArrayList<TestA>(); ``` You still have type checking to do when you are using the objects in the list.
How do you cast a List of supertypes to a List of subtypes?
[ "", "java", "list", "generics", "collections", "casting", "" ]
I've inherited an ecommerce ASP.NET (c# code behind) web application. We've recently moved servers and it's proving somewhat troublesome. I have very little experience with IIS server configuration and dealing with large projects like this. Most of the problems have now been fixed, but we're experiencing problems with a crucial part, as a customer attempts to make a payment. As the customer confirms payment, the application encounters the following error: ``` Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode. ``` Stack Trace: ``` [SerializationException: Type 'PayerAuthentication.PayerAuthenticationServicePost' in Assembly 'PayerAuthentication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.] System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +7733643 System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +258 System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +111 System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) +161 System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) +51 System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +410 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +134 System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1577 ``` Google search results indicate I should add `[Serializable]` to the class declaration affected, but this is in a compiled dll to which I do not have the csproj. The code was working fine on the previous server and I do not believe any changes have been made to the code, only to web.config - what can I do? The sessionstate section of web.config reads `<sessionState mode="StateServer" />` **UPDATE1**: Using Reflector, I exported the class above, made it serializable, recompiled and replaced the dll. The order process went one step further, wherepon I encountered the same error for another dll-compiled class. Once again I was able to use Reflector to see the code, and then export it, edit and recompile. Now I have the same error occurring in: ``` SerializationException: Type 'System.Runtime.Remoting.Messaging.AsyncResult' in Assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.] ``` I'm not sure I can do anything about this, as this must be part of the .net system files! Any further ideas? **UPDATE2**: Ha, well I've subsequently discovered it's processing the payments correctly, but then throwing the above `Unable to serialize the session state` error on `System.Runtime.Remoting.Messaging.AsyncResult` before the user gets receipt of the transaction. Not good. Unsure how to move forward now... **UPDATE3**: I tried creating a copy of the `System.Runtime.Remoting.Messaging.AsyncResult` class, and making it serializable but this is then leading to inconsistent accessibility problems. ``` using System; using System.Runtime.InteropServices; using System.Threading; using System.Security.Permissions; using System.Runtime.Remoting.Messaging; [Serializable, ComVisible(true)] public class myAsyncResult : IAsyncResult, IMessageSink { // Fields private AsyncCallback _acbd; private Delegate _asyncDelegate; private object _asyncState; private ManualResetEvent _AsyncWaitHandle; private bool _endInvokeCalled; private bool _isCompleted; private IMessageCtrl _mc; private IMessage _replyMsg; // Methods internal myAsyncResult(Message m); //[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] public virtual IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink); private void FaultInWaitHandle(); public virtual IMessage GetReplyMessage(); public virtual void SetMessageCtrl(IMessageCtrl mc); //[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] public virtual IMessage SyncProcessMessage(IMessage msg); // Properties public virtual object AsyncDelegate { get; } public virtual object AsyncState { get; } public virtual WaitHandle AsyncWaitHandle { get; } public virtual bool CompletedSynchronously { get; } public bool EndInvokeCalled { get; set; } public virtual bool IsCompleted { get; } public IMessageSink NextSink { [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] get; } } ``` Specifically, that `error CS0122: 'System.Runtime.Remoting.Messaging.Message' is inaccessible due to its protection level`. I can see this is because Message is an internal class. But surely I can't change the accessibility level of it as it is part of the System.Runtime namespace. And making a copy and renaming it is going to cuase the same problem again, surely? Can anyone help me now? **FINAL UPDATE** Looks like, after all this, that it was the SSL certificate (see my answer below)
I now believe that this problem arose when we installed a new SSL certificate. The new certificate had Postcode extensions which our payment merchant HSBC doesn't accept over it's CPI payment gateway. Getting the correct SSL certificate installed seems to have finally solved this problem.
If you really wanted the code, you could try using Reflector's Class View. At the very least, it could help you verify whether or not `[Serializable]` was part of the problem class definition or not.
Serialization Exception in compiled dll
[ "", "c#", "asp.net", "web-applications", "serialization", "dll", "" ]
I have been trying to figure out if there are any differences between these constructors. Assuming there is a Foo() constructor that takes no arguments, are all these constructors going to have the same result? ## Example 1 ``` public Foo() : this() { blah; blah; blah; } ``` ## Example 2 ``` public Foo() { this(); blah; blah; blah; } ``` ## Example 3 ``` public Foo() { this = new Foo(); blah; blah; blah; } ```
* Example 1 is valid (assuming there is a parameterless constructor), and calls the parameterless constructor as part of initialization. See my [article on constructor chaining](http://pobox.com/~skeet/csharp/constructors.html) for more details. EDIT: Note that since the OP's edit, it's infinitely recursive. * Example 2 is never valid * Example 3 is only valid when Foo is a struct, and doesn't do anything useful. I would steer clear of assigning to `this` in structs. As you can see from the other answers, the very *possibility* of it is fairly rarely known (I only know because of some weird situation where it turned up in the spec). Where you've got it, it doesn't do any good - and in other places it's likely to be mutating the struct, which is *not* a good idea. Structs should always be immutable :) EDIT: Just to make people go "meep!" a little - assigning to `this` isn't quite the same as just chaining to another constructor, as you can do it in methods too: ``` using System; public struct Foo { // Readonly, so must be immutable, right? public readonly string x; public Foo(string x) { this.x = x; } public void EvilEvilEvil() { this = new Foo(); } } public class Test { static void Main() { Foo foo = new Foo("Test"); Console.WriteLine(foo.x); // Prints "Test" foo.EvilEvilEvil(); Console.WriteLine(foo.x); // Prints nothing } } ```
Examples 2 and 3 are not legal C#. EDIT: Jon points out accurately that 3 is legal when `Foo` is a `struct`. Go check out his answer!
Using this() in C# Constructors
[ "", "c#", "constructor", "" ]
I haven't been using Java extensively hence forget a lot fundamental things. Basically, I am working with a web-dynamic project (using Eclipse IDE with jdk 1.6), and during the build, I get errors that Cookie class and other web related classes cannot be found. What am I missing? What Jars files do I need to add (and how)? thanks
Think you need servlet-api.jar Try here for any jar files you need <http://www.java2s.com/Code/Jar/CatalogJar.htm>
Sounds like you are missing `servlet-api.jar` You can download it from the [Maven repository](http://repo2.maven.org/maven2/javax/servlet/servlet-api/2.5/).
Missing javax.servlet.http.Cookie class
[ "", "java", "eclipse", "" ]
Have a linking (or ref) table which has a dual primary key. Need to return the last primary key which was auto generated from the current connection in a selected table. This is in java. The database is in MS Access if that makes a difference. Sorry for the rushed description, but our team is working to a tight schedule. Any links or suggestions would be gladly appreciated. EDIT: The database is populated using SQL. We enter the data for one form, but we do not know the auto generated number. Need to find out what this was so it can be entered into the ref table. We only know half the composite key, which is why we need the second one. Edit: Re the best answer so far (cant seem to comment). I get the following error... "Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException" Any Advice?
You need to do two things. First, you'll have to pass in an extra parameter when preparing your statement or executing your statement. If you're using prepared statements, do the following: ``` stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ``` If you're not using prepared statements, do the following when you call executeUpdate(): ``` stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); ``` After you execute your statement, you can call ``` ResultSet rs = stmt.getGeneratedKeys() ``` This will give you a result set that contains any of the keys that were generated. I haven't tried this approach with Access, but it works fine with SQL Server identity columns.
Statement.getGeneratedKeys() should do the trick...
How do I return the last primary key of the last added item in java?
[ "", "java", "database", "methods", "primary-key", "return", "" ]
I have a gridview that is bound to the result from an nhibernate query. If the first item in the list is edited the following exception is thrown: `System.Reflection.TargetException: Object does not match target type` It appears that the problem is caused by the fact that databinding can't deal with the first item in the list being a subtype of the other items in the list. What is a nice / correct way to solve this problem? Currently I have had to turn off nhibernates proxying. **Edit:** I have another couple of solutions: * Clone everything in the list (<http://steve-fair-dev.blogspot.com/2007/08/databind-object-does-not-match-target.html>) - this doesn't work for me as the object doesn't implement ICloneable * change the order of items in the list so that the proxy isn't first (<http://community.devexpress.com/forums/t/30797.aspx>) - this is so hacky, I don't think I can stoop this low! But none of these feel right though...
Is the root cause due to a proxy object in the list (from lazy loading) or because the list isn't homogeneous (contains multiple types even if they belong to the same class hierarchy)? The problem with non-homogeneous data sets is a known limitation. See [this](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=104485) and [this](https://stackoverflow.com/questions/333163/how-to-bind-a-gridview-to-a-list-of-multiple-types). I don't think there's a solution other than to not use databinding to populate the grid. That's easy enough if it's read-only.
Maybe too late, but I'd just like to throw this into the ring, here is a solution that I've used for this. It is also called 'SafeBindingList' like the other suggestion above, but, it does not 'clone' objects to solve the problem. It looks at the objects in the list, then if none proxied, the list is returned unmodified. If one or more objects are proxied, it adds an empty proxy to the non-proxied objects, thus making them all the same type. So, instead returning a List[T] to bind to, use SafeBindingList[T] to ensure all objects have the same type. This is updated for the version of Castle used with NH2.0.1: <http://code.google.com/p/systembusinessobjects/source/browse/trunk/System.BusinessObjects.Framework/Data/SafeBindingLists.cs> Also, credit goes to the original code and poster: <https://forum.hibernate.org/viewtopic.php?t=959464&start=0&postdays=0&postorder=asc&highlight=>
NHibernate proxy causing problems with databinding
[ "", "c#", "asp.net", "nhibernate", "proxy", "data-binding", "" ]
In a string that includes quotes, I always get an extra whitespace before the end quote. For instance > "this is a test " *(string includes quotes)* Note the whitespace after *test* but before the *end quote*. How could I get rid of this space? I tried rtrim but it just applies for chars at the end of the string, obviously this case is not at the end. Any clues? Thanks
Here's another way, which only matches a sequence of spaces and a quote at the *end* of a string... ``` $str=preg_replace('/\s+"$/', '"', $str); ```
Well, get rid of the quotes, then trim, then put the quotes back. Let's make a clean function for that : ``` <?php function clean_string($string, $sep='"') { // check if there is a quote et get rid of them $str = preg_split('/^'.$sep.'|'.$sep.'$/', $string); $ret = ""; foreach ($str as $s) if ($s) $ret .= trim($s); // triming the right part else $ret .= $sep; // putting back the sep if there is any return $ret; } $string = '" this is a test "'; $string1 = '" this is a test '; $string2 = ' this is a test "'; $string3 = ' this is a test '; $string4 = ' "this is a test" '; echo clean_string($string)."\n"; echo clean_string($string1)."\n"; echo clean_string($string2)."\n"; echo clean_string($string3)."\n"; echo clean_string($string4)."\n"; ?> ``` Ouputs : ``` "this is a test" "this is a test this is a test" this is a test "this is a test" ``` This handle strings with no quote, with one quote only at the beginning / end, and fully quoted. If you decide to take " ' " as a separator, you can just pass it as a parameter.
Trimming a white space
[ "", "php", "string", "" ]
I'm implementing a notification framework for one of my projects. As i want it to be very generic, the user can use several transport layers, so that he doesn't really need to care about using one delivery method (lets say WCF) or another (for eg ActiveMQ). The interface the user has access is of course independent of the delivery method (WCF or ActiveMQ). Still, the two classes (consumer and producer) implements singletons, so they actually use default constructors (meaning, no parameters). My problem is that i would like to have one parameter, the delivery method the user want to use. But as far as i know, singleton only use default constructors? which is normal, as there should be no point of using singletons with parameters. So, what are my options here? not to create a singleton? create a method to set the delivery method? ## Thank you very much for your help, Sebastian
You can certainly have parameters with singletons, except instead of passing the parameter into a constructor, you are passing it into the getInstance() method. Your overridden constructor needs to be private of course for a true singleton implementation. My example is written in Java but applies for C# as well. Example: ``` Singleton s = Singleton.getInstance(42); ``` In the Singleton code: ``` private Singleton() { } private Singleton(int num) { //set num } public getInstance(int num) { //singleton code (calls the private non-default constructor if an object //does not already exist) } ```
There are some dependency injection frameworks like Spring.Net which might help you. You can effectively pass a parameter in a configuration file for your singletons constructor. [Link to a Spring Framework example](http://www.springframework.net/doc-latest/reference/html/quickstarts.html) Might I suggest that if you have two different behaviours required of your singleton that you might want to subclass. That way you get the behaviour that you want by calling the singleton of the class behaviour you want.
Possible to use a singleton with a non-default constructor in C#?
[ "", "c#", "singleton", "default-constructor", "" ]
As I make the full switch from Windows to Linux (CentOS 5) I'm in search of the best free GUI SQL Client tool for MSSQL, MySQL, Oracle, etc... any suggestions? I've tried DBVisualizer (The best bet so far but still limited by the free version, not all functionality is there), MySQL GUI Tools (Good but only for MySQL, need other DB's as well) and Aqua Data Studio (Same as DBVis, it's good but a lot of the functionality is missing in the free version).
I'm sticking with DbVisualizer Free until something better comes along. EDIT/UPDATE: been using <https://dbeaver.io/> lately, really enjoying this
I can highly recommend [Squirrel SQL](http://squirrel-sql.sourceforge.net/). Also see this similar question: [Developer tools to directly access databases](https://stackoverflow.com/questions/721852/developer-tools-to-directly-access-databases)
What is the best free SQL GUI for Linux for various DBMS systems
[ "", "sql", "linux", "" ]
How can I get the extension of compressed file after being compressed with `System.IO.Compression.GZipStream`? For example, if the original file is named `test.doc` and compresses to `test.gz`, how do I know what file extension to use when decompressing?
I had to do this some time ago. The solution is to use the J# libraries to do it. You still write it in C# however. <http://msdn.microsoft.com/en-us/magazine/cc164129.aspx> That's microsofts answer on the topic.
There is no way to get the file name - in fact there may never be a filename at all, if for example a piece of data is created in memory and then send over a network connection. Instead of replacing the file extension, why not append it, for example: test.doc.gz Then you can simply strip it off when decompressing.
Compress a file with GZipStream while maintaining its meta-data
[ "", "c#", ".net", "compression", "" ]
Like the subject says I have a listview, and I wanted to add the `Ctrl` + `A` select all shortcut to it. My first problem is that I can't figure out how to programmatically select all items in a listview. It seems like it should be relatively easy, like `ListView.SelectAll()` or `ListView.Items.SelectAll()`, but that doesn't appear to be the case. My next problem is how to define the keyboard shortcut for the `ListView`. Do I do it in a `KeyUp` event, but then how would you check two presses at once? Or is it a property that you set? Any help here would be great.
You could accomplish both with something like this: ``` private void listView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A && e.Control) { listView1.MultiSelect = true; foreach (ListViewItem item in listView1.Items) { item.Selected = true; } } } ```
These works for small lists, but if there are 100,000 items in a virtual list, this could take a long time. This is probably overkill for your purposes, but just in case:: ``` class NativeMethods { private const int LVM_FIRST = 0x1000; private const int LVM_SETITEMSTATE = LVM_FIRST + 43; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct LVITEM { public int mask; public int iItem; public int iSubItem; public int state; public int stateMask; [MarshalAs(UnmanagedType.LPTStr)] public string pszText; public int cchTextMax; public int iImage; public IntPtr lParam; public int iIndent; public int iGroupId; public int cColumns; public IntPtr puColumns; }; [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)] public static extern IntPtr SendMessageLVItem(IntPtr hWnd, int msg, int wParam, ref LVITEM lvi); /// <summary> /// Select all rows on the given listview /// </summary> /// <param name="list">The listview whose items are to be selected</param> public static void SelectAllItems(ListView list) { NativeMethods.SetItemState(list, -1, 2, 2); } /// <summary> /// Deselect all rows on the given listview /// </summary> /// <param name="list">The listview whose items are to be deselected</param> public static void DeselectAllItems(ListView list) { NativeMethods.SetItemState(list, -1, 2, 0); } /// <summary> /// Set the item state on the given item /// </summary> /// <param name="list">The listview whose item's state is to be changed</param> /// <param name="itemIndex">The index of the item to be changed</param> /// <param name="mask">Which bits of the value are to be set?</param> /// <param name="value">The value to be set</param> public static void SetItemState(ListView list, int itemIndex, int mask, int value) { LVITEM lvItem = new LVITEM(); lvItem.stateMask = mask; lvItem.state = value; SendMessageLVItem(list.Handle, LVM_SETITEMSTATE, itemIndex, ref lvItem); } } ``` and you use it like this:: ``` NativeMethods.SelectAllItems(this.myListView); ```
Adding a select all shortcut (Ctrl + A) to a .net listview?
[ "", "c#", ".net", "listview", "keyboard-shortcuts", "" ]
I'd like to code a function like the following ``` public void Foo(System.Type t where t : MyClass) { ... } ``` In other words, the argument type is `System.Type`, and I want to restrict the allowed `Type`s to those that derive from `MyClass`. Is there any way to specify this syntactically, or does `t` have to be checked at runtime?
If your method has to take a `Type` type as it's argument, there's no way to do this. If you have flexibility with the method call you could do: ``` public void Foo(MyClass myClass) ``` and the get the `Type` by calling `.GetType()`. To expand a little. `System.Type` is the type of the argument, so there's no way to further specify what should be passed. Just as a method that takes an integer between 1 and 10, must take an int and then do runtime checking that the limits were properly adhered to.
Specifying the type be MyClass, or derived from it, **is a value check** on the argument itself. It's like saying the hello parameter in ``` void Foo(int hello) {...} ``` must be between 10 and 100. It's not possible to check at compile time. You must use generics or check the type at run time, just like any other parameter value check.
C#: Restricting Types in method parameters (not generic parameters)
[ "", "c#", ".net", "types", "polymorphism", "" ]
What are the best practices of creating war files (using eclipse) to run on tomcat? tutorials, links, examples are highly appreciated.
You can use [Ant](http://ant.apache.org/manual/) to set up, compile, [WAR](http://ant.apache.org/manual/Tasks/war.html), and deploy your solution. ``` <target name="default" depends="setup,compile,buildwar,deploy"></target> ``` You can then execute one click in Eclipse to run that Ant target. Here are examples of each of the steps: ### Preconditions We'll assume that you have your code organized like: * `${basedir}/src`: Java files, properties, XML config files * `${basedir}/web`: Your JSP files * `${basedir}/web/lib`: Any JARs required at runtime * `${basedir}/web/META-INF`: Your manifest * `${basedir}/web/WEB-INF`: Your web.xml files ### Set up Define a `setup` task that creates the distribution directory and copies any artifacts that need to be WARred directly: ``` <target name="setup"> <mkdir dir="dist" /> <echo>Copying web into dist</echo> <copydir dest="dist/web" src="web" /> <copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" /> </target> ``` ### Compile Build your Java files into classes and copy over any non-Java artifacts that reside under `src` but need to be available at runtime (e.g. properties, XML files, etc.): ``` <target name="compile"> <delete dir="${dist.dir}/web/WEB-INF/classes" /> <mkdir dir="${dist.dir}/web/WEB-INF/classes" /> <javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src"> <classpath> <fileset dir="${basedir}/../web/WEB-INF/lib"> <include name="*" /> </fileset> </classpath> </javac> <copy todir="${dist.dir}/web/WEB-INF/classes"> <fileset dir="src"> <include name="**/*.properties" /> <include name="**/*.xml" /> </fileset> </copy> </target> ``` ### Build WAR Create the WAR itself: ``` <target name="buildwar"> <war basedir="${basedir}/dist/web" destfile="My.war" webxml="${basedir}/dist/web/WEB-INF/web.xml"> <exclude name="WEB-INF/**" /> <webinf dir="${basedir}/dist/web/WEB-INF/"> <include name="**/*.jar" /> </webinf> </war> </target> ``` ### Deploy Finally, you can set up a task to deploy the WAR directly into your Tomcat deploy location: ``` <target name="deploy"> <copy file="My.war" todir="${tomcat.deploydir}" /> </target> ``` ### Click and go! Once all this is set up, simply launching the `default` target from Eclipse will compile, WAR, and deploy your solution. The advantage of this approach is that it will work outside Eclipse as well as within Eclipse and can be used to easily share your deployment strategy (e.g. via source control) with other developers who are also working on your project.
I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.
How to create war files
[ "", "java", "eclipse", "tomcat", "war", "" ]
I have a design problem. I have two data objects which are instances of say class A and class B. A and B don't have any behavior - they are java beans with getters and setters. I have a Validation interface and 10 implementations of it defining different Validations. I would like to specify in my properties file which Validation applies to which class. Something like this: class A XYZValidation,ABCValidation class B: ABCValidation, PPPValidation, etc How do I write my Validation class so that it serves objects that are instances of Class A OR ClassB, or just about any other Class C that I might want to add in future? ``` interface Validation { public boolean check(??); } ``` ***> Just wanted to add this line to say thank you to all those who have responded to this post and to say that I am loving my time here on this amazing website. Stackoverflow rocks!***
Have you thought about using annotations to mark the fields you want to validate in your bean? If you have 10 different validations you could specify 10 annotations. Then mark the fields using annotations: ``` @ValideStringIsCapitalCase private String myString; @ValidateIsNegative private int myInt; ``` With reflection API iterate through all the fields and see if they are marked, something like this: ``` public static <T> validateBean(T myBean) throws IllegalAccessException { Field[] fields = myBean.getClass().getDeclaredFields(); // This does not take fields of superclass into account if (fields != null) { for (Field field : allFields) { if (field.isAnnotationPresent(ValideStringIsCapitalCase.class)) { field.setAccessible(true); Object value = field.get(existingEntity); // Validate field.setAccessible(false); } } } } ``` An option would be to mark the whole class with the validator you want to use. EDIT: remember to include annotation: ``` @Retention(RetentionPolicy.RUNTIME) ``` for your annotation interface. EDIT2: please don't modify the fields directly (as in the example above). Instead access their getters and setters using reflection.
I've probably misunderstood the question but would something like this suffice: ``` public class ValidationMappings { private Map<Class, Class<Validation>[]> mappings = new HashMap<Class, Class<Validation>[]>(); public ValidationMappings() { mappings.put(A.class, new Class[]{XYZValidation.class, ABCValidation.class}); mappings.put(B.class, new Class[]{ABCValidation.class, PPPValidation.class}); } public Class[] getValidators(Class cls) { if (!mappings.containsKey(cls)) return new Class[]{}; return mappings.get(cls); } } ``` When you want to get the list of validators for a particular class, you would then call getValidators(Class cls) and iterate over each validator and create an instance of each and call your check method.
Design question - java - what is the best way to doing this?
[ "", "java", "oop", "" ]
I would like to spawn a subprocess Java Virtual Machine (through a Java API call) and communicate with it. Maybe I'm just not searching for the right thing on Google, but I keep getting pointed back to Runtime.exec(), which is not what I want. I know I could connect standard input/output and use various serialization techniques, or use remote method invocation, but these seem to cumbersome/heavyweight. It seems like an API call could be more robust than attempting to call Runtime.exec("/usr/bin/java -cp [system.getclasspath] ..."). The purpose / motivation of this is that dynamically reloading classes with many dependencies seems somewhat tricky (several sites mention reading a .class file and passing it to [ClassLoader].defineClass, but this doesn't handle loading of dependent class files well). If I don't need much communication bandwidth or low latency, I think a new JVM instance would work fine; it's that communicating with it seems cumbersome. In any case this question isn't high priority; I'll probably go the straightforward route and see how I can load dependent class files (e.g. ones for inner classes).
As long as the classes you want to load are in a JAR file or a directory tree separate from your main app, using an URLClassLoader and running them in a separate Thread works fine. AFAIK all Java app servers work like this, so it's definitely a proven technique.
I would definitely recommend taking a look at the class loader mechanism used by the [Tomcat servlet container](http://tomcat.apache.org/svn.html) - they seem to have **exactly** the same class loading problem and seem to have solved it very well.
java newbie question: richer java subprocesses
[ "", "java", "jvm", "" ]
Is there a supported way in Google Analytics to track a campaign without having to use query string parameters. In Analytics you can [tag a link to your site](http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55518) with query string parameters such as `utm_campaign` and `utm_medium` which carry information about the campaign so that they can be tracked. Google actually has an [online tool](http://www.google.com/support/analytics/bin/answer.py?answer=55578&hl=en) to help in the creation of such links. For instance if StackOverflow was advertising on Experts Exchange they may have a link like this : <http://www.stackoverflow.com/?utm_source=expertexchange&utm_medium=banner&utm_campaign=a-better-expert-exchange> For many reasons I don't want these clumsy looking parameters appearing in my URLS : * I want to encourage twittering, and long links discourage this * I dont want people bookmarking them with campaign IDs in * I want people to see a clean URL * I dont want search engines indexing these links. * I want full control about what parameters are sent to google analytics - and not leave it up to my partners to mess up the URLs they access my site with I looked a while ago to try to find a way wherein you could set these parameters. [Google has a page](http://code.google.com/apis/analytics/docs/gaJS/gaJSApiCampaignTracking.html) which at first glance looks like the solution, but actually isn't. That page describes how you can change the names of the query string parameters to something else - for instance to use `src` instead of `utm_source` you would run : ``` pageTracker._setCampSourceKey("src"); ``` I really cannot seem to figure out why they don't make it easy to actually explicitly set the value of the `utm_source` key - and not just set up an alternative parameter name for it. I remember a while back finding someone who had a kind of nasty hack, but I cant even seem to find that now. I seem to recall though that whoever it was took a copy of the analytics code and essentially branched it off and hacked at it. This is not a good solution for me! is there an officially supported way of doing this at all, without some kind of nasty redirects. In a nutshell I want to do something like this (ASP.NET MVC site). Give a partnet a link to my site with a URL like this : ``` http://www.example.com/?cid=2dae88a8-66b1-475d-8a35-2978bd1a158c ``` In the controller for my MVC page I would find out what campaign this GUID related to, and set the model state. Note: this gives me the advantage that i can change the campaign parameters without having to reissue the URL. In the page itself I would then do this: ``` var campaignMedium = <%= ViewData.Model.CampaignMedium %>; var campaignSource = <%= ViewData.Model.CampaignSource %>; var campaignName = <%= ViewData.Model.CampaignName %>; pageTracker._setCampaignData({ utm_source: campaignSource, utm_medium: campaignMedium, utm_campaignName: campaignName }); pageTracker._trackPageview(); ``` **IMPORTANT: This \_setCampaignData method DOES NOT ACTUALLY EXIST. This is just 'pseudo code' for what I'd ideally like to be able to do.** Has anyone successfully managed to do anything like this?
The [solution using push(['\_set', 'campaignParams',...](https://stackoverflow.com/a/4082585/5118762) seems only to work for the [legacy library ga.js](https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCampaigns?hl=de). Using analytics.js you need to specify the campaign param separately. E.g. ``` ga('set', 'campaignName', 'TheCampaignName...'); ga('set', 'campaignSource', 'someCampaignSource'); ga('set', 'campaignMedium', 'email'); ``` <https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#campaignName>
## \_set campaignParams Your theoretical "\_setCampaignData" finally exists, in the form of `["_set","campaignParams",...]` If you have a way to programmatically inject the values you'd like to set (for example, set by a cookie on a redirect, or on the server side and printed onto the page), you can use the `_set` API to hard-code the campaign params that you'd like to set. The format for that is just: ``` _gaq.push(['_set', 'campaignParams', 'utm_campaign=CAMPAIGN&utm_source=SOURCE&utm_medium=MEDIUM']); ``` So, using your original example: ``` var campaignMedium = <%= ViewData.Model.CampaignMedium %>; var campaignSource = <%= ViewData.Model.CampaignSource %>; var campaignName = <%= ViewData.Model.CampaignName %>; _gaq.push(['_set', 'campaignParams', 'utm_campaign=' + campaignName + '&utm_source=' + campaignSource +'&utm_medium=' + campaignMedium]); ``` ## Update 2017 [This answer](https://stackoverflow.com/a/35624890/172322) details how to accomplish this with the newer Google Analytics library, analytics.js/Universal Analytics.
Track campaigns with Google Analytics without query string parameters?
[ "", "javascript", "google-analytics", "" ]
I have a model MyModel which contains a PK - locid, that is an AutoField. I want to construct a model formset from this, with some caveats: * The queryset for the formset should be a custom one (say, order\_by('field')) rather than all() * Since locid for MyModel is an AutoField and thus hidden by default, I want to be able to show it to the user. I'm not sure how to do this. I've tried multiple approaches, ``` MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof')) ``` The above gives me the 3 fields, but locid is hidden. ``` class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.fields['locid'].widget.attrs["type"] = 'visible' locid = forms.IntegerField(min_value = 1, required=True) class Meta: model = MyModel fields = ('locid', 'name', 'dupof') ``` The above gives me a ManyToMany error. Has anyone done something like this before? --- Edit **2** I can now use a custom query when I instantiate the formset - but I still need to show the locid field to the user, because the id is important for the application's use. How would I do this? *Is there a way to override the default behavior of hiding a PK if its an autofield?*
I ended up using a template side variable to do this, as I mentioned here: [How to show hidden autofield in django formset](https://stackoverflow.com/questions/896153/how-to-show-hidden-autofield-in-django-formset)
It makes no sense to show an autofield to the user, as it's an autoincremented primary key -- the user can not change it and it will not be available before saving the record to the database (where the DBMS selectes the next available id). This is how you set a custom queryset for a formset: ``` from django.forms.models import BaseModelFormSet class OrderedFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): self.queryset = MyModel.objects.order_by("field") super(OrderedFormSet, self).__init__(*args, **kwargs) ``` and then you use that formset in the factory function: ``` MyModelFormSet = modelformset_factory(MyModel, formset=OrderedFormSet) ```
Creating modelformset from a modelform
[ "", "python", "django", "formset", "modelform", "" ]
I have a simple form for shipping options and I am using javascript to auto submit the form when someone selects a new option from the drop down list. In order to support browsers without javascript there is also a button to submit the form. This button is hidden using javascript. However, this means my button is visible for a brief period of time and can cause a flicker as the rest of the content is reformatted. Can anyone suggest a way of creating the button so it starts off hidden, but is made visible only if javascript is not available? eg, start out with display:none; and magically change to display:block; if and only if there is no javascript.
Just put anything inside `<noscript> ... </noscript>` tags and then it will only appear if JavaScript is not enabled/available.
It depends on how you are hiding it, are you using a DOM ready or a window ready? Window ready waits for all images to download, which is generally far too long. For accessibility, reasons, I'd hide it on DOM loaded. But to ensure it won't show up, you could put it in a noscript element ``` <noscript> <input type="submit" /> </noscript> ``` As for your last paragraph, nothing like that can happen in the absence of JavaScript.
How do I show content when Javascript isn't available, hide it when javascript is available and not flicker in either case?
[ "", "javascript", "html", "css", "progressive-enhancement", "graceful-degradation", "" ]
Some methods like string.Format() or .Parse() require an IFormatProvider. How do you provide it? * In closed environment application (where you know that localization will never be required), do you just skip it and call the methods without the IFormatProvider? * In applications that might get localized, do you think about the correct value for every method call and just set it right there? That would be probably 'CultureInfo.CurrentCulture' or 'CultureInfo.CurrentUiCulture'. * Or do you use global variables like 'MyUiCultureInfo' and 'MyCultureInfo' to be able to switch the localization by changing their values? How and where do you store these variables? * Is there anything to consider when I develop libraries or frameworks - how to handle localization in this case?
I'm always setting CurrentThread.Current(Ui)Culture to the correct value in our (ASP.NET) applications. This is usually done at the begin of each request, based on the user's preferences or a default value stored in a config file (if the user has not defined a preference). After setting these properties of the current thread, you can stop thinking about it - numbers, dates, etc. will be correctly formatted/parsed, even when no IFormatProvider is provided to these methods. Otherwise, you have to ensure that the correct IFormatProvider is passed everywhere. I the case of a library, I think it should just rely on the application for these things and should not have to worry about these things.
I set the current culture to US english because in my country few 'intelligent' persons decided that decimal separator is comma. Sometimes decimal number is with ',' and sometimes with '.'. Not all computers have regional settings configured correctly and **you shouldn't rely on that**. To set that application-wide settings: ``` Application.CurrentCulture = new CultureInfo("en-US"); Application.CurrentCulture.NumberFormat.NumberDecimalSeparator = "."; ```
How do you handle localization / CultureInfo
[ "", "c#", "localization", "" ]
``` private static Callback callback; public Foo() { super(getCallback()); } private static Callback getCallback() { callback = new Callback(); return callback; } ``` Constructor Foo() can potentially be called from multiple threads. My concern is with the private static field 'callback' and the static method 'getCallback()'. As can be seen, every time 'getCallback()' is called, it assigns a new value to static field 'callback'. My *guess* is that it is not thread safe because the keyword *static* is always attached to the class not the instance, so that means, the static field 'callback' of a Foo can potentially be overwritten by other thread that is constructing another Foo(). Is this correct? Please correct me if I am wrong. Thanks! EDIT: My intention is to keep 'callback' somewhere in the class, so I can reuse it later on. But this is not easy because Foo extends from a class that has constructor mandating 'callback' to be passed on.
Yes, you are correct. It's possible for two instances of `Foo` to end up with the same `CallBack` instance when two threads enter the `getCallback()` method simultaneously and one assigns a new `CallBack` to the static field while the other has already done this but not yet returned. In this case, the best fix is not to have the static field, since it serves no purpose. Alternatively, make `getCallback()` synchronized. But note that it's *not* true that only the `static` keyword results in code that is not threadsafe.
It's not thread-safe. Try these alternatives: Option 1: here all instances share the same callback ``` private static final Callback callback = new Callback(); public Foo() { super(callback); } ``` Option 2: here each instance has its own callback ``` public Foo() { super(new Callback()); } ``` Note that in both cases, although the constructor is thread-safe, the thread-safety of the entire class depends on the implementation of Callback. If it has mutable state, then you'll have potential problems. If Callback is immutable, then you have thread-safety.
Help reviewing the following code, is it thread safe?
[ "", "java", "multithreading", "static-methods", "" ]
I am using LINQ to SQL with stored procedures in SQL Server 2008. Everything work well except one problem. L2S cannot generate the method for the stored procedure with user defined table type as parameter. Method signature in dbml design panel use object for parameter type instead of table type and when I tried to compile I got error: ``` Error: DBML1005: Mapping between DbType 'Structured' and Type 'System.Object' in Parameter 'ParaName' of Function 'dbo.StoredProcName' is not supported. ``` Is there a way to work around this of this problem? I don't want to go back to traditional ADO.NET data access.
I don't think there's anything available right now - table-valued parameters were introduced in SQL Server 2008 - after LINQ and LINQ2SQL were out already. I haven't found any mention in any of the blog post about support for table-valued parameters in LINQ2SQL in .NET 4.0 so far. **UPDATE:** Here's a [blog post by Damien Guard](http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40) on the fixes and improvement for Linq-to-SQL in the .NET 4.0 time frame. **UPDATE 2:** Unfortunately, according to Damien, this feature isn't supported in .NET 3.5, and will not be supported in .NET 4.0 either :-( *Can't be done in 3.5 or 4.0 right now :( [)amien*
I happened upon this [post](http://blog.mikecouturier.com/2010/01/sql-2008-tvp-table-valued-parameters.html) that provides a means of calling stored procedures with TVP parameters from Linq2Sql. It's a round about method that basically creates a partial class extension of your dataContext and passes a dataTable using an SqlCommand. I hope it helps.
LINQ to SQL with stored procedures and user defined table type parameter
[ "", "c#", "linq-to-sql", "stored-procedures", "" ]
Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to an object, file, and VM environment. I could create another "poor man’s" reflection system or hopefully something better that I haven't thought of yet. Does anyone have any thoughts? EDIT: I know C++ doesn't have reflection. ``` union variant_t { unsigned int ui; int i; double d; char* s; }; struct pub_values_t { const char* name; union variant_t* addr; char type; // 'I' is int; 'U' is unsigned int; 'D' is double; 'S' is string }; #define pub_v(n,t) #n,(union variant_t*)&n,t struct pub_values_t pub_values[] = { pub_v(somemember, 'D'), pub_v(somemember2, 'D'), pub_v(somemember3, 'U'), ... }; const int no_of_pub_vs = sizeof(pub_values) / sizeof(struct pub_values_t); ```
To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default). If you have control over your data structure, you could try a `std::vector<boost::any>` or a `std::map<std::string, boost::any>` then add all your member variables to the vector/map. Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.
You can specify your types in an intermediate file and generate C++ code from that, something like COM classes can be generated from idl files. The generated code provides reflection capabilities for those types. I've done something similar two different ways for different projects: * a custom file parsed by a Ruby script to do the generation * define the types as C# types, use C#'s reflection to get all the information and generate C++ from this (sounds convoluted, but works surprisingly well, and writing the type definitions is quite similar to writing C++ definitions)
Enumerate members of a structure?
[ "", "c++", "c", "enumeration", "" ]
When building a Windows Console App in C#, is it possible to write to the console without having to extend a current line or go to a new line? For example, if I want to show a percentage representing how close a process is to completion, I'd just like to update the value on the same line as the cursor, and not have to put each percentage on a new line. Can this be done with a "standard" C# console app?
If you print only `"\r"` to the console the cursor goes back to the beginning of the current line and then you can rewrite it. This should do the trick: ``` for(int i = 0; i < 100; ++i) { Console.Write("\r{0}% ", i); } ``` Notice the few spaces after the number to make sure that whatever was there before is erased. Also notice the use of `Write()` instead of `WriteLine()` since you don't want to add an "\n" at the end of the line.
You can use `Console.SetCursorPosition` to set the position of the cursor and then write at the current position. Here is an [example](https://learn.microsoft.com/en-gb/archive/blogs/brada/showing-progress-in-a-console-windows) showing a simple "spinner": ``` static void Main(string[] args) { var spin = new ConsoleSpinner(); Console.Write("Working...."); while (true) { spin.Turn(); } } public class ConsoleSpinner { int counter; public void Turn() { counter++; switch (counter % 4) { case 0: Console.Write("/"); counter = 0; break; case 1: Console.Write("-"); break; case 2: Console.Write("\\"); break; case 3: Console.Write("|"); break; } Thread.Sleep(100); Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); } } ``` Note that you will have to make sure to overwrite any existing output with new output or blanks. Update: As it has been criticized that the example moves the cursor only back by one character, I will add this for clarification: Using `SetCursorPosition` you may set the cursor to any position in the console window. ``` Console.SetCursorPosition(0, Console.CursorTop); ``` will set the cursor to the beginning of the current line (or you can use `Console.CursorLeft = 0` directly).
How can I update the current line in a C# Windows Console App?
[ "", "c#", "windows", "console", "" ]
As part of a data regression and quality assurance exercise, I need to look for diffs between two tables that should, ideally, be nearly identical. I have looked at a large number of commercial products and can't seem to find one that satisfies all of our requirements: * Must be able to compare LARGE tables (10 million rows, by 200 columns) very efficiently * Must work across different DB servers and different DB vendors (Oracle vs. DB2) * Must be able to compare tables having different structures, ignoring the columns that are not shared between the two tables * Must work with a user supplied, multi-column primary key-- can't rely on key defined in DB * Must run on linux/solaris. Will be run as part of a fully automated process that is executed within an enterprise environment. * Must be able to run headless (wihtout GUI) * Must produce formatted report that identifies row diffs (row on only one side) and value diffs * Customer is willing to pay enterprise level price for right solution. In other words, price no object. Has anyone ever seen something like this?
Not the best solutions but for flexibility, we have implemented this as a set of perl scripts that extract the data and then do file comparison. Most commercial databases have excellent bulk copy utility (bcp, sqlload etc.) and Perl is fast with string comparison and for proecessing large files.
I'd hash the DB rows based on your defined criteria and then use that. If the comparison details are fairly static you may want to persist the hash, either as a new column in the table itself or in a separate dedicated table. An appropriate index would then allow you to perform whatever comparisons you wish.
compare data in 2 SQL tables
[ "", "sql", "database", "" ]
The scenario I have, is in the Execute method of a SPJobDefinition I want to go through every SPSite in the web application. So I have the following code: ``` foreach (SPSite site in this.WebApplication.Sites) { ... } ``` Question is, do I need to dispose of each site? The rule I normally go by is dispose or put inside a using only if I new it up myself. Will that Sites property actually contain fully constructed site objects to begin with which I'll only have a reference to in this code. If so then disposing the sites would be dangerous as I'm modifying another object that might want them. Or the opposite is does the Sites property construct the objects on request.. in which case is it my responcibility to dispose of them? Plus how do I dispose them if I do need to do that. I can't use a using in this case, and will calling a dispose inside the foreach break the enumeration?
Yes you do. See "Writing Applications That Scale to Large Numbers of Users" in [Best Practices: Common Coding Issues When Using the SharePoint Object Model](http://msdn.microsoft.com/en-us/library/bb687949.aspx#WSS3CodingSharePointOM_CodeNotWrittentobeScalable). The correct pattern is: ``` foreach (SPSite site in this.WebApplication.Sites) { try { ... } finally { site.Dispose(); } } ``` Calling dispose will not break the enumeration. It just cleans up the unmanaged memory used by the object.
The guidance here <http://www.sharepointdevwiki.com/display/public/When+to+Dispose+SharePoint+objects> suggests that ``` //loop through each sub site for (int i = 0; i <= rootweb.Webs.Count; i++) { using (SPWeb subweb = rootweb.Webs[i]) { //do stuff } } ``` is the prefered solution to this problem. There is also a tool you can run over your solution to check you are doing things right. <http://code.msdn.microsoft.com/SPDisposeCheck>
SharePoint SPSite Disposing
[ "", "c#", "sharepoint", "dispose", "spsite", "" ]
Does anyone want a framework/class which allows me to clone by values .Net objects? I'm only interested with public read/write properties (namely DataContracts), and I don't care if references are resolved correctly (i.e. collecions which contains the same instance of item twice). I tried serialization trick via `DataContractSerializer` (serialize to XML and back), wrote reflection-based cloning class (sometimes faster/sometimes slower), and was wondering if someone wrote a helper class which can do this via Emit and not reflection. As for now emitting IL is a little to much for my little brain, but I guess this would be the ultimate solution. Unless someone knows an alternative method which is faster than DataContractSerializer.
If you are talking about an object tree/graph: Writing specific IL to serialize an object is tricky. IMO, your best bet is to look at a full serialization, like how `DataContractSerializer` would work - but not necessarily with that engine. For example, [protobuf-net](http://code.google.com/p/protobuf-net/) has a `Serializer.DeepClone<T>` method that might help. It should be faster than `DataContractSerializer`, at least. At the current time, you need to add some clues for the serializer (even if just `[ProtoContract(ImplicitFields=ImplicitFields.AllPublic)]`) - however, the current (incomplete) work-in-progress offers POCO support without attributes. --- If you are talking about individual objects: There are fairly simple things you can do here with `Expression` in .NET 3.5; build a dynamic `Expression` based on reflection, and call `.Compile()`. [MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/) has this already: ``` DestType clone = PropertyCopy<DestType>.CopyFrom(original); ``` With .NET 2.0/3.0 (without `Expression`) you might consider [HyperDescriptor](http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx) for similar purposes.
I have written three deep clone methods for .NET some time ago: * One uses the well-known `BinaryFormatter` technique (though I tweaked it so that objects do not need to be serializable in order to be cloned). This was by far the slowest. * For the second I used pure reflection. It was at least 6 times faster than cloning with the `BinaryFormatter`. This one could also be used on Silverlight and the .NET Compact Framework. * The third one uses Linq Expression Trees (for runtime MSIL generation). It is 60 times faster than the `BinaryFormatter` technique but has a setup time of approximately 2 milliseconds for the first time each class is encountered. ![Logarithmic scale illustrating cloning performance](https://i.stack.imgur.com/VhMyo.png) The horizontal axis shows the number of objects cloned (though each cloned object includes several nested objects). The `BinaryFormatter` is labeled "Serialization" in the chart. The data series "Reflection" is a custom one that copies fields via `GetField()`/`SetField()`. I published all three cloning methods as Open Source here: <http://blog.nuclex-games.com/mono-dotnet/fast-deep-cloning/>
Faster deep cloning
[ "", "c#", ".net", "" ]
Is it possible to make a method that will take anything, including objects, Integers etc? I have a method checking the value if it is null and I was thinking perhaps it could be done with generics instead of overloading. Unfortunately, trying ``` nullChecking(Class<? extends Object> value){ ... } ``` won't allow Integers as they extend Number not object. Is there a way? Cheers
Can't you just do `nullChecking(Object value)` ? If you just wanna test if it's null, it will work.
I'm not sure what you are trying to do... If it's just checking if a object is `null` then you can simply do this: ``` public static boolean nullChecking(Object obj) { return obj == null; } ```
Java generics
[ "", "java", "generics", "" ]
In C#, how do I query a remote server for its current time? Similar functionality to ``` net time \\servername ``` but returning a datestamp that includes seconds. Thanks
Windows Time Service implements NTP. Here is a [C# implementation of an NTP client](http://dotnet-snippets.com/dns/c-simple-network-time-ntp-protocol-client-SID571.aspx). A Windows GUI using it can be found at [Simple Network Time Protocol Client](http://www.bocan.ro/sntpclient). It's by Valer Bocan.
You can use the [NetRemoteTOD](http://msdn.microsoft.com/en-us/library/aa370612(VS.85).aspx) function. An example from <http://bytes.com/groups/net-c/246234-netremotetod-usage>: ``` // The pointer. IntPtr pintBuffer = IntPtr.Zero; // Get the time of day. int pintError = NetRemoteTOD(@"\\sony_laptop", ref pintBuffer); // Get the structure. TIME_OF_DAY_INFO pobjInfo = (TIME_OF_DAY_INFO) Marshal.PtrToStructure(pintBuffer, typeof(TIME_OF_DAY_INFO)); // Free the buffer. NetApiBufferFree(pintBuffer); ```
Get the exact time for a remote server
[ "", "c#", ".net", "time", "" ]
First, my question is not about password hashing, but password encryption. I'm building a desktop application that needs to authentificate the user to a third party service. To speed up the login process, I want to give the user the option to save his credentials. Since I need the password to authentificate him to the service, it can't be hashed. I thought of using the pyCrypto module and its Blowfish or AES implementation to encrypt the credentials. The problem is where to store the key. I know some applications store the key directly in the source code, but since I am coding an open source application, this doesn't seem like a very efficient solution. So I was wondering how, on Linux, you would implement user specific or system specific keys to increase password storing security. If you have a better solution to this problem than using pyCrypto and system/user specific keys, don't hesitate to share it. As I said before, hashing is not a solution and I know password encryption is vulnerable, but I want to give the option to the user. Using Gnome-Keyring is not an option either, since a lot of people (including myself) don't use it.
Encrypting the passwords doesn't really buy you a whole lot more protection than storing in plaintext. Anyone capable of accessing the database probably also has full access to your webserver machines. However, if the loss of security is acceptable, and you really need this, I'd generate a new keyfile (from a good source of random data) as part of the installation process and use this. Obviously store this key as securely as possible (locked down file permissions etc). Using a single key embedded in the source is not a good idea - there's no reason why seperate installations should have the same keys.
Try using [PAM](http://www.kernel.org/pub/linux/libs/pam/). You can make a module that automatically un-encrypts the key when the user logs in. This is internally how GNOME-Keyring works (if possible). You can even write PAM modules in Python with [pam\_python](http://ace-host.stuart.id.au/russell/files/pam_python/).
How To Reversibly Store Password With Python On Linux?
[ "", "python", "linux", "encryption", "passwords", "" ]
I'm trying to compare a time stamp from an incoming request to a database stored value. SQL Server of course keeps some precision of milliseconds on the time, and when read into a .NET DateTime, it includes those milliseconds. The incoming request to the system, however, does not offer that precision, so I need to simply drop the milliseconds. I feel like I'm missing something obvious, but I haven't found an elegant way to do it (C#).
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined). ``` DateTime dateTime = ... anything ... dateTime = new DateTime( dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond), dateTime.Kind ); ``` or the equivalent and shorter: ``` dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond)); ``` This could be generalized into an extension method: ``` public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan) { if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException // Some comments suggest removing the following line. I think the check // for MaxValue makes sense - it's often used to represent an indefinite expiry date. // (The check for DateTime.MinValue has no effect, because DateTime.MinValue % timeSpan // is equal to DateTime.MinValue for any non-zero value of timeSpan. But I think // leaving the check in place makes the intent clearer). // YMMV and the fact that different people have different expectations is probably // part of the reason such a method doesn't exist in the Framework. if (dateTime == DateTime.MinValue || DateTime.MaxValue) return dateTime; // do not modify "guard" values return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks)); } ``` which is used as follows: ``` dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute ... ```
``` var date = DateTime.Now; date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind); ```
How to truncate milliseconds off of a .NET DateTime
[ "", "c#", ".net", "datetime", "" ]
I'm experimenting some difficulties trying to use [**Connection String Builders (ADO.NET)**](http://msdn.microsoft.com/en-us/library/ms254947.aspx) within LINQ to SQL. Let me show you guys what I'm trying to do: > the **app.config** file: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <connectionStrings> <add name="LoremIpsum" connectionString="Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> ``` > and a snippet of the form: ``` ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"]; if (null != settings) { string connection = settings.ConnectionString; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connection); // passwordTextBox being the control where joe the user actually // enters his credentials builder.Password = passwordTextBox.Text; } LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(); // finally some rather anecdotic LINQ sentence here: var foo = db.Table.Single(bar => bar.Table == whatever); ``` > On the other hand checking the **Immediate Window**: ``` ?builder.ConnectionString "Data Source=SomeServer;Initial Catalog=SomeDB;User ID=joe;Password=swordfish" ``` I'm always getting an exception: Login failed for user 'joe'. Any ideas? Thanks much in advance.
It seems like you are trying to modify the connection string that is stored in the app.config file. When you use a no argument constructor for your data context, it reads what was configured at design time. Try injecting your modified connection string into the constructor of the DataContext: ``` ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"]; SqlConnectionStringBuilder builder; LINQTOSQLDataClassDataContext db; if (null != settings) { string connection = settings.ConnectionString; builder = new SqlConnectionStringBuilder(connection); // passwordTextBox being the control where joe the user actually enters his credentials builder.Password =passwordTextBox.Text; db = new LINQTOSQLDataClassDataContext(builder.ConnectionString); } } ```
You're forgetting to send in the connectionstring to the DataContext constructor. Example: ``` LINQTOSQLDataClassDataContext db = new LINQTOSQLDataClassDataContext(builder.ConnectionString); ```
How can I make LINQ to SQL use a connection string which is being modified at runtime?
[ "", "c#", "sql-server", "linq-to-sql", "ado.net", "app-config", "" ]
Has anyone done something like this? How? I'm just starting a project that will have a browser based web application (using PHP and possibly an Ajax framework like Dojo or JQuery) that is presented to the user from within a kiosk unit. It's basically a survey in a browser but will need to id the user via the id card swipe reader on the unit. I don't even know what exact unit this is (sorry for lack of h/w information!) as I have just learned about the project yesterday. I'm waiting to see if the unit came with some sort of software to help me out, but my sense is not from the initial meeting I had. They will be initially running some flavor of Windows though they may decide to switch to Linux later. I have no experience with kiosks so I'm just trying to get a sense of what is usually involved for this sort of thing. The main question is how to get the data input from the kiosk hardware into the web based PHP application? When speaking with the project lead, his first guess on how to tackle this was: - Have some sort of driver that picks up the data input to the id reader. - Write to file. - Use Dojo Offline to read file periodically or when needed and compare a timestamp, etc. Not yet concerned with tackling security implications. First I just want to figure out the basics of how to get this going. I can see how the same could possibly be done with Flex/Air, Silverlight, etc., but we are a PHP shop and frankly, my boss would not consider those. Also, using a database, sockets, etc., seems like it may be overkill (but maybe not???) Any suggestions, warnings, etc.? Thanks.
The hardware you are working with should come with the information you need to be able to retrieve data from it.
Without either software or documentation for the unit you are going to be hard pressed to get anything useful from the data it sends. If you don't have either then you should identify the manufacturer (web search for serial numbers, id numbers or anything else on the hardware) and ask them for these.
How to access kiosk id reader data from PHP based Web Application
[ "", "php", "dojo", "kiosk", "" ]
I have a PHP script that needs to process the same site's RSS feed. Specifically, I'm displaying the most recent blogs from the WordPress RSS feed on the home page. On our staging server it worked fine but on our live (which is a completely different, but LAMP) hosting environment it's not working. I can run `file_get_contents` or `curl` on a remote url fine, but when I try to retrieve our own RSS feed, I am returned a 404 not found page. One other oddity, if I try `file_get_contents(http://domain.com/test.txt)` it fails with a 404 but if I do `file_get_contents(http://www.domain.com/test.txt)` I get the contents of the test text file. This is all assuming I'm running the script from domain.com (not www.domain.com) I've setup an example here: <http://bkwld.com/test.php>
Ok, I still don't know why the hell it's doing this, but I'm going to solve it by running my feed through feedburner and then parsing it's RSS feed. Because it's on a remote domain, it works in my tests. Not ideal, but w/e.
I just had this similar issue. The DNS is the problem, it is not resolving your domain name. You should use the IP instead of the domain in your scripts. You can ping your domain in cmd and use that IP.
Using file_get_contents or curl to url on same server
[ "", "php", "rss", "curl", "file-get-contents", "" ]
I have an application that loads dlls dynamically. The application and the dlls use a Functions.dll that can be a diferent version for the application an for each dll, but in execution the application and the dlls all use the same dll version (the one used by the EXE) and share the static variables... How can i force them to use their own Functions.dll(n-version)? -Details: * I tried loading the dlls by "Assembly dll = Assembly.LoadFile(" and by "Assembly dll=domaindll.Load(" * In Functions.dll, al the methods and objects are Static * I use Functions.dll "statically" by referencing it throught VS in all cases not dynamically * The dlls and Functions.dll are developed in C# too -Folder Estructure: Application: ``` Application.EXE Functions.dll(version 1.2) DLLS: EXAMPLEDLL1: EXAMPLEDLL1.DLL Functions.dll(version 1.1) EXAMPLEDLL2: EXAMPLEDLL2.DLL Functions.dll(version 1.0) EXAMPLEDLL3: EXAMPLEDLL3.DLL Functions.dll(version 1.2) ```
You can enforce binding to a specific version of a DLL by strong-signing it. You can also try setting "Specific Version" to true on the reference properties, but as far as I'm aware that only affects compile-time binding and a different version can be loaded at runtime if the assembly isn't strong-signed. This should get you started: [Strong-Name Signing for Managed Applications](http://msdn.microsoft.com/en-us/library/h4fa028b.aspx) Be aware, though, that any types declared in this dll will not be type-equivalent to the same type in a different version of the assembly. For instance, if I declare a class called `Foo` in `Functions.dll`, then an instance of `Foo` from version 1.0 won't be the same type as an instance of `Foo` from version 1.1. As far as the CLR is concerned, these are completely different types. If all you have are static functions in the assembly and no types are defined, then you should be OK. Otherwise you need to look into a different approach.
At the end I solved it renaming the Functions.dll to match the EXAMPLEDLL that uses it....Ex: Application.EXE-->FunctionsApplication.dll EXAMPLEDLL1.dll-->FunctionsEXAMPLEDLL1.dll Thanks for the answers anyway.. Postdata: In another case where I could sign correctly the dlls i think Adam Robinson answer would be the correct one(and jerryjvl the second anwser).
C# Dynamic dll system problem
[ "", "c#", "dll", "dynamic", "assemblies", "load", "" ]
Be forewarned: This question seems way more obvious than it actually is. I'd like to write a template that can accept any concrete class or template class as a template parameter. This might seem useless because without knowing whether the passed in T is templated or not you won't know how to use it. The reason I want this is so that I can declare a general template with no definition, that users then specialize. Because users are specializing it, they always know about the type they're dealing with. But users can't specialize a template without it first being declared. You could do this: ``` template<class T> class myclass; ``` But that won't work if you pass in a templated T, for example `myclass<std::vector>` won't work. So then we try this: ``` template<class T> class myclass; template<template<class> T> class myclass; ``` This might be the right track, but it won't work as is because class templates can't be overloaded. So let's switch it to function templates, which can be: ``` template<class T> void myfunc(); template<template<class> T> void myfunc(); ``` Sweet, so we're done right? Well, there might be different numbers of parameters given to the template template parameter, so we'll need to take that into account too. ``` template<class T> void myfunc(); template<template<class> T> void myfunc(); template<template<class, class> T> void myfunc(); template<template<class, class, class> T> void myfunc(); // etc. ``` Ugly, but the [Boost Preprocessor Library](http://www.boost.org/doc/libs/1_39_0/libs/preprocessor/doc/index.html) can generate this code for us (and in C++0x support for variadic templates will be added so this ugliness is only temporary). But we've still forgotten a case! What if one of T's parameters isn't a class, but a constant integer. Lets try to support that: ``` template<class T> void myfunc(); template<template<class> T> void myfunc(); template<template<class, class> T> void myfunc(); template<template<class, class, class> T> void myfunc(); // etc. template<template<class> T> void myfunc(); template<template<class, int> T> void myfunc(); template<template<int, class> T> void myfunc(); template<template<int, class, class> T> void myfunc(); template<template<class, int, class> T> void myfunc(); template<template<class, class, int> T> void myfunc(); // etc. ``` Uh oh. Given that any constant type can get passed into a template, in any number, mixed with class parameters, KABLOOEY combinatorial explosion. Just to make things more difficult, what if any of T's parameters are themselves templates?
boost::mpl does something like this (here's their idea of [binding an argument](http://www.boost.org/doc/libs/1_39_0/libs/mpl/doc/refmanual/metafunctions.html)). However, you have to make a lot of assumptions to make it work, like using; ``` template <class T> foo { }; typedef foo< int_<4> > my_foo_4; ``` instead of ``` template <int T> foo { }; typedef foo<4> my_foo_4; ``` to not have to offer overloads for all int, char, bool, etc combination. I can't think of anything that would be more effective than the boost::mpl approach, and in general, I would think any approach would suffer a lot of problems; a class template is NOT a type, and it can't really be wedged into the type system that way (boost::mpl treats it as a function to create new types; more generically, it is used to create a "MetaFunction"). I'm not even sure if variadic templates are going to effect template template parameters (interesting question though).
The solution is: use function overloading and not template specialization! Compile time will be better, constraints gone ... Remember that any template is considered instantiated at the closest global scope after which they are used. This mean that this will work: ``` template <class T> int f(const T& t) { return g(t); } int g(int a) { return a+1; } int main() { return f(5); } ``` As you see, it works even though the function `g` is defined after `f`. This means that you can define whatever template you want that uses the function, as long as the user defines the function before it **uses** the template, you're fine, C++ will find it. Remember also that template specialization doesn't exist for functions! If many functions with the same name exist, C++ will always expect overloading, not template specialization. In short, the best solution is: just use the function as if it existed and expect the users to define the function before they use the template.
How to write a C++ template that accepts every class and class template?
[ "", "c++", "templates", "overloading", "" ]
I know there is a mouse click event for every control but is there a way to determine when the mouse click is not on the control?
you could use [this code](https://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type/978352#978352) to find all controls or target type of visual element on the window and handle it's mouse events.
you can check the IsMouseOver for false, and if you want to hook an action when the IsMouseOver == false, you can override the metadata of that dp.
WPF Mouse Click Off Event
[ "", "c#", "wpf", "mouseevent", "" ]
I would like some suggestions if your project has some java application elements as well as web then is there an option for testing java applications from the outside like we do with the web applications
Do you mean testing desktop applications through the GUI? If so, there are many tools for doing this, both commercial and open source. Some open-source projects to google for: * [Window Licker](http://windowlicker.googlecode.com) (I am an author of this one) * FEST * Marathon * Abbot
Your question is not very clear to me. But from what I understand, I feel jMeter could be something that might help. jMeter can not only test web applications (from outside) but ALSO standalone java applications. Also, do not dismiss jMeter as a performance testing tool. There are ample features in it that makes it a good enough tool for Functional testing as well.
is there an option for testing java applications from the outside like we do with the web applications?
[ "", "java", "automation", "junit", "" ]
I have an array of ushort pixel data (16-bit grayscale values), and I am trying to save it as a jpeg image. However my code is crashing at the Save command with "A generic error occurred in GDI+". I can't figure out how to fix this. The directory I am saving to is created by my application and I write other files to it; so I know it's not a permissions problem. Is it maybe a data corruption problem? Am I doing something wrong in the steps to get the ushort data into the Bitmap object? Because I have **ushort** data I found it took some effort to figure out how to get it into the Bitmap object, and I am possibly doing it wrong. Here is my code: ``` Bitmap img = new Bitmap(width, height, PixelFormat.Format16bppGrayScale); Rectangle rect = new Rectangle(0,0, width, height); BitmapData picData = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat); IntPtr pixelStartAddress = picData.Scan0; WriteableBitmap pic = new WriteableBitmap(width, height, 96.0, 96.0, System.Windows.Media.PixelFormats.Gray16, null); int stride = (thumb.XSize * pic.Format.BitsPerPixel + 7) / 8; pic.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), dataArray, stride, 0); pic.CopyPixels(new System.Windows.Int32Rect(0,0,thumb.XSize, thumb.YSize),pixelStartAddress, dataArray.Length * sizeof(ushort), stride); img.UnlockBits(picData); img.Save(path, ImageFormat.Jpeg); ``` This whole thing has become very frustrating. Please help?!
I'm, afraid it has something to do with the grayscale / JPG. I don't know if JPEG supports grayscales. I would try declaring the bitmap as a normal color one. And testing.
Regarding your comment about image quality (I would have responded as a comment, but it loses the code formatting): You are saving with the default settings for JPEG export. You can create your own EncoderParameters instance with a higher quality setting: ``` var encParams = new EncoderParameters(1); var encParams.Param[0] = new EncoderParameter(Encoder.Quality, 91L); // get jpegEncoder by looping through ImageCodecInfo.GetImageEncoders()) image.Save("path to file", jpegEncoder, encParams); ```
"A generic error occurred in GDI+" when saving Bitmap object as jpeg, c#
[ "", "c#", ".net", "bitmap", "jpeg", "" ]
I'm writing a basic program in python using the PyQt4 module. I'd like to be able to use my system theme's icons for things like the preference dialog's icon, but i have no idea how to do this. So my question is, how do you get the location of an icon, but make sure it changes with the system's icon theme? If it matters, i'm developing this under ubuntu 9.04, so i am using the gnome desktop.
Unfortunately, It appears that Qt does not support getting icons for a specific theme. There are ways to do this for both KDE and Gnome. The KDE way is quite elegant, which makes sense considering that Qt is KDE's toolkit. Instead of using the PyQt4.QtGui class QIcon, you instead use the PyKDE4.kdeui class KIcon. An example of this is: ``` from PyKDE4.kdeui import * icon = KIcon("*The Icon Name*") ``` see the PyKDE documentation for this class, [here](http://api.kde.org/pykde-4.2-api/kdeui/KIcon.html). One way to gain support for this for gnome is to use the python gtk package. It is not as nice as the kde way, but it works none the less. It can be used like this: ``` from PyQt4 import QtGui from gtk import icon_theme_get_default iconTheme = icon_theme_get_default() iconInfo = iconTheme.lookup_icon("*The Icon Name*", *Int of the icon size*, 0) icon = QtGui.QIcon(iconInfo.get_filename()) ``` See the documentation for the [Icon Theme class](http://www.pygtk.org/docs/pygtk/class-gtkicontheme.html) and [Icon Info class](http://www.pygtk.org/docs/pygtk/class-gtkiconinfo.html). EDIT: thanks for the correction CesarB
Use the PyKDE4 KIcon class: <http://api.kde.org/pykde-4.2-api/kdeui/KIcon.html>
System theme icons and PyQt4
[ "", "python", "icons", "pyqt4", "" ]
What is the best way to crop or mask an image into a circular shape, using either ImageMagick or GD libraries? (Note, solution exists on "other" Q&A sites, but not StackOverflow)
Here is one way with ImageMagick that will acomplish this without using a mask: ``` convert -size 200x200 xc:none -fill walter.jpg -draw "circle 100,100 100,1" circle_thumb.png ``` ![walter](https://i.stack.imgur.com/Yu5xU.jpg) ![alt text](https://i.stack.imgur.com/pO6zJ.png)
For those who need to do this in pure **PHP using Imagick**, you will need to refer to this question : [circularize an image with imagick](https://stackoverflow.com/questions/13795535/circularize-an-image-with-imagick/20347987#20347987) Hope this will help. J.
Crop or mask an image into a circle
[ "", "php", "gd", "imagemagick", "" ]
I'm trying to define a many-to-one field in the class that is the "Many". For example, imagine a situation where a user can only be a member of one group but a group can have many users: ``` class User(models.Model): name = models.CharField() class Group(models.Model): name = models.CharField() # This is what I want to do -> users = models.ManyToOneField(User) ``` Django docs will tell to define a group field in the User model as a ForeignKey, but I need to define the relationship in the Group model. As far as I know, there isn't a ManyToOneField and I would rather not have to use a ManyToManyField.
A `ManyToOne` field, as you've guessed, is called `ForeignKey` in Django. You will have to define it on your `User` class for the logic to work properly, but Django will make a reverse property available on the `Groups` model automatically: ``` class Group(models.Model): name = models.CharField(max_length=64) class User(models.Model): name = models.CharField(max_length=64) group = models.ForeignKey(Group) g = Group.objects.get(id=1) print g.user_set.all() # prints list of all users in the group ``` Remember that Django's models sit on top of a relational database... there's no way to define a single FK field in a table that points to more than one foreign key (without a M2M, that is), so putting the ManyToOne relationship on the Groups object doesn't map to the underlying data store. If you were writing raw SQL, you'd model this relationship with a foreign key from the user table to the group table in any event, if it helps to think of it that way. The syntax and logic of using a `ManyToOne` property that is defined on a Group instance, if such a concept existed, would be much less straightforward than the ForeignKey defined on User.
Assuming that the Users construct is the built-in authentication system... I would recommend creating a Profile model of some sort and attaching the OneToMany field to it instead. You can then [hook the Profile model to the user model](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users).
ManyToOneField in Django
[ "", "python", "django", "" ]
Mac OS X development is a fairly new animal for me, and I'm in the process of porting over some software. For software licensing and registration I need to be able to generate some kind of hardware ID. It doesn't have to be anything fancy; Ethernet MAC address, hard drive serial, CPU serial, something like that. I've got it covered on Windows, but I haven't a clue on Mac. Any idea of what I need to do, or where I can go for information on this would be great! Edit: For anybody else that is interested in this, this is the code I ended up using with Qt's QProcess class: ``` QProcess proc; QStringList args; args << "-c" << "ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { print $3; }'"; proc.start( "/bin/bash", args ); proc.waitForFinished(); QString uID = proc.readAll(); ``` Note: I'm using C++.
Try this Terminal command: ``` ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { split($0, line, "\""); printf("%s\n", line[4]); }' ``` From [here](http://www.jaharmi.com/2008/03/15/get_uuid_for_mac_with_ioreg) Here is that command wrapped in Cocoa (which could probably be made a bit cleaner): ``` NSArray * args = [NSArray arrayWithObjects:@"-rd1", @"-c", @"IOPlatformExpertDevice", @"|", @"grep", @"model", nil]; NSTask * task = [NSTask new]; [task setLaunchPath:@"/usr/sbin/ioreg"]; [task setArguments:args]; NSPipe * pipe = [NSPipe new]; [task setStandardOutput:pipe]; [task launch]; NSArray * args2 = [NSArray arrayWithObjects:@"/IOPlatformUUID/ { split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }", nil]; NSTask * task2 = [NSTask new]; [task2 setLaunchPath:@"/usr/bin/awk"]; [task2 setArguments:args2]; NSPipe * pipe2 = [NSPipe new]; [task2 setStandardInput:pipe]; [task2 setStandardOutput:pipe2]; NSFileHandle * fileHandle2 = [pipe2 fileHandleForReading]; [task2 launch]; NSData * data = [fileHandle2 readDataToEndOfFile]; NSString * uuid = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; ```
For C/C++: ``` #include <IOKit/IOKitLib.h> void get_platform_uuid(char * buf, int bufSize) { io_registry_entry_t ioRegistryRoot = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/"); CFStringRef uuidCf = (CFStringRef) IORegistryEntryCreateCFProperty(ioRegistryRoot, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0); IOObjectRelease(ioRegistryRoot); CFStringGetCString(uuidCf, buf, bufSize, kCFStringEncodingMacRoman); CFRelease(uuidCf); } ```
Unique hardware ID in Mac OS X
[ "", "c++", "macos", "unique", "hardware-id", "" ]
I'm really confused with the `codecs.open function`. When I do: ``` file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() ``` It gives me the error > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position > 0: ordinal not in range(128) If I do: ``` file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() ``` It works fine. **Question** is why does the first method fail? And how do I insert the bom? If the second method is the correct way of doing it, what the point of using `codecs.open(filename, "w", "utf-8")`?
I believe the problem is that [`codecs.BOM_UTF8`](https://docs.python.org/library/codecs.html#codecs.BOM_UTF8) is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!" Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8: ``` import codecs file = codecs.open("lol", "w", "utf-8") file.write(u'\ufeff') file.close() ``` (That seems to give the right answer - a file with bytes EF BB BF.) EDIT: S. Lott's [suggestion](https://stackoverflow.com/a/934203/12892) of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.
Read the following: <http://docs.python.org/library/codecs.html#module-encodings.utf_8_sig> Do this ``` with codecs.open("test_output", "w", "utf-8-sig") as temp: temp.write("hi mom\n") temp.write(u"This has ♭") ``` The resulting file is UTF-8 with the expected BOM.
Write to UTF-8 file in Python
[ "", "python", "utf-8", "character-encoding", "byte-order-mark", "" ]
I would like to get a second opinion on how to handle Exceptions within "events" (key input, screen update etc). In this case I have control over the event-sender. So a module is set to handle an event (it implements a listener interface, and is registered against an event sender): ``` public void DefaultSet ( CardData oldDefault, CardData newDefault ) { } ``` The event sender is simply: ``` for ( Enumeration e = listeners.elements(); e.hasMoreElements(); ) { RetrieverListener thisListener = (RetrieverListener) e.nextElement(); thisListener.DefaultSet( oldDefault, newDefault ); } ``` So if/when something goes wrong in the receiver: * Should I try to cope with the exception there, and never throw anything back to the sender? Sometimes the listeners don't have the "context" to handle an error correctly, is that right? * Is it frowned on to throw an exception back to an event-sending module, to be handled in a documented way? e.g. "Throwing an IOException will result in a reset.. ". This seems non-standard from the javadocs I have read. * Should I just log and ignore the exception when something goes wrong & nothing can be done about it?
The Java convention is that listener methods do not throw exceptions. Obviously, programming errors might make a listener throw a RuntimeException, but there's no way the event source can recover from that because it will have left the program's objects in some unknown, maybe inconsistent state. It is therefore up to the listener to catch checked exceptions and either recover from them (roll back a transaction, for example) or report them to some other object. I often use an ErrorHandler interface that looks something like: ``` public interface ErrorHandler { public void errorOccurred(String whatIWasTryingToDo, Exception failure); } ``` An event listener tells its ErrorHandler about errors that have occurred. ``` public class SomeClass implements SomeKindOfListener private final ErrorHandler errorHandler; ... other fields ... public SomeClass(ErrorHandler errorHandler, ... other parameters ... ) { this.errorHandler = errorHandler; ... } public void listenerCallback(SomeEvent e) { try { ... do something that might fail ... } catch (SomeKindOfException e) { errorHandler.errorOccurred("trying to wiggle the widget", e); } } } ``` I initialise event listeners with an implementation of this that handles the failure in whatever way makes sense at that point in the application. It might pop up a dialog, show a flashing error icon in the status bar, log an audit message, or abort the process, for example.
When nothing can be done about you should log and send a message to the user. If something goes wrong that may damage data or give wrong results if you can't recover you should close the application.
Java Exception handling within "events"
[ "", "java", "exception", "events", "" ]
I need a textarea where I type my text in the box, it grows in length as needed to avoid having to deal with scroll bars and it need to shrink after delete text! I didn’t want to go down the mootools or jquery route because I have a lightweight form.
You can check the content's height by setting to `1px` and then reading the `scrollHeight` property: ``` function textAreaAdjust(element) { element.style.height = "1px"; element.style.height = (25+element.scrollHeight)+"px"; } ``` ``` <textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea> ``` It works under Firefox 3, IE 7, Safari, Opera and Chrome.
You may also try `contenteditable` attribute onto a normal `p` or `div`. Not really a `textarea` but it will auto-resize without script. ``` .divtext { border: ridge 2px; padding: 5px; width: 20em; min-height: 5em; overflow: auto; } ``` ``` <div class="divtext" contentEditable>Hello World</div> ```
Textarea to resize based on content length
[ "", "javascript", "" ]
It should change the video and start playing regardless of whether or not a video is currently loaded and playing. Thanks.
You can check out the javascript api for the flowplayer [here](http://flowplayer.org/documentation/api/index.html) Specifically, you'll probably want to check out the flowplayer objects 'Clip' and 'Player'
See example below where api is your flowplayer instance and replaceclip is the one you want to start plating ``` var api = flashembed("player", {src:'FlowPlayerDark.swf'}, {config: ...}}); var replaceclip = {'url':'myvideo.mp4', 'autoplay':true}; <button onClick="api.playClip(replaceclip)">Play</button> ```
How to change video (and start playing immediately) in Flowplayer via Javascript?
[ "", "javascript", "flowplayer", "" ]
What do I need to do to make a [Windows Forms](https://learn.microsoft.com/en-us/dotnet/desktop/winforms/overview/?view=netdesktop-5.0) application to be able to run in the System Tray? Not an application that can be minimized to the tray, but an application that will be only exist in the tray, with nothing more than * an icon * a tool tip, and * a "*right click*" menu.
The code project article [Creating a Tasktray Application](http://www.codeproject.com/Articles/18683/Creating-a-Tasktray-Application) gives a very simple explanation and example of creating an application that only ever exists in the System Tray. Basically change the `Application.Run(new Form1());` line in `Program.cs` to instead start up a class that inherits from `ApplicationContext`, and have the constructor for that class initialize a `NotifyIcon` ``` static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MyCustomApplicationContext()); } } public class MyCustomApplicationContext : ApplicationContext { private NotifyIcon trayIcon; public MyCustomApplicationContext () { // Initialize Tray Icon trayIcon = new NotifyIcon() { Icon = Resources.AppIcon, ContextMenu = new ContextMenu(new MenuItem[] { new MenuItem("Exit", Exit) }), Visible = true }; } void Exit(object sender, EventArgs e) { // Hide tray icon, otherwise it will remain shown until user mouses over it trayIcon.Visible = false; Application.Exit(); } } ```
As mat1t says - you need to add a NotifyIcon to your application and then use something like the following code to set the tooltip and context menu: ``` this.notifyIcon.Text = "This is the tooltip"; this.notifyIcon.ContextMenu = new ContextMenu(); this.notifyIcon.ContextMenu.MenuItems.Add(new MenuItem("Option 1", new EventHandler(handler_method))); ``` This code shows the icon in the system tray only: ``` this.notifyIcon.Visible = true; // Shows the notify icon in the system tray ``` The following will be needed if you have a form (for whatever reason): ``` this.ShowInTaskbar = false; // Removes the application from the taskbar Hide(); ``` The right click to get the context menu is handled automatically, but if you want to do some action on a left click you'll need to add a Click handler: ``` private void notifyIcon_Click(object sender, EventArgs e) { var eventArgs = e as MouseEventArgs; switch (eventArgs.Button) { // Left click to reactivate case MouseButtons.Left: // Do your stuff break; } } ```
How can I make a .NET Windows Forms application that only runs in the System Tray?
[ "", "c#", ".net", "winforms", "system-tray", "" ]
I'm writing a program in scala which call: ``` Runtime.getRuntime().exec( "svn ..." ) ``` I want to check if "svn" is available from the commandline (ie. it is reachable in the PATH). How can I do this ? PS: My program is designed to be run on windows
Here's a Java 8 solution: ``` String exec = <executable name>; boolean existsInPath = Stream.of(System.getenv("PATH").split(Pattern.quote(File.pathSeparator))) .map(Paths::get) .anyMatch(path -> Files.exists(path.resolve(exec))); ``` Replace `anyMatch(...)` with `filter(...).findFirst()` to get a fully qualified path. --- Here's a cross-platform static method that compares common executable extensions: ``` import java.io.File; import java.nio.file.Paths; import java.util.stream.Stream; import static java.io.File.pathSeparator; import static java.nio.file.Files.isExecutable; import static java.lang.System.getenv; import static java.util.regex.Pattern.quote; public static boolean canExecute( final String exe ) { final var paths = getenv( "PATH" ).split( quote( pathSeparator ) ); return Stream.of( paths ).map( Paths::get ).anyMatch( path -> { final var p = path.resolve( exe ); var found = false; for( final var extension : EXTENSIONS ) { if( isExecutable( Path.of( p.toString() + extension ) ) ) { found = true; break; } } return found; } ); } ``` This should address most of the critiques for the first solution. Aside, iterating over the [`PATHEXT`](https://superuser.com/a/228693/9067) system environment variable would avoid hard-coding extensions, but comes with its own drawbacks.
I'm no scala programmer, but what I would do in any language, is to execute something like '`svn help`' just to check the return code (0 or 1) of the exec method... if it fails the svn is not in the path :P ``` Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("svn help"); int exitVal = proc.exitValue(); ``` By convention, the value 0 indicates normal termination.
How to check existence of a program in the path
[ "", "java", "scala", "runtime", "" ]
I'm trying to send a lot of data from a form using the $.post method in jQuery. I've used the serialize() function first to make all the form data into one long string which I will then explode serverside. The weird thing is when I try and send it using $.post it appends the result of the serialize() to the URL as if I was sending it using GET. Anyone have any ideas why this is happening? Here's the jquery: ``` $("#addShowFormSubmit").click(function(){ var perfTimes = $("#addShowForm").serialize(); $.post("includes/add_show.php", {name: $("#showTitle").val(), results: perfTimes }, function(data) { $("#addShowSuccess").empty().slideDown("slow").append(data); }); }); ``` here's the php: ``` $show = $_POST['name']; $results = $_POST['results']; $perfs = explode("&", $results); foreach($perfs as $perf) { $perf_key_values = explode("=", $perf); $key = urldecode($perf_key_values[0]); $values = urldecode($perf_key_values[1]); } echo $key, $values; ```
If you are using a `<button>` element to activate the serialize and ajax, and if that `<button>` element is within the `form` element, the `button` automatically acts as a form submission, no matter what other .click assignment you give it with jQuery. ## type='submit' `<button></button>` and `<button type='submit'></button>` are the same thing. They will submit a form if placed within the `<form>` element. ## type='button' `<button type='button'></button>` is different. It is just a normal button and will not submit the form (unless you purposely make it submit the form via JavaScript). And in the case where a **form** element has no action attribute specified, this submission simply sends the data back onto the same page. So you will end up seeing a page refresh, along with the serialized data appearing in the URL as if you used GET in your ajax. ## Possible solutions 1 - Make the `<button>` type `button`. As explained above, this will prevent the button from submitting the form. Before: ``` <form id='myForm'> <!--Some inputs, selects, textareas, etc here--> <button id='mySubmitButton'>Submit</button> </form> ``` After: ``` <form id='myForm'> <!--Some inputs, selects, textareas, etc here--> <button type='button' id='mySubmitButton'>Submit</button> </form> ``` 2 - Move the `<button>` element outside the `<form>` element. This will prevent the button from submitting the form. Before: ``` <form id='myForm'> <!--Some inputs, selects, textareas, etc here--> <button id='mySubmitButton'>Submit</button> </form> ``` After: ``` <form id='myForm'> <!--Some inputs, selects, textareas, etc here--> </form> <button id='mySubmitButton'>Submit</button> ``` 3 - Add in the `preventDefault()` into the button click handler to prevent the form from being submitted (it's default action): ``` $("#addShowFormSubmit").click(function(event){ event.preventDefault(); var perfTimes = $("#addShowForm").serialize(); $.post("includes/add_show.php", {name: $("#showTitle").val(), results: perfTimes }, function(data) { $("#addShowSuccess").empty().slideDown("slow").append(data); }); }); ``` Obviously without seeing all your code, I have no idea if this is the case for your issue, but the only reason I have ever seen behavior you are describing is because the submit button was a `<button>` without a type specified.
try using serializeArray() instead of serialize(). serialize() will produce an url-encoded query string, whereas serializeArray() produces a JSON data structure.
jquery serialize and $.post
[ "", "php", "jquery", "serialization", "post", "get", "" ]
I'm trying to connect to a web service, written in Java, but there's something I can't figure out. Using WCF and a customBinding, almost everything seems to be fine, except one part of the SOAP message, as it's missing the Nonce and Created part nodes. Obviously I'm missing something, so if you could point me into the right direction, it'd be much appreciated. Here's the custom binding: ``` <binding name="CustomHTTPBinding"> <security includeTimestamp="false" authenticationMode="UserNameOverTransport" defaultAlgorithmSuite="Basic256" requireDerivedKeys="True" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"> </security> <textMessageEncoding maxReadPoolSize="211" maxWritePoolSize="2132" messageVersion="Soap11" writeEncoding="utf-8"/> <httpsTransport /> </binding> ``` And here's the relevant part of the message: ``` <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <o:UsernameToken u:Id="uuid-c306efd1-e84c-410e-a2ad-1046b368582e-1"> <o:Username> <!-- Removed--> </o:Username> <o:Password> <!-- Removed--> </o:Password> </o:UsernameToken> </o:Security> ``` And this's how it should look: ``` <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1"> <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-25763165"> <wsse:Username>..</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">..</wsse:Password> <wsse:Nonce>6ApOnLn5Aq9KSH46pzzcZA==</wsse:Nonce> <wsu:Created>2009-05-13T18:59:23.309Z</wsu:Created> </wsse:UsernameToken> </wsse:Security> ``` So the question is: How could I introduce the Nonce and Created elements inside the security part?
To create the nonce, I had to change a few things First, added a custom binding in my config ``` <system.serviceModel> <bindings> <customBinding> <binding name="myCustomBindingConfig"> <security includeTimestamp="false" authenticationMode="UserNameOverTransport" defaultAlgorithmSuite="Basic256" requireDerivedKeys="true" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"> </security> <textMessageEncoding messageVersion="Soap11"></textMessageEncoding> <httpsTransport maxReceivedMessageSize="2000000000" /> </binding> </customBinding> </bindings> </system.serviceModel> <client> <endpoint address="https://..." [other tags] binding="customBinding" bindingConfiguration="OrangeLeapCustomBindingConfig"/> </client> ``` Then, take this code found here: <http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/4df3354f-0627-42d9-b5fb-6e880b60f8ee> and modify it to create the nonce (just a random hash, base-64 encoded) ``` protected override void WriteTokenCore(System.Xml.XmlWriter writer, System.IdentityModel.Tokens.SecurityToken token) { Random r = new Random(); string tokennamespace = "o"; DateTime created = DateTime.Now; string createdStr = created.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); string nonce = Convert.ToBase64String(Encoding.ASCII.GetBytes(SHA1Encrypt(created + r.Next().ToString()))); System.IdentityModel.Tokens.UserNameSecurityToken unToken = (System.IdentityModel.Tokens.UserNameSecurityToken)token; writer.WriteRaw(String.Format( "<{0}:UsernameToken u:Id=\"" + token.Id + "\" xmlns:u=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">" + "<{0}:Username>" + unToken.UserName + "</{0}:Username>" + "<{0}:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">" + unToken.Password + "</{0}:Password>" + "<{0}:Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">" + nonce + "</{0}:Nonce>" + "<u:Created>" + createdStr + "</u:Created></{0}:UsernameToken>", tokennamespace)); } protected String ByteArrayToString(byte[] inputArray) { StringBuilder output = new StringBuilder(""); for (int i = 0; i < inputArray.Length; i++) { output.Append(inputArray[i].ToString("X2")); } return output.ToString(); } protected String SHA1Encrypt(String phrase) { UTF8Encoding encoder = new UTF8Encoding(); SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider(); byte[] hashedDataBytes = sha1Hasher.ComputeHash(encoder.GetBytes(phrase)); return ByteArrayToString(hashedDataBytes); } ```
I had the same problem. Instead of the custom token serializer I used a `MessageInspector` to add the correct `UsernameToken` in the `BeforeSendRequest` method. I then used a custom behavior to apply the fix. The entire process is documented (with a [demo project](http://www.box.net/shared/lu3q83l6kr)) in my blog post [Supporting the WS-I Basic Profile Password Digest in a WCF client proxy](http://benpowell.org/supporting-the-ws-i-basic-profile-password-digest-in-a-wcf-client-proxy/). Alternatively, you can just read the [PDF](http://www.box.net/shared/ooom8db1i0). If you want to follow my progress through to the solution, you'll find it on StackOverflow titled, "[Error in WCF client consuming Axis 2 web service with WS-Security UsernameToken PasswordDigest authentication scheme](https://stackoverflow.com/questions/3102693/error-in-wcf-client-consuming-axis-2-web-service-with-ws-security-usernametoken-p)":
WCF: Adding Nonce to UsernameToken
[ "", "c#", "wcf", "web-services", "" ]
I am having many files with multple includes one into another like below, `File1` is included in `File2` and then `File2` is under `File3` Now I want to declare a session variable `site_user_conutry` from File1 and then I am checking on File2 that if there is any no value in the session variable then Only I am including File1.php I have added `session_start();` in each [age but still its not working ?? Please tell me how can I make session work in the above condition.
How are you setting the session variable? You should try setting it like so: ``` $_SESSION['site_user_conutry'] = 'United-Kingdom'; ``` Have you placed session\_start() at the very top of the document, or at least before you output any information?
Within File2 ``` if ($_SESSION["site_user_country"] != null) { include_once(File3); } ```
How to work with Session and Include statement in PHP?
[ "", "php", "session", "logic", "" ]
I have used Netbeans before with Subversion (SVN), and I liked how it showed me what I had changed since last commit, using the coloring in the left margin. Can Eclipse do the same? I have installed Subclipse.
Visit Window -> Preferences -> General -> Editors -> Text Editors -> Quick Diff, and enable * Enable quick diff * Show differences in overview ruler
SubVersive and Subclipse can both show changed files in the project explorer and differences between versions in the history. I currently use Subversive and am happy with it (although installing it was painful the first time.)
Can I setup Eclipse to show code changes
[ "", "php", "linux", "eclipse", "svn", "" ]
I am trying to use multimap for the first time but my app will not compile. TIA Paul.. ``` // file dept.h typedef std::multimap <CString, std::map< CString, CString> > _DeparmentRecord; // also tryied replacing CString with LPCWSTR _DeparmentRecord DeparmentRecord; // file dept.cpp DWORD CIni::AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value) { DeparmentRecord.insert(std::make_pair ( Section, std::make_pair(Name, Value)) ); <-- error here } ``` c:\program files\microsoft visual studio 9.0\vc\include\utility(57) : error C2664: 'std::map<\_Kty,\_Ty>::map(const std::less<\_Ty> &)' : cannot convert parameter 1 from 'const std::pair<\_Ty1,\_Ty2>' to 'const std::less<\_Ty> &' 1> with 1> [ 1> \_Kty=CString, 1> \_Ty=CString 1> ] 1> and 1> [ 1> \_Ty1=LPCWSTR, 1> \_Ty2=LPCWSTR 1> ] 1> and 1> [ 1> \_Ty=CString 1> ] 1> Reason: cannot convert from 'const std::pair<\_Ty1,\_Ty2>' to 'const std::less<\_Ty>' 1> with 1> [ 1> \_Ty1=LPCWSTR, 1> \_Ty2=LPCWSTR 1> ] 1> and 1> [ 1> \_Ty=CString 1> ] 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1> c:\dev\projects\migrator\jobbuilder\jobbuilder\ini.cpp(55) : see reference to function template instantiation 'std::pair<\_Ty1,\_Ty2>::pair>(const std::pair> &)' being compiled 1> with 1> [ 1> \_Ty1=const CString, 1> \_Ty2=std::map 1> ] ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Change the function as follows. ``` DWORD AddNameValue(LPCWSTR Section, LPCWSTR Name, LPCWSTR Value) { std::map<CString, CString> aTemp; aTemp.insert(std::make_pair (Name, Value)); DeparmentRecord.insert(std::make_pair (Section, aTemp)) ; } ```
You're trying to insert a `pair< section, pair<...> >` into a map that takes `pair< section, map<...> >`.
std::multimap compile errors
[ "", "c++", "visual-studio-2008", "mfc", "" ]
In essence, I want to put a variable on the stack, that will be reachable by all calls below that part on the stack until the block exits. In Java I would solve this using a static thread local with support methods, that then could be accessed from methods. Typical example: you get a request, and open a database connection. Until the request is complete, you want all code to use this database connection. After finishing and closing the request, you close the database connection. What I need this for, is a report generator. Each report consist of multiple parts, each part can rely on different calculations, sometimes different parts relies in part on the same calculation. As I don't want to repeat heavy calculations, I need to cache them. My idea is to decorate methods with a cache decorator. The cache creates an id based on the method name and module, and it's arguments, looks if it has this allready calculated in a stack variable, and executes the method if not. I will try and clearify by showing my current implementation. Want I want to do is to simplify the code for those implementing calculations. First, I have the central cache access object, which I call MathContext: ``` class MathContext(object): def __init__(self, fn): self.fn = fn self.cache = dict() def get(self, calc_config): id = create_id(calc_config) if id not in self.cache: self.cache[id] = calc_config.exec(self) return self.cache[id] ``` The fn argument is the filename the context is created in relation to, from where data can be read to be calculated. Then we have the Calculation class: ``` class CalcBase(object): def exec(self, math_context): raise NotImplementedError ``` And here is a stupid Fibonacci example. Non of the methods are actually recursive, they work on large sets of data instead, but it works to demonstrate how you would depend on other calculations: ``` class Fibonacci(CalcBase): def __init__(self, n): self.n = n def exec(self, math_context): if self.n < 2: return 1 a = math_context.get(Fibonacci(self.n-1)) b = math_context.get(Fibonacci(self.n-2)) return a+b ``` What I want Fibonacci to be instead, is just a decorated method: ``` @cache def fib(n): if n<2: return 1 return fib(n-1)+fib(n-2) ``` With the math\_context example, when math\_context goes out of scope, so does all it's cached values. I want the same thing for the decorator. Ie. at point X, everything cached by @cache is dereferrenced to be gced.
I went ahead and made something that might just do what you want. It can be used as both a decorator and a context manager: ``` from __future__ import with_statement try: import cPickle as pickle except ImportError: import pickle class cached(object): """Decorator/context manager for caching function call results. All results are cached in one dictionary that is shared by all cached functions. To use this as a decorator: @cached def function(...): ... The results returned by a decorated function are not cleared from the cache until decorated_function.clear_my_cache() or cached.clear_cache() is called To use this as a context manager: with cached(function) as function: ... function(...) ... The function's return values will be cleared from the cache when the with block ends To clear all cached results, call the cached.clear_cache() class method """ _CACHE = {} def __init__(self, fn): self._fn = fn def __call__(self, *args, **kwds): key = self._cache_key(*args, **kwds) function_cache = self._CACHE.setdefault(self._fn, {}) try: return function_cache[key] except KeyError: function_cache[key] = result = self._fn(*args, **kwds) return result def clear_my_cache(self): """Clear the cache for a decorated function """ try: del self._CACHE[self._fn] except KeyError: pass # no cached results def __enter__(self): return self def __exit__(self, type, value, traceback): self.clear_my_cache() def _cache_key(self, *args, **kwds): """Create a cache key for the given positional and keyword arguments. pickle.dumps() is used because there could be unhashable objects in the arguments, but passing them to pickle.dumps() will result in a string, which is always hashable. I used this to make the cached class as generic as possible. Depending on your requirements, other key generating techniques may be more efficient """ return pickle.dumps((args, sorted(kwds.items())), pickle.HIGHEST_PROTOCOL) @classmethod def clear_cache(cls): """Clear everything from all functions from the cache """ cls._CACHE = {} if __name__ == '__main__': # used as decorator @cached def fibonacci(n): print "calculating fibonacci(%d)" % n if n == 0: return 0 if n == 1: return 1 return fibonacci(n - 1) + fibonacci(n - 2) for n in xrange(10): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) def lucas(n): print "calculating lucas(%d)" % n if n == 0: return 2 if n == 1: return 1 return lucas(n - 1) + lucas(n - 2) # used as context manager with cached(lucas) as lucas: for i in xrange(10): print 'lucas(%d) = %d' % (i, lucas(i)) for n in xrange(9, -1, -1): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) cached.clear_cache() for n in xrange(9, -1, -1): print 'fibonacci(%d) = %d' % (n, fibonacci(n)) ```
this question seems to be two question * a) sharing db connection * b) caching/Memoizing b) you have answered yourselves a) I don't seem to understand why you need to put it on stack? you can do one of these 1. you can use a class and connection could be attribute of it 2. you can decorate all your function so that they get a connection from central location 3. each function can explicitly use a global connection method 4. you can create a connection and pass around it, or create a context object and pass around context,connection can be a part of context etc, etc
How to put variables on the stack/context in Python
[ "", "python", "thread-local", "contextmanager", "" ]
If I do the following: ``` public class Test { public static void Main() { List<Person> persons = new List<Person> { new Person() }; persons[0].Sneezing += new EventHandler(Person_Sneezing); persons = null; } public static void Person_Sneezing(object sender, EventArgs e) { (sender as Person).CoverFace(); } } ``` Does the person that was in person[0] still exists in memory because it's Sneezing delegate has a reference to the Person\_Sneezing method or does it get collected by the GC?
This will be collected by the GC. To be kept in memory an object must be referenced directly or indirectly by ... 1. A value on the stack 2. A value rooted in a strong GC handle 3. A corner case or two I'm not thinking of at the moment This is not true for the object at persons[0]. So it will be collected. That is of course assuming the constructor for Person() doesn't do anything funny like add itself to ThreadLocalStorage.
You're halfway there; this would be a memory leak if it were the *other way around.* That is, if it looked like this: ``` public class Test { public void HookupStuff() { List<Person> persons = new List<Person> { new Person() }; this.EventHappened += new EventHandler(persons[0].SomeMethod); // persons[0].Sneezing += new EventHandler(Person_Sneezing); persons = null; } } ``` Now `persons[0]` will stick around, even though you nulled out `persons`, since the parent class has a reference to a method on it.
Does garbage collector clear objects subscribed to events?
[ "", "c#", "memory-leaks", "garbage-collection", "" ]
I need distinct year and month from date column which would be sorted by same column. I have date coulmn with values like (YYYY/MM/DD) ``` 2007/11/7 2007/1/8 2007/11/4 2007/12/3 2008/10/4 2009/11/5 2008/5/16 ``` after having query, it should be ``` 2007/1/1 2007/11/1 2007/12/1 2008/5/1 2008/10/1 2009/11/1 ``` This doesn't seems to be working ``` SELECT distinct (cast(year(datecol) as nvarchar(20) ) + '/'+ cast(month(datecol) as nvarchar(20) ) + '/1') as dt1 FROM Table ORDER BY dt1 ```
Soemthing like this would work on MS SQL Server: ``` select distinct dateadd(day, -1 * DAY(datefield) + 1, datefield) From datetable order by dateadd(day, -1 * DAY(datefield) + 1, datefield) ``` The DATEADD function call basically subtracts (day-1) DAYS from the current date --> you always get the first of whatever month that date is in. Sort by it and you're done! :-) ADditionally, you could also add this functionality to your table as a "computed column" and then use that for easy acccess: ``` alter table yourTable add FirstOfMonth As DATEADD(day, -1 * DAY(datefield) + 1, datefield) persisted ``` Then your query would be even simpler: ``` SELECT DISTINCT FirstOfMonth FROM YourTable ORDER BY FirstOfMonth ``` Marc
When dealing with dates in SqlServer avoid using `cast` like this - the resulting format will change depending on server config. Instead use [`convert`](http://msdn.microsoft.com/en-us/library/ms187928.aspx) and choose a format (for instance 112) that adds leading zeros to the month.
sort distinct date column
[ "", "sql", "sql-server", "t-sql", "" ]
I'm using c# to communicate with twitter and i need to code a schedule system to send twitter messages at a user defined date. The messages to be sent are in a database with the date and time of deliver. Which is the best method to check the db for scheduled messages and send it when the time arrives?
In fact the solution consists in using a windows service but it can't communicate directly with the ASP.NET MVC app. I've added a Web Service that handles the task and a System.Threading.Timer in Windows Service to periodically call the Web Service.
How accurate do you need the timing to be? Could you get away with polling the database every 5 minutes, saying "Tell me all the messages which need to be delivered before current time + 5 minutes" and then sending them all? (And marking them as sent in the database, of course.) Does it matter if they're a bit early or late? You *can* do the scheduling on the C# side to make it more accurate, but unless you really need to I'd stick with a very simple solution. (Depending on your database there may be clever ways of getting callbacks triggered etc... but again, I'd stick with the simplest solution which works.)
Schedule method invocation C#
[ "", "c#", "scheduling", "" ]
I want to rewrite this, maybe using predicates, or Lambda, how can I do this? ``` serviceResponse = client.Authorize(....); string authorizeResponse = string.Empty; foreach (CdcEntry element in serviceResponse.Cdc) { authorizeResponse += element.Name + Environment.NewLine; foreach (CdcEntryItem item in element.Items) { authorizeResponse += " (" + item.Key + ", " + item.Value + ") " + Environment.NewLine; } } ``` Thanks
I don't think there's any real point to use LINQ here, since you're trying to build a response string, and are thus performing a task most suited to imperative rather than functional programming. (You could of course use the `Aggregate` method on a string, but that's not really any help.) In addition, the `StringBuilder` type is more suited for this sort of job. (It's much more efficient, and also cleaner in my opinion. Of course, the former may not matter so much depending on the context.) Here is the optimal way to do this, in my view: ``` serviceResponse = client.Authorize(....); var sb = new StringBuilder(); foreach (CdcEntry element in serviceResponse.Cdc) { sb.AppendLine(element.Name); foreach (CdcEntryItem item in element.Items) { sb.AppendFormat(" ({0}, {1}) ", item.Key, item.Value); sb.AppendLine(); } } var authorizeResponse = sb.ToString(); ```
You certainly could but all you would gain would be a couple of `ForEach` method calls and multi-statement lambdas inside which (in my opinion) would be significantly less readable. Without knowing the datatypes of you identifiers (specifically `serviceResponse.Cdc` and `element.Items`) you may even have to roll your own `ForEach` extension method as well to make this work. I think what you have is better than a LINQ equivalent but if you really want to LINQify it, please post some more info about the code you have posted and we may be able to help more.
How can this be achieved in LINQ?
[ "", "c#", "linq", "" ]
I have a java application, which copies or moves a bunch of giga files from one ftp server to another. Currently it copies a file from the first fpt server to the local computer (where it runs) using ftp get and then copies it to the second ftp server using ftp put. I use net library from apache. Is it possible to copy it directly from one ftp server to another bypassing the local computer? One idea is to create a java telnet session and and send a couple of ftp commands. Will it work? Any other suggestions?
Server-to-server FTP transfer is also called "FXP". Try to search for "fxp java" in google. For example: [this page](http://www.jscape.com/sftp/docs/javadoc/com/jscape/inet/ftp/Fxp.html) could be useful.
That will certainly work. If you can use rcp(1) or scp(1), however, you don't need the intermediate copy or a telnet session. Simply use ``` $ scp user@sys1:file user@sys2:file ``` If you do use a remote session, consider using ssh(1) instead of telnet.
copy or move a file from one ftp server to another
[ "", "java", "ftp", "" ]
I have a desktop application . The functionality is complete, but user interface requires a lot of work. I am looking for UI tools.My current operating system is Windows and application is required to run on both Windows and Linux. Can you guys recommend any? The software is customized file management application for a specific client, with future plans of web integration. Thanks in advance :) Application Environment Lang : java, IDE : Eclipse 3.4, Target Platforms : Windows Vista-OpenSuse 11
SWT is another option. The advantages are a look-and-feel closer to the native platform, and generally faster execution times. The main disadvantage is that you will have to have different distributions for different target platforms, as SWT depends on platform specific libraries. With an eye toward the web integration, look at GWT. You write your interface in Java but it gets generated into Javascript and can thus be run in a browser. This may make your deployments easier. On the downside, you lose a bit of the rich client UI, but maybe you don't even need that. It all depends on how complex your UI is. A word of advice: you mentioned future plans of web integration. Take special care to isolate what logic you can from the UI. Keep the UI as clean as possible, and then you may be able to use the same logic in the web UI either on the client or the server.
If you are just looking for a GUI designer you could check out [Netbeans IDE](http://netbeans.org "Netbeans") which has a built-in Swing user-interface builder. Alternatively you could build a front-end in [JavaFX](http://javafx.com "Java FX"). There's not much tooling for FX yet but a new tool was recently previewed at JavaOne 09. Not sure when it's being released.
UI for a Desktop App
[ "", "java", "user-interface", "desktop", "" ]
For Silverlight 2, it looks like programming choices are: * C# * VB * DLR scripting languages + IronRuby + IronPython + A sadly neglected (if not cancelled) Managed jScript Is this a case where the native languages (C# and VB) are faster than the DLR languages by an order of magnitude or so? Any hope of "living" in IronPython when I do Silverlight client programming, or should I expect to drop into C# for processor-intensive work? My survey of languages comes from [this set of examples for C# and VB](http://silverlight.net/learn/tutorials.aspx) and [this page discussing the DLR](http://silverlight.net/learn/dynamiclanguages.aspx/).
Unfortunately there is no hard and fast answer to this question. Performance of even the same language varies greatly based on a number of parameters. Yes, in **general** VB.Net and C# will be faster than DLR based languages. Static languages do more work at compile time such as method binding. This type of work must be done at runtime for DLR based languages and hence they have a bit more cost at runtime. However, lots of work goes into optimizing the DLR and DLR based languages. Much of this work is mitigated by various caches and so forth. In many types of applications, the performance difference will be negligable. I would not rule out a DLR based language based solely on performance unless a profiler told me it was actually a problem.
Typically optimizing an algorithm will have a much greater effect than rewriting in a static language. You might be interested in [Show #429](http://www.dotnetrocks.com/default.aspx?showNum=429) of .NET Rocks, an interview with Michael Foord. Here's a relevant excerpt from the [transcript](http://perseus.franklins.net/dotnetrocks_0429_michael_foord.pdf): > Dynamic languages are a lot easier to > test, they 're really suited for the > Test Driven Development approach that > the developers were taking at that > time. But I assumed that for > performance reasons, they would have > to rewrite in C# at some point, and > then three and a bit years later we > got 40,000 lines of IronPython code, > we've got about 140.000 lines in a > test code, we've got some type of > about 300 lines of C# and every time > they come to look at the performance, > every time they come and said locate > an operation that's not working fast > enough, we've been able to get the > speed we need by improving our > algorithms, by improving our Python > code and not having to drop into C#, > and the reasons programs run slow is > usually not the fault of the language, > it's the fault of the programmer, the > developer.
What is the difference in speed between the DLR languages and C# in Silverlight 2?
[ "", "c#", "silverlight", "ironpython", "silverlight-2.0", "ironruby", "" ]
I wrote a simple function to copy contents(including all child nodes) from one node to another of an XML DOM Object. Surprisingly in the function, the for loop is not iterating for n=1 for some reason i cant figure out, please help, i've been trying to debug this in all possible ways from 4 days. This function is not iterating for n=1 (i.e. it's iterating for n=0 and n=2 and so on except n=1): ``` function copyNode(fromNode, toNode) { for (var n=0; n [lessthan] fromNode.childNodes.length; n++) { var fromChild = fromNode.childNodes[n]; var toChild = toNode.appendChild(fromChild); copyNode(fromChild, toChild); } } ``` Full code: ``` <html> <head> <script type="text/javascript"> //STANDARD TEXT to XMLDOM OBJECT RETURN FUNCTION function getXmlDoc(text){ var xmldoc = null; try //Internet Explorer { xmldoc=new ActiveXObject("Microsoft.XMLDOM"); xmldoc.async="false"; xmldoc.loadXML(text); return xmldoc; } catch(e) { try //Firefox, Mozilla, Opera, etc. { parser=new DOMParser(); xmldoc=parser.parseFromString(text,"text/xml"); return xmldoc; } catch(e) { alert(e.message); return; } } } //END OF getXmlDoc //Function that refuses to work, the 2nd child is always being skipped, i.e n=1 is never running :(, ONLY n=1 is not running function copyNode(fromNode, toNode) { for (var n=0; n [lessthan] fromNode.childNodes.length; n++) { var fromChild = fromNode.childNodes[n]; var toChild = toNode.appendChild(fromChild); copyNode(fromChild, toChild); } } //Function to clear a node's contents function clearNode(node2) { x2=node2.childNodes; if(x2.length!=0) { for(i=0;i [lessthan] x2.length;i++) { node2.removeChild(x2[i]); } } } //XML1 text="<book>"; text=text+"<title>Everyday Italian</title>"; text=text+"<author>Giada De Laurentiis</author>"; text=text+"<year>2005</year>"; text=text+"</book>"; xmlDoc=getXmlDoc(text); //XML2 text2="<book>"; text2=text2+"<title><a>1</a><b>2</b><c><ca>3</ca></c></title>"; text2=text2+"<year>2006</year>"; text2=text2+"</book>"; xmlDoc2=getXmlDoc(text2); x=xmlDoc.documentElement.childNodes; y=xmlDoc2.documentElement.childNodes; var string = (new XMLSerializer()).serializeToString(y[0]); alert(string); var string = (new XMLSerializer()).serializeToString(x[0]); alert(string); clearNode(x[0]); copyNode(y[0],x[0]); var string = (new XMLSerializer()).serializeToString(xmlDoc); alert(string); </script> </head> <body> </body> </html> ```
As you move (not copy) the source nodes to the destination, they are removed from the list of childNodes on the source, and its length decreases. You should use something like: ``` while (fromNode.firstChild) { toNode.appendChild(fromNode.firstChild); } ``` instead. Also, you don't need the recursion; when the node is moved, all its children will be moved with it.
Here is the way I would do it (which may or may not be preferred). ``` function copyElementChildren(fromNode,toNode){ for (var i in fromNode.childNodes) { var node = fromNode.childNodes[i].cloneNode(true); toNode.appendChild(node); }; }; ``` This uses cloning to copy it the element. The true in cloneNode(true) tells the browser to copy its attributes and childNodes as well.
Copying one DOM XML node to another in JavaScript
[ "", "javascript", "xml", "dom", "" ]
I've seen some Python list comprehensions before, but can this be done in a single line of Python? ``` errs = {} for f in form: if f.errors: errs[f.auto_id] = f.errors ```
``` errs = dict((f.auto_id, f.errors) for f in form if f.errors) ```
Python 3.0 has dict comprehensions as a shorter/more readable form of the anser provided by Steef: ``` errs = {f.auto_id: f.errors for f in form if f.errors} ```
How can this be written on a single line?
[ "", "python", "django", "dictionary", "list-comprehension", "" ]
I'm after a regular expression that matches a UK Currency (ie. £13.00, £9,999.99 and £12,333,333.02), but does not allow negative (-£2.17) or zero values (£0.00 or 0). I've tried to create one myself, but I've got in a right muddle! Any help greatfully received. Thanks!
This'll do it (well mostly...) ``` /^£?[1-9]{1,3}(,\d{3})*(\.\d{2})?$/ ``` Leverages the ^ and $ to make sure no negative or other character is in the string, and assumes that commas will be used. The pound symbol, and pence are optional. *edit: realised you said non-zero so replaced the first \d with [1-9]* Update: it's been pointed out the above won't match £0.01. The below improvement *will* but now there's a level of complexity where it may quite possibly be better to test /[1-9]/ first and then the above - haven't benchmarked it. ``` /^£?(([1-9]{1,3}(,\d{3})*(\.\d{2})?)|(0\.[1-9]\d)|(0\.0[1-9]))$/ ``` Brief explanation: * Match beginning of string followed by optional "£" * Then match *either*: + a >£1 amount with potential for comma separated groupings and optional pence + OR a <£1 >=£0.10 amount + OR a <=£0.09 amount * Then match end of line The more fractions of pence (zero in the above) you require adding to the regex the less efficient it becomes.
Under Unix/Linux, it's not always possible to type in the '£' sign in a JavaScript file, so I tend to use its hexadecimal representation, thus: **/^\xA3?\d{1,3}?([,]\d{3}|\d)\*?([.]\d{1,2})?$/** This seems to take care of all combinations of UK currency amounts representation that I have come across.
UK Currency Regular Expression for javascript
[ "", "javascript", "regex", "" ]
I'm currently refactoring some code to make it more testable. Specifically, I am extracting the interface of several classes to allow easy creation of test doubles. I'd like to keep the public interface the same to this code, naming the interface after the original class. However this leaves me with the problem of what to call the original class. I'm using C++. If my interface is: ``` class ServiceClient; ``` What should I call the contrete, I've come up with a few options that I'm not convinced by: ``` class ConcreteServiceClient; class ServiceClientImpl; class StandardServiceClient; class BasicServiceClient; ``` What conventions do people use?
I would change the name of the interface class. ``` class ServiceClientInterface {}; ``` Then place the concrete implementations in seprate namespaces: ``` namespace MyService { class Client: public ServiceClientInterface {}; } namespace MyServiceTest { class TestClient: public ServiceClientInterface {}; } ``` Or something completely different. PS. I am into full names. I don;t like the the short 'I' is interface thing. Your taste may vary.
Normally, I reserve "Impl" for the [pimpl idiom](http://www.gotw.ca/gotw/028.htm). I use a full "Interface" on abstract base classes. For concrete implementations, drop the Interface and prefix with what specialization this is: ``` class ServiceClientInterface { // some pure virtual methods }; class XMLServiceClient { // Or whatever "service" it is }; class TestServiceClient { // some well defined }; ```
Extracted Interface naming conventions
[ "", "c++", "interface", "naming-conventions", "" ]
If we are to separate our web server and app server, would we need java on both machines? I've had one coworker say to install jboss on both machines (seems to defeat the purpose if both machines have app server installed) and another says just install jboss on one and apache on the other (app server/web server). I have the web project setup already and it uses servlets and JSPs. The JSPs display the content while the servlets do the action. The servlets receive requests and forward responses to the JSP. My question is how do I do this if the web server only has apache and therefore displays static content? I understand how to forward the requests from the web server to the app server but what about maintaining session state, is that done on the web server and if so how would it be done? If the login page is html and the content after the login is html then how could I stop people from accessing the content if they haven't logged in?
The latter setup you describe, with Apache serving static content and forwarding requests for JSP/servlets onto the app server is the standard setup. Session state is maintained as normal, your Java webapp on the app server sends the user back a cookie containing a JSESSIONID and when the user makes subsequent requests, Apache includes all request info (including cookies) in what it forwards to the app server. The setup becomes a bit more complicated if you want to have Apache sit in front of and load balance requests to multiple JBoss instances, but it's still pretty easy to set up with [mod\_proxy\_balancer](http://httpd.apache.org/docs/2.2/mod/mod_proxy_balancer.html). Some links that might help you: <http://help.shadocms.com/blog/2009/how-to-setup-apache-with-jboss-on-a-shado-site.cfm> <http://redlumxn.blogspot.com/2008/01/configure-apache2-and-jboss-422ga.html>
There are many possibilities. 1. On web machine install just apache with mod\_jk to redirect the requests to tomcat/jboss. In this case you don't need java on this machine. 2. You can also separate your jsp container (e.g. tomcat/jboss) and your app server in this case you you will need to install java where you have your web container. 3. Generally where there is a need of higher security people combine the above mentioned possibilities. Thin web layer (apache + no java) + Web container (e.g. tomcat) + app layer (jboss/glassfish) The first solution is normally the standard one.
Separating web server and app server, do both need java?
[ "", "java", "" ]
I've been extremely unsuccessful in compiling Botan as a static library in Visual C++. The build.h file contains the following code: ``` #ifndef BOTAN_DLL #define BOTAN_DLL __declspec(dllexport) #endif ``` This macro then shows up pretty much everywhere in the Botan codebase, like this: ``` class BOTAN_DLL AutoSeeded_RNG : public RandomNumberGenerator ``` My understanding from a [previous question](https://stackoverflow.com/questions/991842/how-to-link-a-static-library-in-visual-c-2008) is that all you need to do is define BOTAN\_DLL without a value and it should compile as a static library just fine. However, doing so causes a huge list of build errors like "missing tag name." Anyone know how to do this? **EDIT**: Here is a sample of the errors that result from adding /D "BOTAN\_DLL" to the makefile: ``` cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /D "BOTAN_DLL" /nologo /c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj adler32.cpp build\include\botan/allocate.h(19) : error C2332: 'class' : missing tag name build\include\botan/allocate.h(19) : error C2143: syntax error : missing ';' bef ore 'constant' build\include\botan/allocate.h(19) : error C2059: syntax error : 'constant' build\include\botan/allocate.h(20) : error C2143: syntax error : missing ';' bef ore '{' build\include\botan/allocate.h(20) : error C2447: '{' : missing function header (old-style formal list?) build\include\botan/secmem.h(229) : error C2143: syntax error : missing ';' befo re '*' build\include\botan/secmem.h(230) : see reference to class template inst antiation 'Botan::MemoryRegion<T>' being compiled build\include\botan/secmem.h(229) : error C4430: missing type specifier - int as sumed. Note: C++ does not support default-int ```
What are the first few error messages you get? Maybe you have forgotten a header file include? It looks like maybe your compilation command is wrong: ``` cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /D "BOTAN_DLL" /nologo /c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj ``` I think you incorrectly have a space between the `/D` [directive](http://msdn.microsoft.com/en-us/library/hhzbb5c8.aspx) and the value of the preprocessor symbol you are defining. It should be this: ``` cl.exe /Ibuild\include /O2 /EHsc /GR /D_CONSOLE /DBOTAN_DLL= /nologo /c src\checksum\adler32\adler32.cpp /Fobuild\lib\adler32.obj ``` EDIT: if you have `/DBOTAN_DLL`, this is equivalent to `/DBOTAN_DLL=1`, you want to use `/DBOTAN_DLL=` which will give it no associated value. With this `/DBOTAN_DLL`, it is inserted into your code as the value 1, and the compiler sees the error: ``` class 1 Allocator { ... ```
I recently had the need to build a static Botan library myself, and though this is a rather old thread, I thought I would post an answer. I believe the "intended" way to do this is using a configuration option. If you specify ``` configure.py --disable-shared ``` then the generated makefile builds a static botan.lib instead of a .dll. It also generates build.h containing ``` #ifndef BOTAN_DLL #define BOTAN_DLL #endif ```
How to compile the Botan crypto library as a static lib in VC++?
[ "", "c++", "visual-c++", "cryptography", "botan", "" ]
I am trying to do multiple counts in a single sql statement. I have two people, Mark and Chris. I want to count how many times each takes the train on a certain date. Here is the code I am using. ``` SELECT TO_DATE(TRAIN.DEPARTURE_DATE,'YYYYMM') , (select COUNT(DISTINCT DEPARTURE_DATE) FROM TRAIN WHERE PERSON_ID='28' AND DEPARTURE_STATION = 'DUBLIN') AS Mark , (select COUNT(DISTINCT DEPARTURE_DATE) FROM TRAIN WHERE PERSON_ID='29' AND DEPARTURE_STATION = 'DUBLIN') AS Chris FROM TRAIN GROUP BY DEPARTURE_DATE ``` The format this code produces is correct, however the result is not. The result is ``` TO_DATE Mark Chris 2009-01-01 8 11 2009-01-02 8 11 2009-01-03 8 11 ``` etc.... The correct result should ``` TO_DATE Mark Chris 2009-01-01 8 11 2009-01-02 3 7 2009-01-03 6 5 ``` etc... Can anyone see the problem with my code? All help is appreciated
You need one more condition in the subqueries: ``` AND TO_DATE(ti.DEPARTURE_DATE,'YYYYMM') = TO_DATE(to.DEPARTURE_DATE,'YYYYMM') SELECT TO_DATE(TRAIN.DEPARTURE_DATE,'YYYYMM') , (select COUNT(DISTINCT DEPARTURE_DATE) FROM TRAIN ti WHERE PERSON_ID='28' AND DEPARTURE_STATION = 'DUBLIN' AND TO_DATE(ti.DEPARTURE_DATE,'YYYYMM') = TO_DATE(to.DEPARTURE_DATE,'YYYYMM')) AS Mark , (select COUNT(DISTINCT DEPARTURE_DATE) FROM TRAIN WHERE PERSON_ID='29' AND DEPARTURE_STATION = 'DUBLIN' AND TO_DATE(ti.DEPARTURE_DATE,'YYYYMM') = TO_DATE(to.DEPARTURE_DATE,'YYYYMM')) AS Chris FROM TRAIN to GROUP BY DEPARTURE_DATE ```
Try this: ``` SELECT TO_DATE(TRAIN.DEPARTURE_DATE,'YYYYMM') , (select COUNT(*) FROM TRAIN WHERE PERSON_ID='28' AND DEPARTURE_STATION = 'DUBLIN' AND DepartureDate = t.DepartureDate) AS Mark , (select COUNT(*) FROM TRAIN WHERE PERSON_ID='29' AND DEPARTURE_STATION = 'DUBLIN' AND DepartureDate = t.DepartureDate) AS Chris FROM TRAIN t GROUP BY DEPARTURE_DATE ```
SQL,multiple counts with multiple results
[ "", "sql", "" ]
I was reading the C Standard the other day, and noticed that unlike signed integer overflow (which is undefined), unsigned integer overflow is well defined. I've seen it used in a lot of code for maximums, etc. but given the voodoos about overflow, is this considered good programming practice? Is it in anyway insecure? I know that a lot of modern languages like Python do not support it- instead they continue to extend the size of large numbers.
Unsigned integer overflow (in the shape of wrap-around) is routinely taken advantage of in hashing functions, and has been since the year dot.
To put it shortly: *It is perfectly legal/OK/safe to use unsigned integer overflow as you see fit as long as you pay attention and adhere to the definition (for whatever purpose - optimization, super clever algorithms, etc.)*
Is using unsigned integer overflow good practice?
[ "", "c++", "c", "" ]
``` Table A Col1 Col2 101 102 101 103 102 104 104 105 Table B Col1 101 102 103 104 105 ``` I want to take data from Table A and insert it into Table B as a Distinct value in one query so `INSERT INTO TableB (Col1) (SELECT ...)` Any ideas?
You should be able to do: ``` INSERT INTO TableB (Col1) (SELECT Col1 FROM TableA UNION SELECT Col2 FROM TableA) ```
``` INSERT TABLEB (Col1) SELECT Col1 FROM TABLEA UNION SELECT COL2 FROM TABLEA ``` For non-distinct, `UNION ALL`
Insert into one column data from two columns
[ "", "sql", "sql-server", "t-sql", "insert", "" ]
My phone, running Windows Mobile 6, has suddenly decided to drop an hour every time I hook it up to my PC. I tried playing with the timezone settings in the Control Panel, to no avail. I've come to the conclusion the heart of the problem is in the Daylight Saving configuration of my timezone. I could not find any utilities to let me edit this on Windows Mobile (ala `tzedit` in Windows). I've decided to write something of my own, but I cannot find the right keywords to search for! All the variations I can think of for "Windows mobile" and "daylight savings" keep coming back to the changes made in 2007 to the U.S.A DST, and not to an API! Does anyone have any suggestions which functions I should be looking for? I'd like to write this in C#, but P/Invoke should let me access the regular API stuff, I hope. UPDATE: I ended up writing the application myself, using the `TimeZoneInformation` function as suggested below. Thanks! Another UPDATE [about a 2 weeks later]: If you need something like this, I put the program and source code online at <http://shalom.craimer.org/projects/>. I hope this save somebody 5 minutes or something.
You can also pinvoke the [TimeZoneInformation](http://msdn.microsoft.com/en-us/library/aa450660.aspx) functions in case you don't want/can't use the OpenNetCF framework.
Try the [TimeZoneInformation](http://www.opennetcf.com/library/sdf/html/081758af-13a4-42ee-64e0-5a1dec1c979d.htm) class of OpenNetCF.
How can I modify the Daylight Saving Time of my timezone on Windows Mobile?
[ "", "c#", "windows-mobile", "compact-framework", "dst", "" ]
I'm trying to use Assembly.Load() to load an assembly that is in the GAC. For example, say I want to list out all of the types that exist in **PresentationCore.dll**, how would I go about loading **PresentationCore.dll**? When I try this: ``` Assembly a = Assembly.Load("PresentationCore.dll"); ``` I get a **FileNotFoundException**. [Another answer on SO](https://stackoverflow.com/questions/283419/how-to-just-load-the-latest-version-of-dll-from-gac/283880#283880) suggested I used Assembly.LoadFrom() to accomplish this - I'm hesitant to do that because Assembly.LoadFrom() is deprecated, according to Visual Studio 2008 - plus, it doesn't seem to actually work. Any ideas?
If the assembly is in the GAC you must load it via its fully qualified name. For example, if I wanted to load `mscorlib.dll` I would do something like this: ``` Assembly a = Assembly.Load ("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); ``` The easiest way to determine an assembly's fully qualified name is to load the assembly in [Reflector](http://www.red-gate.com/products/reflector/) and use the **Name** field from the lower display pane like this: [![](https://i.stack.imgur.com/nNzw0.png)](https://i.stack.imgur.com/nNzw0.png)
You need to pass the name of the assembly to `Assembly.Load()`, not the name of the DLL. If you open the DLL in Reflector, the name should be at the bottom of the window. In the case of PresentationCore.dll, the name should be something like `PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35`.
How would I load an assembly from the GAC?
[ "", "c#", ".net-3.5", "" ]
While a send() succeeds with all data being sent most of the time, it is not always the case. Thus people are advised to use the write-fdset for select() and poll() to check when the socket is writeable. How do usual mechanisms look like to actually buffer the data to send while still maintaining a well comprehensible sourcecode?
As we're in C++ land, you could store the data in a std::vector New data gets appended to the end of the vector. When you get notification that the socket is writable, try to send the complete vector. send() will return how much was really sent. Then simply erase that number of bytes from the beginning of the vector: ``` std::vector<char> buffer; ... if( ! buffer.empty() ) { int bytesRead = send( socket, &buffer[ 0 ], buffer.size(), flags ); if( bytesRead > 0 ) buffer.erase( 0, bytesRead ); else // some error... } ``` So there's probably more error checking to do, but you get the idea? Rather queueing each individual send request, the advantage here is that you get to potentially combine multiple higher level sends into one socket send, assuming you're using TCP? But as Remus quite rightly mentions, your flow control and API is the tricky bit - i.e. how do you stop the buffer becoming too big?
I'm not deeply familiar with the \*nix side of socket programming, but I encountered the same problem on Win32 side. Buffering is not so much of a problem (you queue the requests and peek on write completion to submit next from queue), the real problem is that the need to buffer signals that you're actually handling flow control and you cannot resolve flow-control with buffering alone: there can always be a consumer slower than the producer and the buffer will basically grow out of control. You have to propagate the flow control up the stream to whatever module is producing the data, and this makes really complex interfaces. All 'write' requests must support return codes indicating flow control status (ie. 'stop writing, there is no more space!') and callbacks to invite the caller to resume write operations.
How to buffer data for send() and select()?
[ "", "c++", "sockets", "select", "asynchronous", "" ]
I need to select all items in a ListBox when a CheckBox is clicked. Is it possible to select all items in the ListBox using a single line of code? Or will I have to loop through all items and set selected to true for each one of them?
I think you have to loop here. Selecting all items at once is a pretty specific (and probably rare) use case where it simply makes no sense to offer that functionality out of the box. Furthermore, the loop will be just two lines of code anyway.
The fact is that `ListBox.Items` is a plain object collection and returns plain untyped objects, which cannot be multi-selected (by default). If you want to multi-select all items, then this will work: ``` for (int i = 0; i < myListBox.Items.Count;i++) { myListBox.SetSelected(i, true); } ```
How do I select all items in a listbox on checkbox checked?
[ "", "c#", "winforms", "listbox", ".net-2.0", "" ]
I have this piece of code (from the Nokia PC connectivity 3.2 example code, in C#): ``` DAContentAccessDefinitions.CA_FOLDER_INFO folderInfo = new DAContentAccessDefinitions.CA_FOLDER_INFO(); folderInfo.iSize = Marshal.SizeOf(folderInfo); //(32) IntPtr bufItem = Marshal.AllocHGlobal(folderInfo.iSize); //I often get a AccessViolationException on the following line Marshal.StructureToPtr(folderInfo, bufItem, true); ``` If I run `GC.Collect()` at the start of this, then I don't get an `AccessViolationException`. But I don't want to slow down this function unless necessary. I've tried putting `GC.Keepalive` in various places, but without success. `CA_FOLDER_INFO` is defined as: ``` [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct CA_FOLDER_INFO { public int iSize; public int iFolderId; public int iOptions; public string pstrName; public string pstrPath; public int iSubFolderCount; public IntPtr pSubFolders; public IntPtr pParent; } ``` I don't, in this instance, require either of the strings, and changing their definitions to `IntPtr` seems to make the exception go away. What is going on here, and what is the correct way to prevent the exception?
Your problem is that you're passing true to Marshal.StructureToPtr so it attempts to free the two string pointers (which are sometimes invalid). You need to pass false in this instance since you just allocated that memory on the heap. (i.e. there's nothing to free there).
Use the fixed keyword to get a pointer to your original `folderInfo`.
Running a 'GC.Collect' fixes my crash, but I don't understand why
[ "", "c#", "unmanaged", "nokia", "" ]
I want to show an AlertDialog with one option that might change on every request. So for example at one time I want to show the option "add to contacts" while another time it should be "remove from contacts". My code does work on the first time, however Android seems to cache the AlertDialog so that onCreateDialog is not executed next time. Therefore the option doesnt change anymore. Can I prevent this caching, or is there just another way of changing the option? **I am working with SDK 1.5 but using 1.1.** ``` @Override protected Dialog onCreateDialog(final int id) { ... String add_remove_contact = res.getString(R.string.profile_add_to_contacts); if (user.getContacts().contains(profileID)) { add_remove_contact = res.getString(R.string.profile_remove_from_contacts); // TODO: this string is not changed when contact status changes } final CharSequence[] items = {res.getString(R.string.view_profile), res.getString(R.string.profile_send_message), add_remove_contact}; AlertDialog.Builder builder = new AlertDialog.Builder(this); ... return builder.create(); } ```
You can also use the **removeDialog(int)** function of the Activity. When a dialog is dismissed, the Activity basically stores the state of the dialog (for performance reasons I would imagine). Calling **removeDialog(int)** on the dialog forces the activity to unload all references for the dialog and dismisses it from the screen if it's being shown. [Creating Dialogs](http://developer.android.com/guide/topics/ui/dialogs.html) [Activity#removeDialog(int)](http://developer.android.com/reference/android/app/Activity.html#removeDialog(int))
Take a look at [onPrepareDialog](http://developer.android.com/reference/android/app/Activity.html#onPrepareDialog(int,%20android.app.Dialog)) method that will be called before dialog is shown. There You can change the required values based on request type. **Example with date picker** ``` @Override protected Dialog onCreateDialog(final int id) { switch (id) { case DIALOG_DATE_ID: final Calendar c = Calendar.getInstance(); return new DatePickerDialog(this, this, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); default: return super.onCreateDialog(id); } } @Override protected void onPrepareDialog(final int id, final Dialog dialog) { switch (id) { case DIALOG_DATE_ID: //update to current time final Calendar c = Calendar.getInstance(); ((DatePickerDialog) dialog).updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); break; } } ```
Android AlertDialog with dynamically changing text on every request
[ "", "java", "android", "android-alertdialog", "" ]
I'm working on a project where certain objects are referenced counted -- it's a very similar setup to COM. Anyway, our project does have smart pointers that alleviate the need to explicitly call Add() and Release() for these objects. The problem is that sometimes, developers are still calling Release() with the smart pointer. What I'm looking for is a way to have calling Release() from the smart pointer create a compile-time or run-time error. Compile-time doesn't seem possible to me. I thought I had a run-time solution (see code below), but it doesn't quite compile either. Apparently, implicit conversion isn't allowed after using operator->(). Anyway, can anyone think of a way to accomplish what I'm trying to accomplish? Many thanks for your help! Kevin ``` #include <iostream> #include <cassert> using namespace std; class A { public: void Add() { cout << "A::Add" << endl; } void Release() { cout << "A::Release" << endl; } void Foo() { cout << "A::Foo" << endl; } }; template <class T> class MySmartPtrHelper { T* m_t; public: MySmartPtrHelper(T* _t) : m_t(_t) { m_t->Add(); } ~MySmartPtrHelper() { m_t->Release(); } operator T&() { return *m_t; } void Add() { cout << "MySmartPtrHelper::Add()" << endl; assert(false); } void Release() { cout << "MySmartPtrHelper::Release()" << endl; assert(false); } }; template <class T> class MySmartPtr { MySmartPtrHelper<T> m_helper; public: MySmartPtr(T* _pT) : m_helper(_pT) { } MySmartPtrHelper<T>* operator->() { return &m_helper; } }; int main() { A a; MySmartPtr<A> pA(&a); pA->Foo(); // this currently fails to compile. The compiler // complains that MySmartPtrHelper::Foo() doesn't exist. //pA->Release(); // this will correctly assert if uncommented. return 0; } ```
You can't do it - once you've overloaded the `operator ->` you're stuck - the overloaded operator will behave the same way reardless of what is rightwards of it. You could declare the Add() and Release() methods private and make the smart pointer a friend of the reference-counting class.
`operator->` has to return a pointer or an object which itself supports `operator->`. It can be recursive. What you can't do is to have `operator->` behave differently based on what appears on the right hand side of the `->`. I can't think of any approach that doesn't involve somehow replicating the interfaces of your pointed-to objects, or require you to create objects publicly derived from your pointed to objects with Add and Release hidden and made private in the derived class and using a `Base* pBase = pDerived; pBase->Add();` trick to call add and release from the smart pointer.
Can smart pointers selectively hide or re-direct function calls to the objects they are wrapping?
[ "", "c++", "operator-overloading", "overloading", "smart-pointers", "" ]
I have the unfortunate task of cleaning up a bunch of old ColdFusion code. Queries are all over the place, I am working on moving them all to common CFCs for easier maintenance. I am running into a problem because `cfquery` is automatically converting the single quotes to double-single-quotes. How can I override that behavior? More specific information is below. --- So here is the query I started with: ``` <cfquery name="getObjectInfo" datasource="#BaseDS#"> SELECT groupName AS lastname, '[Group]' AS firstname FROM groups WHERE groups.group_id = #objectreference_id# </cfquery> ``` The weird thing here is that a literal is being "selected", because of the way we want it displayed (again, I didn't write this, I'm just trying to clean it up a little). So in the common function, there is an optional parameter for the select clause: ``` <cffunction name="fSelGroup" access="public" returntype="query" hint="Returns query selecting given group."> <cfargument name="intGroupID" type="numeric" required="true" hint="ID of group to be returned." /> <cfargument name="strSelectAttributes" type="string" required="false" hint="Attributes to be selected in query" default="*" /> <cfquery name="getObjectInfo" datasource="#Application.DataSource#"> SELECT #Arguments.strSelectAttributes# FROM Groups WHERE Group_ID = #Arguments.intGroupID# </cfquery> <cfreturn getObjectInfo /> </cffunction> ``` **Here is the problem**: When I pass in `"GroupName AS LastName, '[Group]' AS FirstName"` for the strSelectAttributes parameter, the query that is sent to the database is: ``` SELECT GroupName AS LastName, ''[Group]'' AS FirstName FROM Groups WHERE Group_ID = 4 ``` You see, my quotes got "sanitized" into an invalid query.
ColdFusion does not escape *all* single quotes, but only those that arrive in the query through variable interpolation. This is the offender: ``` SELECT #Arguments.strSelectAttributes# ``` This is usually a helpful thing and a small line of defense against SQL injection attacks. So rule number one is (here and everywhere else): Don't build your SQL string from variables. If you *positively have to* use variables to build an SQL string, despite all the possible negative effects, use the `PreserveSingleQuotes()` function: ``` SELECT #PreserveSingleQuotes(Arguments.strSelectAttributes)# ``` This function stops ColdFusion from auto-escaping the single quotes. And any other function call does the same thing, by the way. Try: ``` SELECT #LCase(Arguments.strSelectAttributes)# ``` which means that PreserveSingleQuotes() is really just a no-op that turns a string into a function result, preventing the automatic variable interpolation routine from happening.
Put a call to preserveSingleQuotes() around your variable. It's made specifically for writing dynamic SQL. Also, you really, really should use cfqueryparam for your values, and I hope you're sanitizing your input somehow so that arguments.strSelectAttributes can't contain something like ';drop table groups; in it. ``` <cfquery name="getObjectInfo" datasource="#Application.DataSource#"> SELECT #preserveSingleQuotes(Arguments.strSelectAttributes)# FROM Groups WHERE Group_ID = <cfqueryparam value="#Arguments.intGroupID#" cfsqltype="cf_sql_integer"/> </cfquery> ```
How to override SQL sanitization in ColdFusion
[ "", "sql", "coldfusion", "sanitization", "cfquery", "" ]
In the following code I am trouble with my injected EnitityManager, which **always shows up as null**; ``` public class GenericController extends AbstractController { @PersistenceContext(unitName = "GenericPU") private EntityManager em; protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { //(em == null) is always trigged if (em == null) throw new NullPointerException("em is null"); Collection<Generic> Generics = em.createNamedQuery("Generic.findAll").getResultList(); ModelAndView mav = new ModelAndView("Generic"); mav.addObject(Generics); return mav; } } ``` Here is the bean definition, defined in *dispatcher-servlet.xml*. ``` <bean id="Generic" class="com.application.web.GenericController" /> ``` EnitityManager should be injected based on tx:annotation-based, defined in the *persistence-context.xml* file. ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="url" value="removed" /> <property name="username" value="removed" /> <property name="password" value="removed" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="GenericPU" /> <property name="dataSource" ref="dataSource" /> <property name="jpaDialect"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /> </property> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="generateDdl" value="false" /> <property name="databasePlatform" value="org.hibernate.dialect.SQLServerDialect" /> </bean> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> </beans> ``` The persistence-context is loaded from the *applicationContext.xml* ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <import resource="classpath:META-INF/persistence-context.xml"/> </beans> ``` The classpath import is done because the ORM entities are included as a JAR file into the project. Note that I believe the persistence-context is being loaded, as Spring will not allow the application to be deployed if it can't parse its configuration files. Here is my *persistence.xml*. ``` <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="CoolOrmJpaPU" transaction-type="RESOURCE_LOCAL"> <class>com.application.orm.jpa.Generic</class> <!-- bunch more classes --> </persistence-unit> </persistence> ``` And my *web.xml* ``` <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>redirect.jsp</welcome-file> </welcome-file-list> </web-app> ``` Can anyone help me out here?
I was lucky enough today to be able to speak with a consultant about this issue, he was able to help me sort the whole thing out. So my problem is that Spring MVC was establishing **two distinct contexts**, one application context, defined in applicationContext.xml and one web context, defined in dispatcher-servlet.xml. Beans from one context can not talk to beans in another context, thus when I initilized my persistence context inside of applicationContext.xml, I could not access it in beans loaded by dispatcher-servlet.xml, ie my controllers. When Netbeans auto-generated the base to my Spring MVC it set this up by default. In some large web applications, it would make sense to separate the web part of the application in a context distinct from the rest of the logic (persistence, business code, etc). In my case, where I am trying to auto inject my entity manager directly into my controllers, this worked against me. To fix the issue I moved the line ``` <import resource="classpath:META-INF/persistence-context.xml"/> ``` From the applicationContext.xml, to my dispatcher-servlet.xml. My controllers then were properly injected with EntityManagers from the @PersistanceContext annotation.
Have you included ``` <context:annotation-config /> ``` In your spring XML. Reference [here](http://static.springframework.org/spring/docs/2.5.x/reference/xsd-config.html#xsd-config-body-schemas-context)
Fixing Null EntityManger in Spring MVC application?
[ "", "java", "spring", "jpa", "spring-mvc", "entitymanager", "" ]
I'm in the process of creating a blog for somebody. They want to pull in a lot of data and integrate it quite tightly into the design, so standard widgets are a no-no. That's been fine until now. They have a public access Google Calendar with various events on it and I want to grab the next 5 events (from "now" onwards) and display the event title, when that instance of the event starts, its location and a link to the gcal item. From what I can see, there are three options for grabbing gcal feeds: XML, ical or HTML (containing some really whack JSON). XML seems like the logical choice, right? Well the XML feed is (after the atom feed description) actually just a lot of faffy HTML. Parsing this is possible but it's a huge pain in the behind because recurring events (of which there are several on the calendar) only show the first instance of that event and (apparently) no information on when the next instance is. So am I just being a bit dense? Is there a way to show what I want just hacking through the XML API? Or would I have better luck through iCal? I've never done any iCal with PHP so if you have, please suggest any libs you've used to make things simpler for yourself. **Edit:** thanks to the answer, I downloaded the Zend Gdata pack (which, thankfully, *is* separate to the rest of the Zend Framework). Doing what I need was as easy as this: ``` require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Gdata_HttpClient'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); $service = new Zend_Gdata_Calendar(); $query = $service->newEventQuery(); $query->setUser('your_user@googlemail.com'); $query->setVisibility('public'); $query->setProjection('full'); $query->setStartMin(date('Y-n-j')); $query->setStartMax(date('Y-n-j', time() + (60*60 *24*8))); $query->setOrderby('starttime'); try { $eventFeed = $service->getCalendarEventFeed($query); } catch (Zend_Gdata_App_Exception $e) { return; } foreach ($eventFeed as $event) echo $event; // do something real here ``` That should get you a week's worth of events (yes setStartMax is exclusive so setting it 8 days in the future is required). Hope this helps somebody else in the future.
Another option is to use the Zend Google Calendar library, it is a separate part of the zend framework so you don't need the whole zend framework <http://framework.zend.com/manual/en/zend.gdata.calendar.html> it is not that hard once you have a look at the examples.
In case it helps anyone else, I figured out how to get calendars other than the default. If you go into your google calendar and look up calendar settings, at the bottom there is a calendar ID that is formatted like a really long email address.(example: adg5jcq8gk7lsp6rrbmrm8c@group.calendar.google.com) Use that with $query->setUser() to use that specific calendar.
Getting Google Calendar events in PHP
[ "", "php", "xml", "google-calendar-api", "icalendar", "atom-feed", "" ]
I have the following problem: I've deployed in Tomcat a JNLP and an executable JAR files. JNLP file should automatically download the JAR file and execute it. The JAR file is signed and verified. This is done (the downloading part). But when to execute the JAR main class (specified in the JNLP file), a problem occurs: A part of the main class code is executed. Afterwards, when it tries to load a class that has a static final org.apache.log4j.Logger instance declared, it says an error. Below are the representative parts of the JNLP file, the code and the error. **JNLP** ``` <?xml version='1.0' encoding='UTF-8'?> <jnlp spec="1.5+" codebase="http://localhost:8080/examples" href="DemoInstaller.jnlp" download="eager" main="true"> <information> <title>Demo Installer</title> <vendor>Codemart [www.codemart.ro]</vendor> <homepage>https://sourceforge.net/projects/cminstall/</homepage> <description>This is a demo installer built using Codemart Installer framework with JavaFX</description> <description kind="tooltip">Codemart Demo Installer</description> <offline-allowed /> <shortcut online="true"> <desktop /> </shortcut> </information> <security> <all-permissions /> </security> <update check="background" /> <resources> <j2se href="http://java.sun.com/products/autodl/j2se" version="1.6+" /> <jar href="DemoInstaller.jar" main="true" download="eager" /> </resources> <application-desc main-class="ro.codemart.installer.packer.ant.impl.nestedjar.Main" /> ``` **The main class:** ``` public class Main { public static void main(String[] args) throws Exception { final Main main = new Main(); //this is the problem class ! Class clazz = Class.forName("WizardRunner"); Method m = clazz.getMethod("main", new Class[]{args.getClass()}); m.invoke(null, new Object[]{args}); ... } } ``` **And the problem class:** ``` public class WizardRunner{ private final static Logger log = Logger.getLogger(WizardRunner.class); ... } ``` **And the error:** log4j:ERROR Could not find [log4j.dtd]. Used [sun.misc.Launcher$AppClassLoader@d9f9c3] class loader in the search. log4j:ERROR Could not parse url [jar:<http://localhost:8080/examples/DemoJar.jar!/log4j.xml]>. java.io.FileNotFoundException: JAR entry log4j.dtd not found in at com.sun.jnlp.JNLPCachedJarURLConnection.connect(Unknown Source) at com.sun.jnlp.JNLPCachedJarURLConnection.getInputStream(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) at org.apache.log4j.xml.DOMConfigurator$2.parse(DOMConfigurator.java:612) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:711) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:618) at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:470) at org.apache.log4j.LogManager.(LogManager.java:122) at org.apache.log4j.Logger.getLogger(Logger.java:117) at ro.codemart.installer.wizard.WizardRunner.(WizardRunner.java:38) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at ro.codemart.installer.packer.ant.impl.nestedjar.Main.executeApplicationMainClass(Main.java:216) at ro.codemart.installer.packer.ant.impl.nestedjar.Main.main(Main.java:290) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.javaws.Launcher.executeApplication(Unknown Source) at com.sun.javaws.Launcher.executeMainClass(Unknown Source) at com.sun.javaws.Launcher.doLaunchApp(Unknown Source) at com.sun.javaws.Launcher.run(Unknown Source) at java.lang.Thread.run(Unknown Source) log4j:WARN No appenders could be found for logger (WizardRunner). log4j:WARN Please initialize the log4j system properly. Thank you!
I think the problem is missing log4j.jar - it's not specified or loaded by the .jnlp file. You mentioned in the previous answer that it's in your classpath, but how if you're running via WebStart? I believe your classpath is limited to what's defined in the .jnlp file. Try adding ``` <jar href="log4j.jar" main="true" download="eager" /> ``` to ``` <resources> ```
Yes, the **log4j.dtd** file comes embedded with **log4j-1.2.12.jar**. Also this log4j jar is in the classpath.
Why does my Jnlp program not working with log4j?
[ "", "java", "log4j", "jnlp", "" ]
This are my first two lines: ``` <?php header('Content-Type: application/x-javascript'); ``` And it gives me the headers already sent in line 1. It is intended to generate a JavaScript file that loads from an HTML page, when checked the JavaScript file from Firebug i got the following file: ``` 1 <br /> 2 <b>Warning</b>: Cannot modify header information - headers already sent by (output started at C:\Program Files\Apache Group\Apache2\htdocs\totoro\Js\libs.php:1) in <b>C:\Program Files\Apache Group\Apache2\htdocs\totoro\Js\libs.php</b> on line <b>1</b><br /> 3 var Totoro = {}, $t = Totoro; ``` As you can see, it spits a character that looks like garbage characters, but nothing is sended, the first line is a `header` function call. What might be the problem?
You have most probably saved the file as UTF-8 with [BOM](http://en.wikipedia.org/wiki/Byte-order_mark) (Byte-order mark), resave it as UTF-8 without said thingy.
This character sequence is the [UTF-8 BOM](http://en.wikipedia.org/wiki/Byte-order_mark#Representations_of_byte_order_marks_by_encoding). When using UTF-8, save your files without BOM (sometimes also called signature). Additionally you should declare the encoding you’re using. Because as the UTF-8 BOM is shown as the characters you named, your data is probably interpreted with ISO 8859-1, as the UTF-8 BOM byte sequence 0xEFBBBF represents the characters `ï` (0xEF), `»` (0xBB) and `¿` (0xBF) in ISO 8859-1. So remove the BOM and use this `Content-Type` header field along with the correct MIME type `application/javascript` and `charset` parameter: ``` Content-Type: application/javascript;charset=utf-8 ```
php script can't send headers because headers have already been sent, but are characters outside the script
[ "", "php", "header", "" ]
Can you create an index on a table variable in SQL Server 2000? i.e. ``` DECLARE @TEMPTABLE TABLE ( [ID] [int] NOT NULL PRIMARY KEY ,[Name] [nvarchar] (255) COLLATE DATABASE_DEFAULT NULL ) ``` Can I create an index on `Name`?
The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first. **SQL Server 2014** In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations. Example syntax for that is below. ``` /*SQL Server 2014+ compatible inline index syntax*/ DECLARE @T TABLE ( C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/ C2 INT INDEX IX2 NONCLUSTERED, INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/ ); ``` Filtered indexes and indexes with included columns can not currently be declared with this syntax however **SQL Server 2016** relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it *may* be the case that included columns are also allowed but the current position is that they ["will likely not make it into SQL16 due to resource constraints"](https://connect.microsoft.com/SQLServer/Feedback/Details/2079552) ``` /*SQL Server 2016 allows filtered indexes*/ DECLARE @T TABLE ( c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/ ) ``` --- **SQL Server 2000 - 2012** > Can I create a index on Name? Short answer: Yes. ``` DECLARE @TEMPTABLE TABLE ( [ID] [INT] NOT NULL PRIMARY KEY, [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL, UNIQUE NONCLUSTERED ([Name], [ID]) ) ``` A more detailed answer is below. Traditional tables in SQL Server can either have a clustered index or are structured as [heaps](http://msdn.microsoft.com/en-us/library/hh213609.aspx). Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a [uniqueifier](http://msdn.microsoft.com/en-us/library/ms190639%28v=sql.105%29.aspx) to any duplicate keys to make them unique. Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server [adds the row locator](http://sqlblog.com/blogs/kalen_delaney/archive/2010/03/07/more-about-nonclustered-index-keys.aspx) (clustered index key or [RID](http://technet.microsoft.com/en-us/library/ms190696%28v=sql.105%29.aspx) for a heap) to all index keys (not just duplicates) this again ensures they are unique. In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a `UNIQUE` or `PRIMARY KEY` constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of `NULL`s is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints. Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the `PRIMARY KEY` will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying `CLUSTERED` or `NONCLUSTERED` explicitly with the constraint declaration (Example syntax) ``` DECLARE @T TABLE ( A INT NULL UNIQUE CLUSTERED, B INT NOT NULL PRIMARY KEY NONCLUSTERED ) ``` As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012. ``` +-------------------------------------+-------------------------------------+ | Index Type | Can be created on a table variable? | +-------------------------------------+-------------------------------------+ | Unique Clustered Index | Yes | | Nonunique Clustered Index | | | Unique NCI on a heap | Yes | | Non Unique NCI on a heap | | | Unique NCI on a clustered index | Yes | | Non Unique NCI on a clustered index | Yes | +-------------------------------------+-------------------------------------+ ``` The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the **non unique** non clustered index on `Name` is simulated by a **unique** index on `Name,Id` (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway). A non unique clustered index can also be achieved by manually adding an `IDENTITY` column to act as a uniqueifier. ``` DECLARE @T TABLE ( A INT NULL, B INT NULL, C INT NULL, Uniqueifier INT NOT NULL IDENTITY(1,1), UNIQUE CLUSTERED (A,Uniqueifier) ) ``` But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.
It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: <https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386> Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table. The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table. To avoid name clashes, something like this usually works: ``` declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);'; exec (@cmd); ``` This insures the name is always unique even between simultaneous executions of the same procedure.
Creating an index on a table variable
[ "", "sql", "sql-server", "t-sql", "indexing", "table-variable", "" ]