Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
## Why is :memory: in sqlite so slow? I've been trying to see if there are any performance improvements gained by using in-memory sqlite vs. disk based sqlite. Basically I'd like to trade startup time and memory to get extremely rapid queries which do *not* hit disk during the course of the application. However, the following benchmark gives me only a factor of 1.5X in improved speed. Here, I'm generating 1M rows of random data and loading it into both a disk and memory based version of the same table. I then run random queries on both dbs, returning sets of size approx 300k. I expected the memory based version to be considerably faster, but as mentioned I'm only getting 1.5X speedups. I experimented with several other sizes of dbs and query sets; the advantage of :memory: *does* seem to go up as the number of rows in the db increases. I'm not sure why the advantage is so small, though I had a few hypotheses: * the table used isn't big enough (in rows) to make :memory: a huge winner * more joins/tables would make the :memory: advantage more apparent * there is some kind of caching going on at the connection or OS level such that the previous results are accessible somehow, corrupting the benchmark * there is some kind of hidden disk access going on that I'm not seeing (I haven't tried lsof yet, but I did turn off the PRAGMAs for journaling) Am I doing something wrong here? Any thoughts on why :memory: isn't producing nearly instant lookups? Here's the benchmark: ``` ==> sqlite_memory_vs_disk_benchmark.py <== #!/usr/bin/env python """Attempt to see whether :memory: offers significant performance benefits. """ import os import time import sqlite3 import numpy as np def load_mat(conn,mat): c = conn.cursor() #Try to avoid hitting disk, trading safety for speed. #http://stackoverflow.com/questions/304393 c.execute('PRAGMA temp_store=MEMORY;') c.execute('PRAGMA journal_mode=MEMORY;') # Make a demo table c.execute('create table if not exists demo (id1 int, id2 int, val real);') c.execute('create index id1_index on demo (id1);') c.execute('create index id2_index on demo (id2);') for row in mat: c.execute('insert into demo values(?,?,?);', (row[0],row[1],row[2])) conn.commit() def querytime(conn,query): start = time.time() foo = conn.execute(query).fetchall() diff = time.time() - start return diff #1) Build some fake data with 3 columns: int, int, float nn = 1000000 #numrows cmax = 700 #num uniques in 1st col gmax = 5000 #num uniques in 2nd col mat = np.zeros((nn,3),dtype='object') mat[:,0] = np.random.randint(0,cmax,nn) mat[:,1] = np.random.randint(0,gmax,nn) mat[:,2] = np.random.uniform(0,1,nn) #2) Load it into both dbs & build indices try: os.unlink('foo.sqlite') except OSError: pass conn_mem = sqlite3.connect(":memory:") conn_disk = sqlite3.connect('foo.sqlite') load_mat(conn_mem,mat) load_mat(conn_disk,mat) del mat #3) Execute a series of random queries and see how long it takes each of these numqs = 10 numqrows = 300000 #max number of ids of each kind results = np.zeros((numqs,3)) for qq in range(numqs): qsize = np.random.randint(1,numqrows,1) id1a = np.sort(np.random.permutation(np.arange(cmax))[0:qsize]) #ensure uniqueness of ids queried id2a = np.sort(np.random.permutation(np.arange(gmax))[0:qsize]) id1s = ','.join([str(xx) for xx in id1a]) id2s = ','.join([str(xx) for xx in id2a]) query = 'select * from demo where id1 in (%s) AND id2 in (%s);' % (id1s,id2s) results[qq,0] = round(querytime(conn_disk,query),4) results[qq,1] = round(querytime(conn_mem,query),4) results[qq,2] = int(qsize) #4) Now look at the results print " disk | memory | qsize" print "-----------------------" for row in results: print "%.4f | %.4f | %d" % (row[0],row[1],row[2]) ``` Here's the results. Note that disk takes about 1.5X as long as memory for a fairly wide range of query sizes. ``` [ramanujan:~]$python -OO sqlite_memory_vs_disk_clean.py disk | memory | qsize ----------------------- 9.0332 | 6.8100 | 12630 9.0905 | 6.6953 | 5894 9.0078 | 6.8384 | 17798 9.1179 | 6.7673 | 60850 9.0629 | 6.8355 | 94854 8.9688 | 6.8093 | 17940 9.0785 | 6.6993 | 58003 9.0309 | 6.8257 | 85663 9.1423 | 6.7411 | 66047 9.1814 | 6.9794 | 11345 ``` Shouldn't RAM be almost instant relative to disk? What's going wrong here? ## Edit Some good suggestions here. I guess the main takehome point for me is that \*\*there's probably no way to make :memory: *absolutely faster*, but there is a way to make disk access *relatively slower.* \*\* In other words, the benchmark is adequately measuring the realistic performance of memory, but not the realistic performance of disk (e.g. because the cache\_size pragma is too big or because I'm not doing writes). I'll mess around with those parameters and post my findings when I get a chance. That said, if there is anyone who thinks I can squeeze some more speed out of the in-memory db (other than by jacking up the cache\_size and default\_cache\_size, which I will do), I'm all ears...
It has to do with the fact that SQLite has a page cache. According to the [Documentation](http://www.sqlite.org/compile.html), the default page cache is 2000 1K pages or about 2Mb. Since this is about 75% to 90% of your data, it isn't surprising that the two number are very similar. My guess is that in addition to the SQLite page cache, the rest of the data is still in the OS disk cache. If you got SQLite to flush the page cache (and the disk cache) you would see some really significant differences.
My question to you is, What are you trying to benchmark? As already mentioned, SQLite's :memory: DB is just the same as the disk-based one, i.e. paged, and the only difference is that the pages are never written to disk. So the only difference between the two are the disk writes :memory: doesn't need to do (it also doesn't need to do any disk reads either, when a disk page had to be offloaded from the cache). But read/writes from the cache may represent only a fraction of the query processing time, depending on the query. Your query has a where clause with two large sets of ids the selected rows must be members of, which is expensive. As Cary Millsap demonstrates in his blog on optimizing Oracle (here's a representative post: <http://carymillsap.blogspot.com/2009/06/profiling-with-my-boy.html>), you need to understand which parts of the query processing take time. Assuming the set membership tests represented 90% of the query time, and the disk-based IO 10%, going to :memory: saves only those 10%. That's an extreme example unlikely to be representative, but I hope that it illustrates that your particular query is slanting the results. Use a simpler query, and the IO parts of the query processing will increase, and thus the benefit of :memory:. As a final note, we've experimented with SQLite's virtual tables, where you are in charge of the actual storage, and by using C++ containers, which are typed unlike SQLite's way of storing cell values, we could see a significant improment in processing time over :memory:, but that's getting of topic a bit ;) --DD PS: I haven't enough Karma to comment on the most popular post of this thread, so I'm commenting here :) to say that recent SQLite version don't use 1KB pages by default on Windows: <http://www.sqlite.org/changes.html#version_3_6_12>
SQLite Performance Benchmark -- why is :memory: so slow...only 1.5X as fast as disk?
[ "", "python", "database", "sqlite", "memory", "benchmarking", "" ]
I am thinking i might want to port a lib to read a DVD filesystem. I am not talking about movies but datadisc. Theres existing code for me to do raw reads from the disc. I need code that request this data and allow me to browse files on the disc. What lib can i use for this? -edit- NOTE: I am using an OSless hardware. Ppl seem to miss that but Alnitak caught it and gave me a great answer :)
You need `libudf` which is part of GNU [`libcdio`](http://www.gnu.org/software/libcdio/).
If you want to browse files, why not let your operating system do the heavy lifting? Given that a modern OS will already have everything it needs to mount filesystems from DVDs -- and that there will be numerous people already using and debugging this code, as opposed to a smaller and more focused userbase for a userspace library such as libdvdread -- it seems silly not to leverage them.
lib to read a DVD FS (data disc)
[ "", "c++", "hardware", "io", "disk", "dvd", "" ]
I have used a prototype plugin which filters the contents of a dropdown as you type. So for example if you typed 'cat' into the text box, only items containing the substring 'cat' would be left as options in the drop down. Does anyone know of a jquery plugin which can do this?
I wrote [a little script to do this](http://andrew.hedges.name/experiments/narrowing/) a few years ago. It could be packaged up as a jQuery plug-in quite easily, probably. You're welcome to it. I also do this in my [PHP Function Reference](http://andrew.hedges.name/widgets/#phpfr) Dashboard widget if you want to look at the code there.
I was just looking for something similar, and the best one for what I need seems to be the [JQuery UI MultiSelect](http://www.quasipartikel.at/multiselect/). It turns Multi-select boxes into a pretty slick dual-list view, with live filtering on the master list. **EDIT: New Development!** > "[Chosen](http://harvesthq.github.com/chosen/) is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors." I'm totally using [Chosen](http://harvesthq.github.com/chosen/) on all select-using projects in the foreseeable future.
Jquery: Filter dropdown list as you type
[ "", "javascript", "jquery", "jquery-plugins", "" ]
I'm doing a query to the Alexa API which, for some unknown reason, will occasionally fail. When it does fail, I want to automatically retry the query, up to 10 times. When it fails, the response returned by the API contains the substring `AuthFailure`. What kind of loop can I do that will retry the query until either the response returned does not contain the substring `AuthFailure` or 10 retries have been attempted?
You could do this with a `for` loop. ``` for($i=0; $i < 10; $i++) { $return = (Alexa call here) if(!strstr($return,"AuthFailure")) break; } ``` Adjust 10 to whatever number you wish. Better yet, use a constant `define()`'ed elsewhere. This will run until the number of tries is exhausted or until the return value does not contain "AuthFailure".
I'd do something like this: ``` define('ALEXA_FAILED', 'AuthFailure'); $response = ALEXA_FAILED; $tries = 0; while ($tries <= 10 && stripos($response, ALEXA_FAILED) !== FALSE) { $response = GetAlexaResponse(); $tries++; } ```
PHP: Retrying a query a set number of times or until success
[ "", "php", "loops", "" ]
I am trying to understand Iterability in Python. As I understand, `__iter__()` should return an object that has `next()` method defined which must return a value or raise `StopIteration` exception. Thus I wrote this class which satisfies both these conditions. But it doesn't seem to work. What is wrong? ``` class Iterator: def __init__(self): self.i = 1 def __iter__(self): return self def next(self): if self.i < 5: return self.i else: raise StopIteration if __name__ == __main__: ai = Iterator() b = [i for i in ai] print b ```
Your current code seems to work. Instead i'll show you some more iterators/generators. the simplest builtin with exactly your behavior. ``` Iterator2 = xrange(2,5) ``` A direct translation of your class to a generator ``` def Iterator3(): i = 1 while i < 5: i += 1 yield i ``` a generator composed from generators in the python standard library ``` import itertools Iterator4 = itertools.takewhile( lambda y : y < 5, itertools.count(2) ) ``` a simple generator expression (not very exciting...) ``` Iterator5 = ( x for x in [2, 3, 4] ) ```
Your Iterator class is correct. You just have a typo in this statement: ``` if __name__ ==' __main__': ``` There's a leading whitespace in the ' \_\_main\_\_' string. That's why your code is not executed at all.
Iterability in Python
[ "", "iterator", "python", "" ]
I am looking at some solutions for building a site with a mix of free and paid/premium content (no, it's not porn). I gather that Drupal has the Premium plugin which supports this. I'm also looking at Expression Engine, which seems to have some built in support for this, although Paypal is the only payment option. I'm looking at aMember (<http://www.amember.com/>) which seems to be a user role package that supports this, supports lots of payment methods, and has plugins to tie in to both Expression Engine and Wordpress. Frankly, I find Drupal very frustrating to work with, so I'm leaning towards EE or Worpress + aMember. Am I missing any other good options? Anyone have experience with any of these packages?
Expression Engine is amazing, and there is tons of support on their forums. I'm sure someone has found a way to use more than just paypal with it, just ask on the forums there and see what they say. But I'd recommend EE
Joomla has been a good CMS for such sites, as we can see social-networking, e-commerce, subscription website, news website, etc Or maybe Data Life Engine (DLE) would suit you (not free)
Recommend PHP/MySQL CMS with paid/premium content support
[ "", "php", "wordpress", "drupal", "content-management-system", "expressionengine", "" ]
I'm trying to figure out what is the smartest way to name private methods and private static methods in C#. Background: I know that the best practice for private members is underscore-prefix + camelcase. You could argue this with me, but trust me I've seen enough code from hardcore pros that follow this convention, it is the skilled industry standard. I also know that pascal case is the industry standard for public methods. But I have seen a combination of test style naming (ie. method\_must\_return\_false\_occasionally ) to pascal case, camelcase, and underscore-prefix + camelcase, for private and private static methods. But what is the best practice style for private and private static method naming in C#? If there are certain styles that are used from some private methods and not others, I can understand that, just explain. Thanks for reading.
Check out the Microsoft's [Naming Guidelines](http://msdn.microsoft.com/en-us/library/xzf533w0%28VS.71%29.aspx) and Brad Abram's [Style Guide](http://blogs.msdn.com/brada/articles/361363.aspx) They say that all methods should be PascalCase ``` public void DoWork() {} private void StillDoWork() {} private static void ContinueToDoWork() {} ```
The [naming guidelines](http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx) for .NET class library development don't distinguish between public and private usage and recommend [Pascal](http://msdn.microsoft.com/en-us/library/x2dbyw72(VS.71).aspx) case for static methods. **EDIT**: My personal practice is to use Pascal casing for methods and properties, camel casing for fields, parameters, and local variables. When referencing instance members from within the class I use `this.` to distinguish from class members and parameters when necessary. I have no idea if I qualify as a "hardcore pro," but I do get paid. :-) **EDIT 2**: Since writing this originally I've changed jobs. The coding standard we follow is different than my personal feelings and we do prefix private fields with underscores. I've also started using ReSharper and our standards (generally) follow the default rules. I find I can easily live with the underscores. I only use `this` when absolutely required as it does not fit our code standards. Consistency trumps personal preference.
What is the best practice for naming private and static private methods in C#?
[ "", "c#", "naming-conventions", "private-methods", "" ]
Suppose we have a class A and class B and C inherit from it. Then we create an array of references to A's, and fill it with B's and C's. Now we decided that we want to eliminate all the C's. Is there a way to check what type each field of the array really holds without doing something redundant like a returnType() function? Edit: fixed "array of A's" to "array of references to A's".
You can't create an array of As and fill it with Bs and Cs - they will be sliced down to As. You can create a n array of pointers to A , wich you can populate with pointers to B and pointers to C. To check the type of something in this situation - use dynamic cast: ``` // create B or C randomly A * a = rand() % 2 ? new B : new C; if ( dynamic_cast <B *> ( a ) ) { // it's a B } else { // it isn't (must be C in this case) } ```
Ideally, you want to figure out what functionality it is that makes you not want the Cs in there. Then add a virtual function that exposes that property. This way when you add class D that also has that same unwanted property, things will continue to behave correctly. ``` class A { public: virtual bool IsFrobbable() { return true; } }; class B : public A { }; class C : public A { public: virtual bool IsFrobbable() { return false; } }; int main() { vector<A *> vA; vA.push_back(new A()); vA.push_back(new B()); vA.push_back(new C()); vA.erase(remove_if(vA.begin(), vA.end(), not1(mem_fun(&A::IsFrobbable)))); // Now go ahead and frob everything that's left } ```
Checking real variable type in polymorphism (C++)
[ "", "c++", "polymorphism", "typechecking", "" ]
What is the nicest way of splitting this: ``` tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') ``` into this: ``` tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')] ``` Assuming that the input always has an even number of values.
`zip()` is your friend: ``` t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') zip(t[::2], t[1::2]) ```
``` [(tuple[a], tuple[a+1]) for a in range(0,len(tuple),2)] ```
Multiple Tuple to Two-Pair Tuple in Python?
[ "", "python", "data-structures", "tuples", "" ]
How can I add multiple paragraph tag, newly tag on top within div container. ``` <div id="pcontainer"> <p>recently added on top every time on click event recently added paragarph on top</p> <p>added before recent</p> </div> ``` I am using append but every time I click button it add to bottom I need it to added on top of all paragraph please help.
You may use [prepend](http://docs.jquery.com/Manipulation/prepend) to add the paragraph at the top of the container: ``` // HTML: <div><p>Lorem ipsum</p></div> $('div').prepend('<p>Bla bla bla'); ``` **Update**: Regarding your comment about how to fade in the paragraph - use [fadeIn](http://docs.jquery.com/Effects/fadeIn#speedcallback): ``` $("#pcontainer").prepend($('<p>This paragraph was added by jQuery.</p>').fadeIn('slow')); ``` A working demo: <http://jsbin.com/uneso>
A more elegant way without jQuery: ``` var container = document.getElementById('pcontainer'); container.insertBefore(document.createElement("p"), container.firstChild); ``` This assumes there is already an element in the container btw.
how to add paragraph on top of div content
[ "", "javascript", "jquery", "dom", "" ]
**What is the best size for an individual tile in a 2D sprite sheet?** I am creating a sprite sheet and am trying to figure out what the best resolution is to use for each sprite. Is there a standard size I shouldn't go above or below? ex. 64px X 64px, 512px X 512px, etc. I am trying to get HD quality sprites. Think Alien Hominid, Castle Crashers, or World of Goo. Some examples would be nice too, so if you have sprite sheet example please upload them.
This depends on how the sprite is going to be rendered, as well as what you are going to do with them when you render them. If you are going to avoid scaling the sprites, making them the same as their final rendered resolution as possible will help keep the quality higher. I would definitely stick to power of two texture sizes, since it does seem to help in general. However, if you're going to be doing a lot of transformations on your sprites, particularly with rotations or scaling, you may want to go slightly larger than the resolution they will render, since the resampling may be slightly better quality. You'll want to consider how many sprites are being composited and displayed at any time, and what hardware you'll be running on (xbox, pc, both?), to determine the best options for balancing performance with texture quality. If you're not going too crazy with the number of sprites, though, you can probably go at a higher quality, and allow the system to downsize them as needed, and get good results.
This may not directly answer your question, but I wanted to throw in what I've learned when using sprite sheets. Sprite sheets are great because the fewer textures that the GPU has to switch between when drawing to the screen, the better performance. I would recommend that you take a look at the [XNA sprite sheet example](http://creators.xna.com/en-US/sample/spritesheet), if you haven't already. It offers a couple great benefits: * It automatically packs your sprites (in different files) into one big texture. I thought keeping my artwork in separate files and having the one giant sprite sheet generated automatically would be better than keeping all my art in one file. For example, what if I decide I want my animations to have an extra frame in the middle? Then I have to shift around a bunch of stuff in the sprite sheet to make room for the new frame. If I'm using one file per frame, it's just a one line change to the XML file listing what goes into the sprite sheet if I want to add a new frame in the middle. It can be a pain to list every frame file separately, so I can see why this may not work for some people, but it was great for my project. Also, I found that the gain of being able to swap textures in and out of my sprite sheet easily was more than worth it, which will help you as you determine what size of sprites to use. * We ran into a [problem](http://christophermpark.blogspot.com/2008_10_01_archive.html) when scaling sprites. I believe that link describes the issue pretty well. In any case, this sprite sheet example will automatically add a 1 pixel border (using the color of the pixel that was originally on the edge) around each sprite you add to the sprite sheet, which will protect you from seeing oddly colored borders around your sprites when scaling, because it still only draws the sprite using the original size. It just uses the extra border for interpolation instead of a nearby sprite's pixels or white space. Reed is correct that there really isn't any standard sprite size you should use. It depends mostly on what type of game you are doing, what type of scaling and rotating you are doing, etc. However, there are specific sizes you need to watch for when using sprite sheets. Sprite sheets are just one giant texture, but there is a limit to how big of a texture GPU's can hold in their memory. The XBOX360 supports up to 4096x4096 (I think) textures. If you're programming for Windows, then it depends on the user's graphics card. From what I've seen, it's probably best to stick with 2048x2048 on Windows, because most graphics cards can support at least that much. One last note on the sprite sheet example. I don't believe that it will watch for a maximum sprite sheet size, so if you do use it, you may want to add a couple lines to catch when the size of the generate texture is larger than you want to support.
Recommend sprite size for games (XNA)?
[ "", "c#", "xna", "" ]
``` package abc; class DependencyDataCollection { private int sNo; private String sessionID; private int noOfDependency; private int noOfRejection; private int totalValue; /** Creates a new instance of DependencyDataCollection */ public DependencyDataCollection(int sNo, String sessionID, int noOfDependency, int noOfRejection, int totalValue) { this.sNo = sNo; this.sessionID = sessionID; this.noOfDependency = noOfDependency; this.noOfRejection = noOfRejection; this.totalValue = totalValue; } public int getSNo() { return sNo; } public String getSessionID() { return sessionID; } public int getNoOfDependency() { return noOfDependency; } public int getNoOfRejection() { return noOfRejection; } public int getTotalValue() { return totalValue; } } public class DependencyStack { LinkedList lList; /** Creates a new instance of DependencyStack */ public DependencyStack() { lList = new LinkedList(); } public void add(int sNo, String sessionID, int noOfDependency, int noOfRejection, int totalValue) { lList.add(new DependencyDataCollection(sNo,sessionID,noOfDependency,noOfRejection,totalValue)); } public int size() { return lList.size(); } public void show() { for(int i=0;i<lList.size();i++) { DependencyDataCollection ddc = (DependencyDataCollection)lList.get(i); System.out.println(ddc.getSNo()+" "+ddc.getSessionID()+" "+ddc.getNoOfDependency()+" "+ddc.getNoOfRejection()+" "+ddc.getTotalValue()); } } public int returnIndexOfSession(String sessionID) { DependencyDataCollection ddc = null; for(int i=0;i<lList.size();i++) { ddc = (DependencyDataCollection)lList.get(i); if(ddc.getSessionID().equals(sessionID)) break; } return ddc.getSNo(); } public static void main(String args[]) { DependencyStack ds = new DependencyStack(); ds.add(1,"a",0,0,0); ds.add(2,"b",0,0,0); ds.show(); //System.out.println(ds.returnIndexOfSession("a")); // DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0); // System.out.println(ds.indexOf(ddc)); } } ``` This is a simple Linked List program in java which is using inbuilt linkedlist class from java.util package. The linked list is used to store different amount of data using DependencyDataCollection Class.. **Now my question is** > 1) Please evaluate this program, > and temme am i respecting all java > concepts like private member > access,which i have done, etc.. > > 2) I am facing problem to find the > indexOf a particular session. > > For e.g. Node 1 contains > 1,"a",0,0,0...............Node 2 > contains 2,"b",0,0,0 > > Now i wanted to find the indexOf the > node which is containing one of the > data as "b" or "a". What could be the shortest inbuilt method which can do so, as i have made a function named "public int returnIndexOfSession(String sessionID)" which makes use of for loop, i find this very time consuming.. Is there any other way out.. Please evaluate and guide as i am a newbie in java.
Here are the changes I would make, rationale is in the comments. ``` import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; class DependencyDataCollection { // makte them fnal, then you hava an immutible object and your code is much safer. // in your case you had noset methods so it was safe, but always try to make things final. private final int sNo; private final String sessionID; private final int noOfDependency; private final int noOfRejection; private final int totalValue; public DependencyDataCollection(final int sNo, final String sessionID, final int noOfDependency, final int noOfRejection, final int totalValue) { this.sNo = sNo; this.sessionID = sessionID; this.noOfDependency = noOfDependency; this.noOfRejection = noOfRejection; this.totalValue = totalValue; } public int getSNo() { return sNo; } public String getSessionID() { return sessionID; } public int getNoOfDependency() { return noOfDependency; } public int getNoOfRejection() { return noOfRejection; } public int getTotalValue() { return totalValue; } } class DependencyStack { // change the type to be as generic as poosible - List interface // added generics so you get compile time safety and don't use casts later on // renamed it to something meaningful private final List<DependencyDataCollection> dependencies; // use an ArrayList instead of a LinkedList, it'll be faster since you are not inserting/deleting // into the middle of the list { dependencies = new ArrayList<DependencyDataCollection>(); } // your Stack shouldn't know how to make the collections... (in my opinion) public void add(final DependencyDataCollection ddc) { dependencies.add(ddc); } public int size() { return dependencies.size(); } // the next 3 methods are just convenience since you don't know if someione // will want to write to a file or a writer instead of a stream public void show() { show(System.out); } public void show(final OutputStream out) { show(new OutputStreamWriter(out)); } public void show(final Writer writer) { show(new PrintWriter(writer)); } public void show(final PrintWriter writer) { // use the new for-each instead of the old style for loop // this also uses an iterator which is faster than calling get // (well on an ArrayList it probably is about the same, but a LinkedList it'll be faster) for(final DependencyDataCollection ddc : dependencies) { writer.println(ddc.getSNo() + " " + ddc.getSessionID() + " " + ddc.getNoOfDependency() + " " + ddc.getNoOfRejection() + " " + ddc.getTotalValue()); } } public int returnIndexOfSession(final String sessionID) { DependencyDataCollection foundDDC; final int retVal; foundDDC = null; for(final DependencyDataCollection ddc : dependencies) { if(ddc.getSessionID().equals(sessionID)) { foundDDC = ddc; break; } } // deal with the fact that you might have not found the item and it would be null. // this assumes -1 is an invalid session id if(foundDDC == null) { retVal = -1; } else { retVal = foundDDC.getSNo(); } return (retVal); } public static void main(final String[] args) { DependencyStack ds = new DependencyStack(); ds.add(new DependencyDataCollection(1,"a",0,0,0)); ds.add(new DependencyDataCollection(1,"a",0,0,0)); ds.show(); //System.out.println(ds.returnIndexOfSession("a")); // DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0); // System.out.println(ds.indexOf(ddc)); } } ``` Edit: This one will speed up the lookups (and deletes). ``` class DependencyStack { // A Map provides quick lookup private final Map<String, DependencyDataCollection> dependencies; // a LinkedHashMap allows for quick lookup, but iterates in the order they were added... if that matters for show. { dependencies = new LinkedHashMap<String, DependencyDataCollection>(); } // your Stack shouldn't know how to make the collections... (in my opinion) public void add(final DependencyDataCollection ddc) { if(ddc == null) { throw new IllegalArgumentException("ddc cannot be null"); } dependencies.put(ddc.getSessionID(), ddc); } public int size() { return dependencies.size(); } // the next 3 methods are just convenience since you don't know if someione // will want to write to a file or a writer instead of a stream public void show() { show(System.out); } public void show(final OutputStream out) { show(new OutputStreamWriter(out)); } public void show(final Writer writer) { show(new PrintWriter(writer)); } public void show(final PrintWriter writer) { // use the new for-each instead of the old style for loop // this also uses an iterator which is faster than calling get // (well on an ArrayList it probably is about the same, but a LinkedList it'll be faster) for(final DependencyDataCollection ddc : dependencies.values()) { writer.println(ddc.getSNo() + " " + ddc.getSessionID() + " " + ddc.getNoOfDependency() + " " + ddc.getNoOfRejection() + " " + ddc.getTotalValue()); } } public int returnIndexOfSession(final String sessionID) { final DependencyDataCollection ddc; final int retVal; if(sessionID == null) { throw new IllegalArgumentException("sessionID cannot be null"); } // get it if it exists, this is much faster then looping through a list ddc = dependencies.get(sessionID); // deal with the fact that you might have not found the item and it would be null. // this assumes -1 is an invalid session id if(ddc == null) { retVal = -1; } else { retVal = ddc.getSNo(); } return (retVal); } public static void main(final String[] args) { DependencyStack ds = new DependencyStack(); ds.add(new DependencyDataCollection(1,"a",0,0,0)); ds.add(new DependencyDataCollection(1,"a",0,0,0)); ds.show(); //System.out.println(ds.returnIndexOfSession("a")); // DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0); // System.out.println(ds.indexOf(ddc)); } } ```
One thing that stands out is the lack of javadoc style comments (from <http://en.wikipedia.org/wiki/Javadoc> ) ``` /** * Validates a chess move. Use {@link #doMove(int, int, int, int)} to move a piece. * * @param theFromFile file from which a piece is being moved * @param theFromRank rank from which a piece is being moved * @param theToFile file to which a piece is being moved * @param theToRank rank to which a piece is being moved * @return true if the chess move is valid, otherwise false */ ```
Need to know some basics of LinkedList class in Java
[ "", "java", "" ]
Note: I'm optimizing because of past experience and due to profiler software's advice. I realize an alternative optimization would be to call `GetNeighbors` less often, but that is a secondary issue at the moment. I have a very simple function described below. In general, I call it within a foreach loop. I call that function a lot (about 100,000 times per second). A while back, I coded a variation of this program in Java and was so disgusted by the speed that I ended up replacing several of the for loops which used it with 4 if statements. Loop unrolling seems ugly, but it did make a noticeable difference in application speed. So, I've come up with a few potential optimizations and thought I would ask for opinions on their merit and for suggestions: * Use four if statements and totally ignore the DRY principle. I am confident this will improve performance based on past experience, but it makes me sad. To clarify, the 4 if statements would be pasted anywhere I called getNeighbors() too frequently and would then have the inside of the foreach block pasted within them. * Memoize the results in some mysterious manner. * Add a "neighbors" property to all squares. Generate its contents at initialization. * Use a code generation utility to turn calls to GetNeighbors into if statements as part of compilation. ``` public static IEnumerable<Square> GetNeighbors(Model m, Square s) { int x = s.X; int y = s.Y; if (x > 0) yield return m[x - 1, y]; if (y > 0) yield return m[x, y - 1]; if (x < m.Width - 1) yield return m[x + 1, y]; if (y < m.Height - 1) yield return m[x, y + 1]; yield break; } //The property of Model used to get elements. private Square[,] grid; //... public Square this[int x, int y] { get { return grid[x, y]; } } ``` Note: 20% of the time spent by the GetNeighbors function is spent on the call to m.get\_Item, the other 80% is spent in the method itself.
Brian, I've run into similar things in my code. The two things I've found with C# that helped me the most: First, don't be afraid necessarily of allocations. C# memory allocations are very, very fast, so allocating an array on the fly can often be faster than making an enumerator. However, whether this will help depends a lot on how you're using the results. The only pitfall I see is that, if you return a fixed size array (4), you're going to have to check for edge cases in the routine that's using your results. Depending on how large your matrix of Squares is in your model, you may be better off doing 1 check up front to see if you're on the edge, and if not, precomputing the full array and returning it. If you're on an edge, you can handle those special cases separately (make a 1 or 2 element array as appropriate). This would put one larger statement in there, but that is often faster in my experience. If the model is large, I would avoid precomputing all of the neighbors. The overhead in the Squares may outweigh the benefits. In my experience, as well, preallocating and returning vs. using yield makes the JIT more likely to inline your function, which can make a big difference in speed. If you can take advantage of the IEnumerable results and you are not always using every returned element, that is better, but otherwise, precomputing may be faster. The other thing to consider - I don't know what information is saved in Square in your case, but if hte object is relatively small, and being used in a large matrix and iterated over many, many times, consider making it a struct. I had a routine similar to this (called hundreds of thousands or millions of times in a loop), and changing the class to a struct, in my case, sped up the routine by over 40%. This is assuming you're using .net 3.5sp1, though, as the JIT does many more optimizations on structs in the latest release. There are other potential pitfalls to switching to struct vs. class, of course, but it can have huge performance impacts.
I'd suggest making an array of Squares (capacity four) and returning that instead. I would be very suspicious about using iterators in a performance-sensitive context. For example: ``` // could return IEnumerable<Square> still instead if you preferred. public static Square[] GetNeighbors(Model m, Square s) { int x = s.X, y = s.Y, i = 0; var result = new Square[4]; if (x > 0) result[i++] = m[x - 1, y]; if (y > 0) result[i++] = m[x, y - 1]; if (x < m.Width - 1) result[i++] = m[x + 1, y]; if (y < m.Height - 1) result[i++] = m[x, y + 1]; return result; } ``` I wouldn't be surprised if that's much faster.
C# Micro-Optimization Query: IEnumerable Replacement
[ "", "c#", "optimization", "" ]
What would be the best way to create a circularly linked list in C#. Should I derive it from the LinkedList< T> collection? I'm planning on creating a simple address book using this Linked List to store my contacts (it's gonna be a suck-y address book, but I don't care cause I'll be the only one to use it). I mainly just want to create the crucially linked list so that I can use it again in other projects. If you don't think the Linked List is the right way to go let me know which way would be better.
As most of these answers don't actually get at the substance of the question, merely the intention, perhaps this will help: As far as I can tell the only difference between a Linked List and a Circular Linked List is the behavior of iterators upon reaching the end or beginning of a list. A very easy way to support the behavior of a Circular Linked List is to write an extension method for a LinkedListNode that returns the next node in the list or the first one if no such node exists, and similarly for retrieving the previous node or the last one if no such node exists. The following code should accomplish that, although I haven't tested it: ``` static class CircularLinkedList { public static LinkedListNode<T> NextOrFirst<T>(this LinkedListNode<T> current) { return current.Next ?? current.List.First; } public static LinkedListNode<T> PreviousOrLast<T>(this LinkedListNode<T> current) { return current.Previous ?? current.List.Last; } } ``` Now you can just call myNode.NextOrFirst() instead of myNode.Next and you will have all the behavior of a circular linked list. You can still do constant time removals and insert before and after all nodes in the list and the like. If there's some other key bit of a circular linked list I am missing, let me know.
It would likely be a bad idea to derive from the BCL LinkedList class. That class is designed to be a non-circular list. Trying to make it circular will only cause you problems. You're probably much better off writing your own.
Creating a circularly linked list in C#?
[ "", "c#", "linked-list", "addressbook", "" ]
Yesterday I had the need for a matrix type in Python. Apparently, a trivial answer to this need would be to use `numpy.matrix()`, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. `numpy.matrix` does not perform this. An example is ``` >>> numpy.matrix([[1,2,3],[4,"5",6]]) matrix([['1', '2', '3'], ['4', '5', '6']], dtype='|S4') >>> numpy.matrix([[1,2,3],[4,5,6]]) matrix([[1, 2, 3], [4, 5, 6]]) ``` As you can see, the `numpy.matrix` must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values ``` >>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1] '5' >>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2] '6' ``` Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: * list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well. * dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows. Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list". My curiosities are: * do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)? * why is this data type not provided in the standard library? Too restricted interest maybe? * How would you have solved this need? Dictionary, list, or another smarter solution?
You can have inhomogeneous types if your `dtype` is `object`: ``` In [1]: m = numpy.matrix([[1, 2, 3], [4, '5', 6]], dtype=numpy.object) In [2]: m Out[2]: matrix([[1, 2, 3], [4, 5, 6]], dtype=object) In [3]: m[1, 1] Out[3]: '5' In [4]: m[1, 2] Out[4]: 6 ``` I have no idea what good this does you other than fancy indexing, because, as Don pointed out, you can't do math with this matrix.
I'm curious why you want this functionality; as I understand it, the reason for having matrices (in numpy), is primarily for doing linear math (matrix transformations and so on). I'm not sure what the mathematical definition would be for the product of a decimal and a String. Internally, you'll probably want to look at sparse matrix implementations (<http://www.inf.ethz.ch/personal/arbenz/pycon03_contrib.pdf>). There are lots of ways to do this (hash, list, linked list), and each has its own advantages and drawbacks. If your matrix isn't going to have a lot of nulls or zeroes, then you can ditch the sparse implementations.
Matrices in Python
[ "", "python", "matrix", "" ]
While I realize that I could just show the form off-screen and hide it, along with many other forms of WinForms hackish wizardry, I'd rather stick with the zen path and get this done right. I have a SSRS local report (so no server) that I want to give the user the option of either viewing or printing (in other words, I don't want to force them to view to print). Unfortunately, the ReportViewer control complains about its "state" when I try to print it either as a component I'm creating explicitly in my code (inside a using() block, of course) or if I try to instantiate my viewer form and just print without ever showing it. Is there a means to do this that will sit well with me, or should I just show it off-screen and move on with my life?
I have a sample that does this posted on my blog here: <http://blogs.msdn.com/brianhartman/archive/2009/02/27/manually-printing-a-report.aspx> The LocalReport object can be instantiated independently of the ReportViewer control and used directly in the sample code attached to that blog post. Or you can pass in ReportViewer.LocalReport even if you don't first display the report in the UI.
Check this out and see if it helps...<http://scruffylookingcatherder.com/archive/2007/12/07/printing-reporting-services-2005-reports.aspx> A little explanation: It's using the SSRS web service to render the report to an EMF image then send the image to the printer.
How to print a ReportViewer's report without showing a form
[ "", "c#", ".net", "reporting-services", "" ]
Do I need to manually call `close()` when I use a `std::ifstream`? For example, in the code: ``` std::string readContentsOfFile(std::string fileName) { std::ifstream file(fileName.c_str()); if (file.good()) { std::stringstream buffer; buffer << file.rdbuf(); file.close(); return buffer.str(); } throw std::runtime_exception("file not found"); } ``` Do I need to call `file.close()` manually? Shouldn't `ifstream` make use of [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) for closing files?
NO This is what RAII is for, let the destructor do its job. There is no harm in closing it manually, but it's not the C++ way, it's programming in C with classes. If you want to close the file before the end of a function you can always use a nested scope. In the standard (27.8.1.5 Class template basic\_ifstream), `ifstream` is to be implemented with a `basic_filebuf` member holding the actual file handle. It is held as a member so that when an ifstream object destructs, it also calls the destructor on `basic_filebuf`. And from the standard (27.8.1.2), that destructor closes the file: > `virtual ˜basic_filebuf();` > > **Effects:** Destroys an object of class `basic_filebuf<charT,traits>`. Calls `close()`.
Do you need to close the file? NO Should you close the file? Depends. Do you care about the possible error conditions that could occur if the file fails to close correctly? Remember that close calls `setstate(failbit)` if it fails. The destructor will call `close()` for you automatically because of **RAII** but will not leave you a way of testing the fail bit as the object no longer exists.
Do I need to manually close an ifstream?
[ "", "c++", "ifstream", "raii", "" ]
I have a WPF application that connects via a socket to a device and gets streaming text data (approx 1 message per second). This data is then displayed on the UI. The user can create rules like *"If the data contains 'abc' highlight the line"* or *"…make it bold"*, so plain text output will not do, it needs to be "rich" text. My current solution to this is to have a [FlowDocument](http://msdn.microsoft.com/en-us/library/system.windows.documents.flowdocument.aspx) in my ViewModel that contains the formatted output. The View has a [FlowDocumentScrollViewer](http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentscrollviewer.aspx) that is bound to the FlowDocument in the ViewModel. This works, but when the FlowDocument gets large (~6,000 lines) performance starts to degrade. The current algorithm caps the number of lines at 10,000, but then things get even worse, to the point where the app is unusable. Once it reaches 10,000 lines, then I remove a line for every line that is added resulting in the FlowDocumentScrollViewer getting 2 update notifications for every new line. I tried to find a way to batch delete (when we reach 10,000 lines delete the oldest 1,000 lines), but there is no bulk delete on the FlowDocument. Looping 1,000 times and doing the delete results in 1,000 update notifications and locks up the UI. That’s my problem, here’s my question: **What is the best way to display streaming rich text content with WPF?** I get ~ 1 message per second, each message is ~150 characters, and I want to keep the last 10000 messages. Am I going about this the wrong way? Are there other controls/objects that would perform better? **EDIT**: Here are some more requirements * Need to be able to print the output text * Need to be able to select and copy the output text so it can be pasted into another document
The performance breakdown seemed to be caused by the high number of Blocks in the FlowDocument. For every message received I was creating a Run, adding that run to a Paragraph and adding the paragraph to the document. I changed the algorithm so now it creates a Paragraph then adds 250 Runs to that Paragraph, then creates a new Paragraph ... adds 250 Runs ... and so on. This essentially cuts the number of blocks in half. This also has an added benefit when I reach the max number of lines (10,000). Instead of deleting a single line for each new line added (and pegging the CPU), I can just delete the oldest Paragraph and that instantly deletes the oldest 250 lines. This relatively simple change brought the performance well within the acceptable range. Instead of pegging the CPU and locking up the UI, now the CPU stays relatively low with spikes around 15%.
This idea complicates things significantly, but my thought would be to create one viewer per message and create only as many viewers as are necessary to display the currently visible messages. I think the VirtualizingStackPanel control would be a good tool to manage this. I found a series describing the implementation of a VirtualizingStackPanel [here](http://blogs.msdn.com/dancre/archive/2006/02/06/implementing-a-virtualized-panel-in-wpf-avalon.aspx). Obviously, this implies maintaining the message buffer in a separate data structure. **EDIT:** I just realized that the standard ListBox control uses a VirtualizingStackPanel in its implementation. With this in mind, my revised suggestion is: 1. Create a data structure to contain the source of each message. 2. Create a property on the data structure that creates a FlowDocument from the message source "on the fly" 3. Bind a ListBox to a collection of said data structures. 4. Define the ItemTemplate for the ListBox with a FlowDocumentScrollViewer where the Document property is bound to the aforementioned data structure's property. **EDIT 2:** Regarding printing/zooming: I can't help you much with printing in WPF (something involving VisualBrush, maybe?), but zooming should be pretty easy to do. I created a ZoomListBox to test this idea. The XAML looks like this: ``` <ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="Test.ZoomListBox" d:DesignWidth="640" d:DesignHeight="480" x:Name="ThisControl"> <ListBox.ItemsPanel> <ItemsPanelTemplate> <VirtualizingStackPanel IsItemsHost="True"> <VirtualizingStackPanel.LayoutTransform> <ScaleTransform ScaleX="{Binding ElementName=ThisControl, Path=Zoom}" ScaleY="{Binding ElementName=ThisControl, Path=Zoom}" /> </VirtualizingStackPanel.LayoutTransform> </VirtualizingStackPanel> </ItemsPanelTemplate> </ListBox.ItemsPanel> </ListBox> ``` And the code behind is this: ``` public partial class ZoomListBox { public ZoomListBox() { this.InitializeComponent(); } public double Zoom { get { return (double)GetValue(ZoomProperty); } set { SetValue(ZoomProperty, value); } } // Using a DependencyProperty as the backing store for Zoom. This enables animation, styling, binding, etc... public static readonly DependencyProperty ZoomProperty = DependencyProperty.Register("Zoom", typeof(double), typeof(ZoomListBox), new UIPropertyMetadata(1.0)); } ``` And an example of using it: ``` <Grid x:Name="LayoutRoot"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <l:ZoomListBox x:Name="ZoomList"> <Button>Foo</Button> <Button>Foo</Button> <Button>Foo</Button> <Button>Foo</Button> <Button>Foo</Button> <Button>Foo</Button> <Button>Foo</Button> </l:ZoomListBox> <Slider Grid.Row="1" Value="{Binding ElementName=ZoomList, Path=Zoom}" Minimum="0.5" Maximum="5" /> </Grid> ```
Displaying streaming rich text with WPF
[ "", "c#", ".net", "wpf", "flowdocument", "" ]
In multithreaded .NET programming, what are the decision criteria for using ThreadPool.QueueUserWorkItem versus starting my own thread via new Thread() and Thread.Start()? In a server app (let's say, an ASP.NET app or a WCF service) I think the ThreadPool is always there and available. What about in a client app, like a WinForms or WPF app? Is there a cost to spin up the thread pool? If I just want 3 or 4 threads to work for a short period on some computation, is it better to QUWI or to Thread.Start().
The ThreadPool is always there, however, there are a finite number of threads allocated to the pool based on the number of processors. For ASP.NET applications, it is generally a bad idea to use Threads unless you really are starting off an Async process and know that there won't be a large number of requests (remember that there are a finite number of threads in the ThreadPool which you share with everything running in your AppDomain and there is a realistic limit on the total number of threads you want to create using new Thread() as well). For WinForms apps consider using the BackgroundWorker instead of using a Thread or the ThreadPool. It uses the ThreadPool, however, it makes communicating between threads easier on the multi-thread savvy programmer. **Updated** > Avoid using ***ThreadPool.QueueUserWorkItem*** as your app pool could disappear at any time. Move this work outside or use WebBackgrounder if you must. From [Hanselman.com - "Checklist: What NOT to do in ASP.NET"](http://www.hanselman.com/blog/ChecklistWhatNOTToDoInASPNET.aspx)
I was gonna make this a comment, but it got too long. CodemonkeyKing seems to have hit on an important point, though not strongly enough in my opinion. There are lots of criteria you might use to describe code. Will it be used in a long running app or not? Winforms app or not? Is it a Server or client app? library or standalone exe? etc etc. Seems to me that if your code will run in a standalone app and you have control over all the surrounding code, then you can roll your own thread pool, start your own threads, and measure and manage the cost around thread startup, thread latency, and resource consumption. Or you could use the QUWI, but it won't kill your app either way. You are free to choose. On the other hand if your code is packaged as a library that may be used in a server -in ASP.NET, or maybe in a SQL CLR app, or a WCF Service - then it is a really bad idea to create threads. You need to use QUWI, or some other mechanism that exploits the built-in thread pool (like BackgroundWorker). If it is to be used in client-side apps with other libraries, once again, QUWI is required. Imagine that every library wanting to take advantage of multi-core computers rolled their own threads. There would be complete chaos in apps that used more than a few libraries. Rampant threads, all competing for the same resources. No central coordination of #threads vs # processors. Good hygeine *demands* that a library, whether it is to be consumed in client apps or server apps, uses the common threadpool, and that means QUWI. Last thing to realize is this; > A managed thread is either a background thread or a foreground thread. Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down. > > Threads that belong to the managed thread pool (that is, threads whose IsThreadPoolThread property is true) are background threads. All threads that enter the managed execution environment from unmanaged code are marked as background threads. All threads generated by creating and starting a new Thread object are by default foreground threads. > > If you use a thread to monitor an activity, such as a socket connection, set its IsBackground property to true so that the thread does not prevent your process from terminating. from the [MSDN site](http://msdn.microsoft.com/en-us/library/h339syd0.aspx).
Advantage of using Thread.Start vs QueueUserWorkItem
[ "", "c#", ".net", "multithreading", "" ]
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. Why this distinction? Does Python include different types of safeguards to minimize the risks of this feature?
As a Python programmer who has had a taste of Ruby (and likes it), I think there is somewhat of an ironic parallel to when Python was beginning to become popular. C and Java programmers would ‘bash’ Python, stating that it wasn't a real language, and that the dynamic nature of its types would be dangerous, and allow people to create ‘bad’ code. As Python became more popular, and the advantages of its rapid development time became apparent, not to mention the less verbose syntax: ``` // Java Person p = new Person(); ``` ``` # Python p = Person() ``` we began to see some more dynamic features appear in later versions of Java. Autoboxing and -unboxing make it less troublesome to deal with primitives, and Generics allow us to code once and apply it to many types. It was with some amusement that I saw one of the key flexible features of Ruby – Monkey Patching, being touted as dangerous by the Python crowd. Having started teaching Ruby to students this year, I think that being able to ‘fix’ the implementation of an existing class, even one that is part of the system, is very powerful. Sure, you can screw up badly and your program can crash. I can segfault in C pretty easily, too. And Java apps can die flaming death. The truth is, I see Monkey Patching as the next step in dynamic and meta-programming. Funny, since it has been around since Smalltalk.
It's a technique less practised in Python, in part because "core" classes in Python (those implemented in C) are not really modifiable. In Ruby, on the other hand, because of the way it's implemented internally (not better, just different) just about anything can be modified dynamically. Philosophically, it's something that tends to be frowned on within the Python community, distinctly less so in the Ruby world. I don't know why you assert that it's more controversial (can you link to an authoritative reference?) - my experience has been that monkey-patching is an accepted technique if one where the user should be aware of possible consequences.
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
[ "", "python", "ruby", "language-features", "monkeypatching", "" ]
for\_each accepts InputIterators : ``` //from c++ standard template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function f); ``` is it ok to change the object in Function f, like this : ``` struct AddOne { void operator()(int & x){x = x + 1;} }; std::vector<int> vec(10); std::for_each(vec.begin(),vec.end(),AddOne()); ``` This code works in VC++2008 and also with GCC, but is it also portable (legal) code ? (InputIterators are only guaranteed to be usable as rvalue, in this case they are used as lvalue in AddOne's operator())
Read this [article](http://www.ddj.com/cpp/184403769). To be pedantic: `for_each` is a non-modifying sequence operation. The intent is not to modify the sequence. However, it *is* okay to modify the input sequence when using `for_each`.
You misunderstand something. Saying input iterators are only guaranteed to be usable as rvalues doesn't mean you can't get an lvalue out of an iterator somehow. So it does not mean that the result of `*iterator` is an rvalue. What you/for\_each passes to `AddOne` is the result of `operator*` - *not* the iterator itself. About `for_each` and a modifying function object - read [this question](https://stackoverflow.com/questions/662845/why-is-stdforeach-a-non-modifying-sequence-operation/662922)
Is it ok to mutate objects with std::for_each?
[ "", "c++", "stl", "" ]
What's the difference between `IEnumerable` and `Array`? What's the difference between `IList` and `List`? These seem to have the same function.
`IEnumerable` provides only minimal "iterable" functionality. You can traverse the sequence, but that's about it. This has disadvantages; for example, it is very inefficient to count elements using `IEnumerable`, or to get the nth element. But it has advantages too; for example, an `IEnumerable` could be an endless sequence, like the sequence of primes. `Array` is a fixed-size collection with random access (i.e. you can index into it). `List` is a variable-size collection (i.e. you can add and remove elements) with random access. `IList` is an interface which abstracts list functionality (count, add, remove, indexer access) away from the various concrete classes such as `List`, `BindingList`, `ObservableCollection`, etc.
IEnumerable is an interface that allows the iteration through a collection of items (e.g. via the foreach keyword). An array is a .NET intrinsic. It holds items of the same type, but it is of a fixed size. Once you create an array with x elements, it cannot grow or shrink. IList defines the interface for a list, and also implements IEnumerable. List implements the IList interface; it is a concrete type of list. The difference between .NET Lists and arrays is that lists can have elements added to them -- they grow to be big enough to hold all of the required items. The list stores this internally in an array and, when the array is no longer big enough to hold all of the elements, a new array is created and the items copied across. IList & arrays both implement IEnumerable. That's how interfaces work -- classes implement the contract and behave in a similar fashion and can be treated similarly as a result (you know that the class implements IEnumerable, you don't need to know the hows or the whys). I suggest you read up on interfaces and so forth.
What's the difference between IEnumerable and Array, IList and List?
[ "", "c#", "" ]
I need to write a WPF excel-like grid control. I'm new to WPF and can't quite work out where to start. Should it derive from UserControl, FrameworkElement, or something else? I need it to have horizontal and vertical scrollbars and a content area. Does that mean my grid control should have a DockPanel with the scrollbars, then another control for the content area so that my GridUserControl would have a DockPanel with 2 docked scrollbars and a GridContentFrameworkElement control? Buying a grid is not an option. --- This is what I decided on: I have a GridUserControl (derived from UserControl). It has a DockPanel with 2 docked ScrollBar objects. The main content area (GridContent) is another control derived from Panel. The content is drawn in GridContent.OnRender. I did not go with a ScrollViewer since it wants to render the entire content area and then scroll that around. I only wanted to draw the bit of the content area that was currently visible since the grid can have millions of lines in it.
It should probably derive from either UserControl or ItemsControl (or something else in the ItemsControl hierarchy, such as Selector). If you are new to WPF it is probably best to derive from UserControl because creating a nice custom control requires a reasonable fluency with the idioms of WPF development as well as just the APIs. Rather than trying to manage the scrolling area manually by creating explicit ScrollBar elements, consider using the ScrollViewer class. If you host your grid content within a ScrollViewer, and it is too large for the available display area, ScrollViewer will take care of displaying scroll bars and scrolling the content automatically. Note that if you are looking for data grid-type functionality then there are various free, commercial and open source WPF data grids available, though these do tend to be biased towards tabular data editing rather than, say, Excel-like functionality.
Are you sure you have to write one? The are lots of [good grids](http://www.infragistics.com/dotnet/netadvantage/wpf/xamdatagrid.aspx#Overview) out there; [even free ones](http://xceed.com/Grid_WPF_Intro.html). I know it's non-responsive, but just trying to help.
Writing a WPF Grid
[ "", "c#", "wpf", "grid", "" ]
I'm working on setting this up on Mac OS X Leopard. I'm having a devil of a time getting PHP5 working as fastcgi under lighttpd. I've verified that I've compiled php with fastcgi enabled. I've tried configuring lighttpd as I've seen in various documentation. The core bit that I'm not understanding is if php-cgi is supposed to create the socket, or if lighttpd creates it. My lighttpd config looks like this: ``` fastcgi.server = ( ".php" => ( "localhost" => ( "socket" => "/var/run/php-fastcgi.socket", "bin-path" => "/usr/local/php/bin/php-cgi" ) ) ) ``` When I check /var/run/ no php-fastcgi.socket has been created.
I was tearing my hair out with the same problem. Ive setup lighty and php so many times on linux, but I struggled to get the php fastcgi-socket working under OSX. In the end I started the fast cgi server manually, using php-cgi -b 127.0.0.1:5555 Then specified a tcp port in lighty config... fastcgi.server = ( ".php" =>( "localhost" =>("host" => "127.0.0.1","port" => 5555 ))) Probably not ideal, but it does work this way
Do you have the `mod_fastcgi` module enabled? ``` server.modules += ( "mod_fastcgi" ) ``` Does the user the server is running on has permissions to write to `/var/run`? For what is worth, here's my config on a machine running Debian Etch: ``` fastcgi.server = ( ".php" => (( "bin-path" => "/usr/bin/php5-cgi", "socket" => "/tmp/php.socket", "max-procs" => 1, "idle-timeout" => 20, "bin-environment" => ( "PHP_FCGI_CHILDREN" => "1", "PHP_FCGI_MAX_REQUESTS" => "1000"), "bin-copy-environment" => ( "PATH", "SHELL", "USER"), "broken-scriptfilename" => "enable" )) ) ```
Does PHP or LIghttpd create the fastcgi socket?
[ "", "php", "fastcgi", "" ]
I am new in binary conversion. I use Python, Bash and AWK daily. I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work. **Where do you use binary conversion in Python/Bash/AWK?** I would like to see examples of codes.
Conversion of strings of binary digits to a number using Python on the commandline: ``` binary=00001111 DECIMAL=$(python -c "print int('$BINARY', 2)") echo $decimal ``` See the docs for the [int function](http://docs.python.org/library/functions.html#int). Oh, wait, I misread the question, you want to know what converting to binary gets you. Well, that depends on what you mean by "convert to binary". Say I want to store a file with a million integers. The integers will be between 0 and 32,000. If I were to store them as text it would take at best two bytes for each number (single digit number and a separator), at worst six bytes (five digit number and a separator), with an average size of 4.6 bytes per number (see comment for the math). I also would have no easy way of choosing the 15th number. If I were store them as 16bit integers (in binary), every number would take up exactly two bytes and I could find the 15th number by `seek`'ing to offset `2*(15-1)` and reading two bytes. Also, when I go to do math on the text based version I (or my language) must first convert the string to a number, whereas the binary version is already a 16bit number. So, in short, you use binary types to 1. save space 2. have consistent record sizes 3. speed up programs
In shell, a nice use of [`dc`](https://stackoverflow.com/questions/750606/what-technologies-are-you-using-even-though-they-are-embarassingly-out-of-date/750620#750620): ``` echo 2i 00001111 pq | dc ``` 2i means: *base for input numbers is 2*. pq means: *print and quit*. The other way is: ``` echo 2o 15 pq | dc ``` I don't remember having used this feature in real-world situations.
How do you use Binary conversion in Python/Bash/AWK?
[ "", "python", "bash", "binary", "awk", "" ]
When I call an external `.exe` program in Python, how can I get `printf` output from the `.exe` application and print it to my Python IDE?
To call an external program from Python, use the [subprocess](http://docs.python.org/library/subprocess.html#module-subprocess) module. > The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. An example from the doc (`output` is a file object that provides output from the child process.): ``` output = subprocess.Popen(["mycmd", "myarg"], stdout=subprocess.PIPE).communicate()[0] ``` A concrete example, using `cmd`, the Windows command line interpreter with 2 arguments: ``` >>> p1 = subprocess.Popen(["cmd", "/C", "date"],stdout=subprocess.PIPE) >>> p1.communicate()[0] 'The current date is: Tue 04/14/2009 \r\nEnter the new date: (mm-dd-yy) ' >>> ```
I am pretty sure that you are talking about Windows here (based on the phrasing of your question), but in a Unix/Linux (including Mac) environment, the commands module is also available: ``` import commands ( stat, output ) = commands.getstatusoutput( "somecommand" ) if( stat == 0 ): print "Command succeeded, here is the output: %s" % output else: print "Command failed, here is the output: %s" % output ``` The commands module provides an extremely simple interface to run commands and get the status (return code) and the output (reads from stdout and stderr). Optionally, you can get just status or just output by calling commands.getstatus() or commands.getoutput() respectively.
How to get output of exe in python script?
[ "", "python", "ide", "executable", "redirect", "" ]
I need to send email in delbian linux. How to send? I run my server on 256 MB linux box and I heard postfix and sendmail is overkill. Recently I came across the ssmtp, that seems to be an executable, needs to be executed as a process and called through python using os modules. alternatively, python already provides smtplib which is working fine with me. What is the advantage of using ssmtp over python's smtplib?
In a Python program, there is no advantage. The only purpose of ssmtp is to wrap the SMTP protocol in the sendmail API. That is, it provides a program `/usr/sbin/sendmail` that accepts the same options, arguments, and inputs as the full-blown sendmail (though most of the options do nothing); but behind the scenes, instead of processing the email itself, it sends the message to an SMTP server. This is for systems that need to have a `sendmail` program present, perhaps because they don't understand SMTP - for example, I think older versions of PHP had this requirement, and even in recent versions it might still be easier to configure PHP to use the so-called sendmail interface (i.e. the program `sendmail`) than to use SMTP directly. (I haven't used PHP in a little while, I'm not sure about the current status) However, in Python the situation is reversed: you have a builtin library that makes it easy to use SMTP directly, whereas using `sendmail` requires you to invoke the `subprocess` module which is somewhat clunky and also very dependent on things that are not part of Python. So basically there is no reason not to use `smtplib`.
Additionally, *postfix* is very easy to install in "satellite" mode, where all it does is queue and deliver email for you. Way easier than implementing your own email queue. Most decent package management systems will let you configure it this way.
how to send mail in python ssmtp vs smtplib
[ "", "python", "smtplib", "ssmtp", "" ]
My instructor sent me this code, which is supposed to be an integral part of an ongoing project. Thing is, it doesn't work. ``` import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.Kernel; import java.awt.image.ConvolveOp; import com.sun.image.codec.jpeg.JPEGImageEncoder; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import javax.swing.*; public class ImageUtil { public static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException{ if(quality <0||quality>1){ throw new IllegalArgumentException ("quality has to be between 0 and 1"); } ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath()); Image i = ii.getImage(); Image resizedImage = null; int iWidth = i.getWidth (null); int iHeight = i.getHeight(null); if (iWidth > iHeight){ resizedImage = i.getScaledInstance(newWidth,(newWidth*iHeight)/iWidth, Image.SCALE_SMOOTH); } else { resizedImage = i.getScaledInstance((newWidth*iWidth)/iHeight,newWidth, Image.SCALE_SMOOTH); } Image temp = new ImageIcon (resizedImage).getImage(); BufferedImage bufferedImage = new BufferedImage (temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB); // copy to a buffered image Graphics g = bufferedImage.createGraphics(); g.setColor(Color.white); g.fillRect(0,0,temp.getWidth(null), temp.getHeight(null)); // causea el error de ejecución? g.drawImage(temp,0,0,null); g.dispose(); float softenFactor = 0.05f; float [] softenArray = {0, softenFactor,0, softenFactor, 1-(softenFactor*4), softenFactor,0, softenFactor,0}; Kernel kernel = new Kernel (3,3,softenArray); ConvolveOp cOp = new ConvolveOp (kernel, ConvolveOp.EDGE_NO_OP,null); bufferedImage = cOp.filter (bufferedImage,null); FileOutputStream out = new FileOutputStream(resizedFile); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage); param.setQuality(quality,true); encoder.setJPEGEncodeParam(param); encoder.encode(bufferedImage); } public static void main(String args[]) throws IOException { File originalImage= new File ("/images/goya.jpg"); resize(originalImage,new File("/images/goyanuevotamanio.jpg"),350, 0.2f); resize(originalImage, new File("/images/goyanuevotamanio.jpg"), 350, 1f); } } ``` He says the code should be able to resize both height and width yet his resize method: ``` public static void resize(File originalFile, File resizedFile, int newWidth, float quality) ``` lacks a `newHeight` parameter. The RuntimeException that's thrown says: ``` Exception in thread "main" java.lang.IllegalArgumentException: **Width (-1) and height (-1) cannot be <= 0** at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:999) at java.awt.image.BufferedImage.<init>(BufferedImage.java:312) at ImageUtil.resize(ImageUtil.java:38) at ImageUtil.main(ImageUtil.java:72) Java Result: 1 ``` How can I change this?
Without analyzing the code to see what the problem might be, I can say that if the intention is to keep the images aspect ratio, a new height parameter is not needed. It will always be a fixed ratio of the width. **UPDATE:** I've run the code against my own test image and it does indeed work as expected. The error you are getting is most likely caused when the program cannot find the source image you specify. I get the same error when I specify a source image that doesn't exist. Try using an absolute path (including drive letter etc.) for your source image. **UPDATE 2** Add the following code after the line.. ``` ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath()); if(ii.getImageLoadStatus() == MediaTracker.COMPLETE) { System.out.print("Load image ok\n"); } else { System.out.print("Load image failed\n"); } ``` This will tell you if the program is failing to load the source image.
Why you apply soften to resize it have to be sharpen Kernal -1 -2 -1 -2 12+q -2 -1 -2 -1 where a tipical q could be 28 and you are not applyng the resize version of drawImage (q = 36 is equivalent to your F=0.05 for sharpen)
Making this code for image resize() work
[ "", "java", "image", "netbeans6.5", "" ]
I am using the following the following class `org.apache.poi.hssf.usermodel.HSSFCell`, with a list of the following methods: ``` void setCellValue(boolean value) void setCellValue(java.util.Calendar value) void setCellValue(java.util.Date value) void setCellValue(double value) void setCellValue(HSSFRichTextString value) void setCellValue(java.util.Calendar value) void setCellValue(HSSFRichTextString value) ``` Take note that, there are no methods with Object as method parameter. Now, I have no way to determine my value class type during compiled time. I can only determine my value class type during runtime. Hence, how I can determine the correct method to be called, if I do not know the method signature during compiled time? My code is below: ``` final int rowCount = tableModel.getRowCount(); for (int i = 0; i < rowCount; i++) { final HSSFRow row = sheet.createRow(i + 1); for (int j = 0; j < columnCount; j++) { final Object object = tableModel.getValueAt(i, j); final Class myClass = tableModel.getColumnClass(j); // How to perform casting during compiled time, and invoke // the setCellValue with correct signature? if (object != null) { row.createCell(j).setCellValue(??); // Does not accept Object! } } } ``` Perhaps ugly if...else with `instanceof` would resolve my problem. However, if I do not want the ugly if...else with `instanceof`, is there any better way to do so?
One way of handling this is to load that list of methods at runtime into a `Map` and then for each call, use the `Map`. That is, something like this (where this code is simplified and omits error checking): ``` Map<? extends Object, Method> map; Method[] methods = Setters.class.getMethods(); for (Method method : methods) { if (method.getName().equals("setCellValue")) { map.put(method.getParameterTypes()[0], method); } } ``` then when you want to call this, look up the Method in the `map` by argument type and use that instance. To show this off, again with simplified but this time full code. Note that to be fully general, the code gets a little more complicated, as is shown below. If you don't have to worry about primitives (which depends on your usage) or if you don't have to worry about interfaces or superclasses, then you can simplify the example below. Also, if you can guarantee that there will be no overlap in interfaces or superclasses in the arguments that you have to worry about, you can move all of the complicated logic into initialization (which doesn't matter if it takes 1 ms longer). In this case, all of the logic in `findMethodToInvoke()` would be moved into the constructor, where you would loop over all interfaces and superclasses of each method you find and add them to your parameterTypeMap. If you do this optimization, then `findMethodToInvoke()` becomes a single line: ``` return parameterTypeMap.get(test.getClass()); ``` but without this optimization and with full generality, here's my example of how to do this: ``` import java.lang.reflect.*; import java.util.*; public class Test { private final Map<Object, Method> parameterTypeMap = new HashMap<Object, Method>(); private final Object[] tests = {Double.valueOf(3.1415), Boolean.TRUE, new Date(), new GregorianCalendar(), new HashMap<Object, Object>()}; public Test() { Method[] methods = Setters.class.getMethods(); for (Method method : methods) { if (method.getName().equals("setCellValue")) { Class<?>[] clazzes = method.getParameterTypes(); if (clazzes.length != 1) { continue; } if (clazzes[0].isPrimitive()) { handlePrimitive(method, clazzes[0]); } parameterTypeMap.put(clazzes[0], method); } } } // See http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isPrimitive() private void handlePrimitive(Method method, Class<?> clazz) { if (clazz == Boolean.TYPE) { parameterTypeMap.put(Boolean.class, method); } else if (clazz == Double.TYPE) { parameterTypeMap.put(Double.class, method); } // ... and so on for the other six primitive types (void doesn't matter) } public void doTests(Setters setter) { for (Object test : tests) { Method method = findMethodToInvoke(test); if (method == null) { System.out.println("Nothing found for " + test.getClass()); continue; } try { method.invoke(setter, test); } catch (Exception e) { e.printStackTrace(); } } } private Method findMethodToInvoke(Object test) { Method method = parameterTypeMap.get(test.getClass()); if (method != null) { return method; } // Look for superclasses Class<?> x = test.getClass().getSuperclass(); while (x != null && x != Object.class) { method = parameterTypeMap.get(x); if (method != null) { return method; } x = x.getSuperclass(); } // Look for interfaces for (Class<?> i : test.getClass().getInterfaces()) { method = parameterTypeMap.get(i); if (method != null) { return method; } } return null; } public static void main(String[] args) { Test test = new Test(); test.doTests(new Setters()); } } class Setters { public void setCellValue(boolean value) { System.out.println("boolean " + value); } public void setCellValue(double value) { System.out.println("double " + value); } public void setCellValue(Calendar value) { System.out.println("Calendar " + value); } public void setCellValue(Date value) { System.out.println("Date " + value); } public void setCellValue(Map<?, ?> value) { System.out.println("Map " + value); } } ```
I think the `instanceof` is the way to go. If you think it makes your code ugly extract that `instanceof` expressions into an auxiliary method: ``` public void setCellValue(HSSFCell cell, Object value) { if (null == cell) throw new IllegalArgumentException("cell"); if (null == value) throw new IllegalArgumentException("value"); if (value instanceof Double) cell.setCellValue((Double)value); // auto-boxing will handle this else if (value instanceof Boolean) { cell.setCellValue((Boolean)value); // auto-boxing will handle this } else if (value instanceof Calendar) { cell.setCellValue((Calendar)value); } else if ... ..... } else { throw new UnsupportedTypeException("Object of class " + Value.class.getName() + " not supported."); } } ``` Alternately you can use reflection. Even with reflection *I think* you still have to do some customization for the primitive types because the auto-boxing doesn't work for `getMethod()` ... ``` public void invokeSetCellValue(HSSFCell cell, Object obj) { try { Class<?> clazz = obj.getClass(); if (obj instanceof Double) { clazz = double.class; } else if (obj instanceof Boolean) { clazz = boolean.class; } Method m = HSSFCell.class.getMethod("setCellValue", clazz); m.invoke(cell, obj); } catch (SecurityException e) { } catch (NoSuchMethodException e) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } ```
Determine Correct Method Signature During Runtime
[ "", "java", "reflection", "" ]
As I've created the application that is hard on calculations -> lots of work to do, not very complex calculations -> it takes too long to work it out and the process is only at 45% of the CPU. Can I maximize it somehow?: to go to 90%?
If you have a dual core machine (which I'm guessing you do), the most you could hope to get in a single thread would be 50% CPU usage. To get 90% CPU usage, you will most likely need to thread your calculations. This may be very simple, or very difficult, depending on the nature of the algorithm you want to thread. If you can break up your working set into multiple groups, I would recommend considering using the [ThreadPool](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx), or potentially even the [Task Parallel Library](http://blogs.msdn.com/pfxteam/), depending on your timing for release.
More than likely you have a dual core CPU, and if your app is single threaded, the maximum CPU it will use is 50% (all of one core). In order to get better use, you need to utilize multiple threads, but that also means figuring out some way to break your calculations into pieces so that they can be worked on by more than one core.
How to maximize power used by my application in C#?
[ "", "c#", "process", "cpu", "maximize", "" ]
Let's say I'm creating an OpenGL game in C++ that will have many objects created (enemies, player characters, items, etc.). I'm wondering the best way to organize these since they will be created and destroyed real-time based on time, player position/actions etc. Here's what I've thought of so far: I can have a global array to store pointers to these objects. The textures/context for these objects are loaded in their constructors. These objects will have different types, so I can cast the pointers to get them in the array, but I want to later have a renderObjects() function that will use a loop to call an ObjectN.render() function for each existing object. I think I've tried this before but I didn't know what type to initialize the array with, so I picked an arbitrary object type, then cast anything that wasn't of that type. If I remember, this didn't work because the compiler didn't want me dereferencing the pointers if it no longer knew their type, even if a given member function had the same name: (\*Object5).render() <-doesn't work? Is there a better way? How to commercial games like HL2 handle this? I imagine there must be some module etc. that keeps track of all the objects.
I'm not sure I fully understand the question but I think you are wanting to create a collection of polymorphic objects. When accessing a polymorphic object, you must always refer to it by a pointer or a reference. Here is an example. First you need to set up a base class to derive your objects from: ``` class BaseObject { public: virtual void Render() = 0; }; ``` Then create the array of pointers. I use an STL set because that makes it easy to add and remove members at random: ``` #include <set> typedef std::set<BaseObject *> GAMEOBJECTS; GAMEOBJECTS g_gameObjects; ``` To add an object, create a derived class and instantiate it: ``` class Enemy : public BaseObject { public: Enemy() { } virtual void Render() { // Rendering code goes here... } }; g_gameObjects.insert(new Enemy()); ``` Then to access objects, just iterate through them: ``` for(GAMEOBJECTS::iterator it = g_gameObjects.begin(); it != g_gameObjects.end(); it++) { (*it)->Render(); } ``` To create different types of object, just derive more classes from class BaseObject. Don't forget to delete the objects when you remove them from the collection.
For my soon-to-be personal game project, I use a component-based entity system. You can read more about it by searching "component based game development". A famous article is [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/) from the Cowboy programming blog. In my system, entities are just ids - unsigned long, a bit like in a relational database. All the data and the logic associated to my entities are written into Components. I have Systems that link entity ids with their respective components. Something like that: ``` typedef unsigned long EntityId; class Component { Component(EntityId id) : owner(id) {} EntityId owner; }; template <typename C> class System { std::map<EntityId, C * > components; }; ``` Then for each kind of functionality, I write a special component. All entities don't have the same components. For example you could have a static rock object that has the WorldPositionComponent and the ShapeComponent, and a moving enemy that has the same components plus the VelocityComponent. Here's an example: ``` class WorldPositionComponent : public Component { float x, y, z; WorldPositionComponent(EntityId id) : Component(id) {} }; class RenderComponent : public Component { WorldPositionComponent * position; 3DModel * model; RenderComponent(EntityId id, System<WorldPositionComponent> & wpSys) : Component(id), position(wpSys.components[owner]) {} void render() { model->draw(position); } }; class Game { System<WorldPositionComponent> wpSys; System<RenderComponent> rSys; void init() { EntityId visibleObject = 1; // Watch out for memory leaks. wpSys.components[visibleObject] = new WorldPositionComponent(visibleObject); rSys.components[visibleObject] = new RenderComponent(visibleObject, wpSys); EntityId invisibleObject = 2; wpSys.components[invisibleObject] = new WorldPositionComponent(invisibleObject); // No RenderComponent for invisibleObject. } void gameLoop() { std::map<EntityId, RenderComponent *>::iterator it; for (it = rSys.components.iterator(); it != rSys.components.end(); ++it) { (*it).second->render(); } } }; ``` Here you have 2 components, WorldPosition and Render. The Game class holds the 2 systems. The Render component has an access to the position of the object. If the entity doesn't have a WorldPosition component, you can choose default values, or ignore the entity. The Game::gameLoop() method will only render visibleObject. There is no waste of processing for non-renderable components. You can also split my Game class into two or three, to separate display and input systems from the logic. Something like Model, View and Controller. I find it neat to define my game logic in term of components, and to have entities that only have the functionality that they need - no more empty render() or useless collision detection checks.
Best way to organize entities in a game?
[ "", "c++", "opengl", "" ]
I've run into quite an awkward predicament in a project at work. We need to create users across 4 or 5 different services, and have set it up in such a way that if one fails, they all fail. They're encapsulated within a transaction scope block. One of the services we need to add users to requires telnetting in, and fudging some data. There are other ways to do it (that cost money) but for now that's what we're stuck with. Adding one user takes approximately 3 minutes. We're going to work on getting that down significantly as can be imagined but that's not really the point. This call is asynchronous and kind of has to be to work correctly. The punchline is, there can only be a maximum of 10 connections to the service. Our project is being set up to create users in a batch. So potentially 50 users created at a time. This presents a problem when only 10 connections can be made via telnet, and a processed user isn't likely to take very long other than the telnet service. I now need to synchronise this process so the rest can't continue until it has finished. We're using callbacks and delegates with asynchronous calls to implement the functionality. What would be the best way of encapsulating the asynchronous portion, and not continuing until it's completed? Should we set up a loop that only terminates when the call is finished? Is there something in the Threading library that could help? I've never worked with threads before so this will be a first for me. What tools are there to help with this problem? EDIT: If I use the BeginInvoke / EndInvoke pattern, will asynch calls within the first delegate honour the begin/end also? Example: ``` public void dele1(string message) { Console.Write(message); delegate2 del2 = new delegate2; del2(); Console.Write("End of Delegate 2"); } public void dele2() { // Long Processing Console.Write("Delegate 2"); } public delegate void delegate1(String message); public delegate void delegate2(); delegate1 del1 = new delegate1(dele1); del1("Delegate 1").BeginInvoke; del1().EndInvoke; Console.Write("End of Delegate 1"); ``` // Expected Output (End Invoke waits until Delegate 2 is finished): ``` Delegate 1 End of Delegate 2 Delegate 2 End of Delegate 1 ``` // Or (End Invoke only waits for delegate 1 to finish but not any internal delegate calls): ``` Delegate 1 End of Delegate 2 End of Delegate 1 Delegate 2 ``` Will end invoke wait until the second delegate finishes processing also? Or will I need to use the invoke patterns on all delegate calls?
You could indeed use monitors, semaphores, or you could even spin wait until your asynchronous method call(s) is done. But you can get this for free too. If you call `EndInvoke()` on a delegate that was previously started with `BeginInvoke()`, you block until the asynchronous work is done. Not sure if this helps because you have to be using this asynchronous pattern. If it does, you get Asynchronous execution (and conversion from Asynchronous back to synchronous calls) for free. Check out [Calling Synchronous Methods Asynchronously on MSDN](http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx) for more info on this pattern. I hope this helps!
`IAsyncResult` has a property `AsyncWaitHandle` which gives you a wait handle (if one is available) which will be signalled when the operation completes. Thus you can use `WaitHandle.WaitAll` (or `.WaitAny`) to perform non-spinning waits on many handles at once.
Synchronising an Asynchronous call in c#
[ "", "c#", "multithreading", "asynchronous", "delegates", "" ]
I want to accept a string from a form and then break it into an array of characters using PHP, for example: ``` $a = 'professor'; $b[0] == 'p'; $b[1] == 'r'; $b[2] == 'o'; . . . . . $b[8] = 'r'; ```
You don't need to do that. In PHP you can access your characters directly from the string as if it where an array: ``` $var = "My String"; echo $var[1]; // Will print "y". ```
``` str_split($word); ``` ~~This is faster than accessing $word as an array.~~ (And also better in that you can iterate through it with `foreach()`.) [Documentation](https://www.php.net/str_split).
break a word in letters php
[ "", "php", "" ]
What is the best way to write a callback? I only need to call 1 function that has the sig of void (string, int); and this would need to invoke a class since i have member objs that i need to process. Whats the best way to write this? in C i would do pass a func pointer and an void\*obj. i dislike that and i suspect there is a better way to do this in C#?
The standard way of handling (or replacing the need for) callbacks in C# is to use delegates or events. [See this tutorial for details.](http://www.akadia.com/services/dotnet_delegates_and_events.html) This provides a very powerful, clean way of handling callbacks.
C#3.0 introduced lambdas which allow you forgo the declaration of callback (or delegate) signatures. It allows you to do things like: ``` static void GiveMeTheDate(Action<int, string> action) { var now = DateTime.Now; action(now.Day, now.ToString("MMMM")); } GiveMeTheDate((day, month) => Console.WriteLine("Day: {0}, Month: {1}", day, month)); // prints "Day: 3, Month: April" ```
How should i create a callback
[ "", "c#", "callback", "" ]
If I have a databound form, how do I know if a user has modified it (either by typing text into a text box, or by selecting an item in a combobox)? I've tried hooking into my textbox's "TextChanged" event, but the problem is that, when my form participates in databinding, the "TextChanged" event fires, prematurely marking my form as "dirty."
try implementing ``` public partial class Window1 : INotifyPropertyChanged ``` and then ``` public event PropertyChangedEventHandler PropertyChanged; public string UserName { get { return _UserName; } set { if (value != _UserName) { _UserName = value; OnNotifyPropertyChanged("UserName"); }} } private void OnNotifyPropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } ``` and databind like ``` <TextBox Text="{Binding UserName}"/> ```
Does your model class implement `INotifyPropertyChanged`? If so, you could add a handler for the `PropertyChanged` event on the class, and watch for the property in question to change. If you haven't implemented `INotifyPropertyChanged`, maybe the mechanism that you're using to notify the UI layer of updates could be used here as well?
How can I mark a form/field as "dirty" if it's databound?
[ "", "c#", ".net", "wpf", "validation", "" ]
I have data like this (col2 is of type Date) ``` | col1 | col2 | ------------------------------ | 1 | 17/10/2007 07:19:07 | | 1 | 17/10/2007 07:18:56 | | 1 | 31/12/2070 | | 2 | 28/11/2008 15:23:14 | | 2 | 31/12/2070 | ``` How would select rows which col1 is distinct and the value of col2 is the greatest. Like this ``` | col1 | col2 | ------------------------------ | 1 | 31/12/2070 | | 2 | 31/12/2070 | ```
``` SELECT col1, MAX(col2) FROM some_table GROUP BY col1; ```
``` select col1, max(col2) from table group by col1 ```
SQL select distinct rows
[ "", "sql", "" ]
I have a local server where I do all my testing and work. Once I am done, I simply upload the db schema along with the relevant code. However the problem arises when I make some changes to the schema. I have to manually type the "alter table" query on my live server. Is there a way to get the incremental changes that took place in the db schema so that I can just apply the new ones? Or do I have to manually keep track? If I use mysqldump, then it produces the schema of the final db (not with alter table etc). Thank you very much.
[MySQL Workbench](http://dev.mysql.com/downloads/gui-tools/5.0.html) lets you export ALTER scripts (File -> Export -> Forward Engineer SQL ALTER Script). You'll have first to import your existing database and apply your modifications to it. The commercial version lets you reverse engineer a live database, the community one does it importing a CREATE script instead (this would be a simple dump of the existing structure). Alternatively you can reverse engineer a live database with [DBDesigner 4](http://www.fabforce.net/dbdesigner4/), save all to an XML Model file end import this, but you're gonna lose stuff like the default charset and such...
I keep the delta sql scripts which go to the production server together with the new code. I script everything so the change of the application from version X to version Y is "automatic". [Some people also have undo scripts](http://www.se-radio.net/podcast/2008-09/episode-109-ebay039s-architecture-principles-randy-shoup) in case something goes wrong.
Php Db synchronization
[ "", "php", "schema", "migration", "mysql", "" ]
I've declared the following hashmap: ``` HashMap<Integer, Hive> hives ``` Where Hive is an object. If I call "hives.get(2)" will it return a copy of the object Hive at that location or a reference to it? My goal is to modify the Hive object at that location. If it returns the reference, I can just modify the returned hive and be done. However, if a copy gets returned then I'll have to put that copy back into the hashmap. Sorry for the simple question. I tried looking around for a solution, but everywhere I looked it simply said the value would be returned, it didn't say if it would be a copy of the value or a reference to it. Thanks, Zain
It returns a reference. You can pretty much assume this is the case unless otherwise specified.
You will get a reference to it—Java objects are always passed by reference.
the get() function for java hashmaps
[ "", "java", "object", "reference", "hashmap", "" ]
I am trying to move an OpenGL app to Windows. It was my understanding that Windows had a decent OpenGL implementation. But I'm starting to think that it doesn't... Specifically, I use array buffers and [glDrawArrays](http://msdn.microsoft.com/en-us/library/dd318837(VS.85).aspx). When I tried to compile my code in Visual Studio 2008 Pro, I received the following errors: ``` vertexbuffers.cpp(31) : error C3861: 'glGenBuffers': identifier not found vertexbuffers.cpp(32) : error C2065: 'GL_ARRAY_BUFFER' : undeclared identifier vertexbuffers.cpp(32) : error C3861: 'glBindBuffer': identifier not found vertexbuffers.cpp(33) : error C2065: 'GL_ARRAY_BUFFER' : undeclared identifier vertexbuffers.cpp(33) : error C2065: 'GL_STATIC_DRAW' : undeclared identifier vertexbuffers.cpp(33) : error C3861: 'glBufferData': identifier not found ``` When I examined `<GL\gl.h>` (contained in `C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl`), I saw: ``` /* ClientArrayType */ /* GL_VERTEX_ARRAY */ /* GL_NORMAL_ARRAY */ /* GL_COLOR_ARRAY */ ``` **Update** but it would seem that those contants get defined elsewhere. How am I supposed to generate buffers if I don't have access to those functions? The documentation doesn't say that those array types are disabled. How do I get access to the **real** implementation on OpenGL on Windows?
The #defines are commented out in the header file whenever they would otherwise be repeated. Look at line 1054 of gl.h: ``` /* vertex_array */ #define GL_VERTEX_ARRAY 0x8074 ``` If this #define is actually missing then you should probably replace the file with a fresh copy. If you look at [the documentation for glGenBuffers](http://www.opengl.org/sdk/docs/man/xhtml/glGenBuffers.xml) you will see that it is only available in OpenGL 1.5 and higher. The header file for Windows only comes with OpenGL 1.2 and you should use the extension mechanism to access the newer functionality. If you call [wglGetProcAddress](http://www.opengl.org/sdk/docs/man/xhtml/glGenBuffers.xml) with the function name, e.g. ``` void (__stdcall *glGenBuffers)(GLsizei,GLuint*) = wglGetProcAddress("glGenBuffers"); ``` then you have a pointer to the function.
You might give GLEW a shot: <http://glew.sourceforge.net/> I'm pretty sure I used it at some time in the past, and makes this sort of thing a little easier and more portable.
Trouble porting OpenGL app to Windows
[ "", "c++", "windows", "visual-studio", "opengl", "" ]
I've inherited a asp.net website project that currently runs SQL Server 2000 as its backend. I've been doing some databases changes on a local copy of the db using SQL Server 2005 Express. I've create a table using `varchar(max)` columns. They are used to stored snippets of XHTML that are of arbitrary length. While browsing around on stackoverflow I came across this: [Are there any disadvantages to always using nvarchar(MAX)?](https://stackoverflow.com/questions/148398/are-there-any-disadvantages-to-always-using-nvarcharmax) User mattruma says he found out the "hard way" about using `varchar(max)` on SQL Server 2000. What should I use instead of `varchar(max)` given that the live database runs on SQL Server 2000? Thanks in advance for any help!
It sounds like the `varchar(MAX)` limitations are a moot point if your live DB is SQL Server 2000, which doesn't support them. If you have more than 8K characters to store you are pretty much left with the only other option, a `TEXT` column. However, beware that `TEXT` columns have a lot of limitations too. For example you can't sort or group on them easily, nor can you compare them for equivalency with other columns. That is you can't say `Select * from mytable where Mytext1 = mytext2`. Other relevant concerns: * I'd suggest using an `NText` or `NVarchar` column regardless of the way you go to support Unicode. * If the table has a lot of other columns and the `varchar(8000)` column is likely to be frequently close to full, you may have problems with the row limit of 8K. Keep this in mind too.
`VARCHAR(Max)` was introduced in SQL Server 2005, and will not work on SQL Server 2000. You need to use either `VARCHAR(8000)` assuming that will be big enough. Otherwise you will need to use `TEXT` **Edit** Also if you switch to `VARCHAR(8000)` keep in mind there is a limit that a single row cannot have more then 8060 bytes. So if you fill up a `varchar(8000)` table and have a bunch of other large columns you will get an error. This is where `Text` comes in. `Text` has performance implication because by default it is stored in a separate location, and they keep a pointer in a table. There is a set option which changes this behavior so that text types are kept in the table until they reach a certain size. If you have mostly small blobs you might want to enable this.
varchar(max) MS SQL Server 2000, problems?
[ "", "sql", "sql-server", "varchar", "" ]
Hey all. I'm trying to see about handling events in a console application. I would prefer to not use silent WinForms (though I understand that that's one way) to do it. I've read over a similar question and its response. See response text below ([link](https://stackoverflow.com/questions/687146/webbrowser-control-console-application-events-not-firing/687165#687165)): > The basic requirement of an STA thread > is that it needs to run a message > pump. In Windows Forms, you can use > Application.Run. Or you could write > the message pump by hand, using > user32!GetMessage & DispatchMessage. > But it's probably easier to use the > one in WinForms or WPF. What the basic structure of a program that uses "user32 -> GetMessage" & "user32 -> DispatchMessage"?
See the topic "Using Messages and Message Queues" in MSDN (under Win32 and COM Development > User Interface > Windows User Experience > Windows Management > Windows User Interface > Windowing > Messages and Message Queues; you'll probably need to take a look at the other articles and samples in the same section). Quick summary, omitting error handling and using C syntax rather than C# for reasons discussed below: ``` RegisterClass(...); CreateWindow(...); ShowWindow(...); // probably not in your case while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } ``` As you can see from the window setup boilerplate, this still relies on "silent windows," albeit created and message-pumped via the Win32 API rather than through WinForms. So you're not really gaining anything by doing this way. Hence my feeling there's not much point translating this stuff into C# -- if the only solution to your problem is an invisible window, you may as well use an invisible Windows Form and all the friendly wrappers that come with that platform. However, if you're not actually using a Windows Forms control like the poster of the linked question, then you can quite happily use .NET events in a console application. The restriction to STA and the need for a message pump is specific to receiving events from WinForms and ActiveX controls like the WebBrowser (or messages from Win32 HWNDs, though that doesn't necessarily require STA).
What kind events do you want to handle? Setting up a message pump will allow you to process Windows API messages. But since this is a console app, I can't think of any Windows API messages that would be of interest. We tend to think of "Events" as being associated with Windows messages because controls in Windows Forms application respond to user input using EventHandler delegates, which are called in response to Windows API messages. However, there's no reason you can't use delegates in a console app; and you don't need a message pump. You can even use the EventHandler delegate, altough it will seem out of place because it won't be resonding to Windows API messages. Of course there are other kinds of "events" that you might be interested in. The most common kind of event scenario involving a console app is to wait for input from the console (stdin). It's also common to block on a WaitHandle or other synchronization object if there are multiple threads in use. Both of these cases could be considered a type of event handling. If you create a hidden window (a time honored practice), you'll still need a Windows message to respond to. So the question is: to what, or to whom, are you trying to respond?
C# Console App + Event Handling
[ "", "c#", "event-handling", "console-application", "" ]
I finally figured out [how to print transformed XML](https://stackoverflow.com/questions/707518/printing-transformed-xml) without prompting the user or showing an IE window, but now I need to specify a number of copies and possibly other printer settings. Is there a way to programmatically change printer settings on a WebBrowser control? The code in question: ``` private static void PrintReport(string reportFilename) { WebBrowser browser = new WebBrowser(); browser.DocumentCompleted += browser_DocumentCompleted; browser.Navigate(reportFilename); } private static void browser_DocumentCompleted (object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser browser = sender as WebBrowser; if (null == browser) { return; } browser.Print(); browser.Dispose(); } ```
The only method I've had success with is modifying the registry on the fly (and changing them back to not affect anything else). You can find the settings you need at "Software\Microsoft\Internet Explorer\PageSetup" under CurrentUser. To change the printer, you can use this: ``` using System.Management public static bool SetDefaultPrinter(string defaultPrinter) { using (ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer")) { using (ManagementObjectCollection objectCollection = objectSearcher.Get()) { foreach (ManagementObject mo in objectCollection) { if (string.Compare(mo["Name"].ToString(), defaultPrinter, true) == 0) { mo.InvokeMethod("SetDefaultPrinter", null, null); return true; } } } } return false; } ``` As for the number of copies, you can always put the WebBrowser.Print in a while loop.
``` string strKey = "Software\\Microsoft\\Internet Explorer\\PageSetup"; bool bolWritable = true; RegistryKey oKey = Registry.CurrentUser.OpenSubKey(strKey, bolWritable); Console.Write(strKey); if (stringToPrint.Contains("Nalog%20za%20sluzbeno%20putovanje_files")) { oKey.SetValue("margin_bottom", 15); oKey.SetValue("margin_top", 0.19); } else { //Return onld walue oKey.SetValue("margin_bottom", 0.75); oKey.SetValue("margin_top", 0.75); } ```
How do I programmatically change printer settings with the WebBrowser control?
[ "", "c#", "winforms", "printing", "webbrowser-control", "" ]
I have a C++ DLL (no code) that I want to expose to .NET applications. After pondering all the options I have/know of/could find (COM, P/Invoke, SWIG, etc.), I'm writing a .NET Class Library (in C++/CLI). Now the resulting DLL (class library) requires the original DLL and its dependencies, too. My problem lies in automagically keeping track of such things, so that applications that use the wrapper don't have to keep track of the other (native) DLLs (especially if the original DLL(s) develop a new dependancy). To be more precise (and have something concrete to discuss), I'm trying to wrap `cmr`, so I write `MR`, the class library (which depends on `cmr`, naturally). `cmr` depends on `PNL`, `OpenCV`, and others. When I tried adding a reference to `MR` in a (C#) project, Visual Studio (2005 SP1) just copied `MR.DLL`, leaving all the dependencies behind, and then complaining (throwing a `FileNotFoundException` about missing modules). Manually copying `cmr`, `PNL`, etc. to the `bin` directory fixed the problem. Without further ado, my question is this: Is there a way for .NET apps to only add a reference to one DLL, and everything *just works*? I've been scouring through Google and SO, to no avail... **EDIT**: mergebin seems the closest to what I'm looking for, but it can only merge a .NET DLL with one native DLL. Too bad one can't merge native DLLs.
You might take a look at [mergebin](http://www.koushikdutta.com/2008/09/day-6-mergebin-combine-your-unmanaged.html), a tool that allows you to combine unmanaged and managed DLLs into one assembly. [System.Data.SQLite](http://sqlite.phxsoftware.com/) uses this approach.
I'm currently having a very similar problem. One big step too meet my goal was to copy the Native .DLL into the output directory by a pre-built step in the C++/CLI project and add the linker option ``` /ASSEMBLYLINKRESOURCE:"$(OutDir)\Native.dll" ``` This writes into the resulting assembly that there is a file "Native.dll" that belongs to the assembly. Now all projects referencing that project/assembly will also copy the Native.dll around! (It should also go into the GAC if you put you're assembly there - I didn't check that). Okay, you still have to add all depending native.dll's. I also don't know if the native DLL is found on run-time if you load the assembly via Assembly.LoadFrom() from a very different path (this is something I have to solve for my problem because our C++/CLI wrapper assembly is needed by the Visual Studio designer). I hope this helps you a bit for you're problem. **EDIT:** Further investigations showed that the Wrapper .DLL always finds the native .DLL...that's the good thing. The bad thing is that the Visual Studio Designer copies the needed assemblies to a temporary directory (somewhere inside the user directory) when you open a form. When it copies the assemblies it ignores the linked resources and by this the native .DLL!
Track DLL dependencies for wrapping a native C++ DLL to .NET
[ "", "c#", "dll", "interop", "c++-cli", "" ]
I've been following a tutorial "McGugan - Beginning Game Development with Python and Pygame (Apress, 2007)" and in the code at around chapter five involving object movement I keep getting invalid syntax alerts on '-' being used in the code. It isn't up to date but I would've thought a subtract wouldn't be changed in any updates due to its simplicity and necessity. This is the code I have: ``` background_image_filename = 'sushiplate.jpg' sprite_image_filename = 'fugu.png' import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image_filename).convert() sprite = pygame.image.load(sprite_image_filename).convert_alpha() clock = pygame.time.Clock() position = Vector2(100.0, 100.0) speed = 250. heading = Vector2() while True: for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == MOUSEBUTTONDOWN: destination = Vector2(*event.pos) – Vector2(*sprite.get_size())/2. heading = Vector2.from_points(position, destination) heading.normalize() screen.blit(background, (0,0)) screen.blit(sprite, position) time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 distance_moved = time_passed_seconds * speed position += heading * distance_moved pygame.display.update() ``` am I doing something wrong or is it just simply outdated? Any help is much needed.
In this line: ``` destination = Vector2(*event.pos) – Vector2(*sprite.get_size())/2. ``` You somehow typed the character "`–`" (EN DASH) instead of "`-`" (HYPHEN-MINUS). Use "`-`" (HYPHEN-MINUS) instead, like this: ``` destination = Vector2(*event.pos) - Vector2(*sprite.get_size())/2. ```
I can't be sure without a stack trace, but I have a hunch that it's the wrong - symbol. What editor are you using? Is it possible that your editor is taking the - symbol and turning it into a fancier dash, like an ndash or an mdash?
Pygame Invalid Syntax I just can't figure out
[ "", "python", "syntax", "pygame", "" ]
I've already checked out the question [Deleting duplicate records using a temporary table](https://stackoverflow.com/questions/633860/deleting-duplicate-records-using-a-temporary-table) and it doesn't quite go far enough to assist me with this question: I have a table of approximately 200,000 address locations hosted on a ***SQL 2000 Server***. This table has a huge problem with duplicate data in the table caused by invalid input from various parties over the years. I need to output a list of duplicate records so I can begin the long process of cleaning them up. So consider the following table structure: ``` Table Company( CompanyId NVarChar(10) Not Null Constraint PK_Locations Primary Key, CompanyName NVarChar(30), CompanyAddress NVarChar(30), CompanyCity NVarchar(30), CompanyState Char(2), CompanyZip NVarChar(10), DateCreated DateTime, LastModified DateTime, LastModifiedUser NVarChar(64) ) ``` For the first parse I'm not even going to worry about typos and variations of spelling yet which is going to be a greater nightmare down the road that I haven't even got the first clue about solving yet. So for this part a record is considered to be duplicate when multiple records match on the following conditions: > (CompanyName Or CompanyAddress) And CompanyCity And CompanyState Zip is excluded because so many of the locations are missing zip/postal codes and so many are entered incorrectly that it just makes for a far less accurate report if I include them. I realize that there may legitimately be multiple locations for a company within a single city/state [for instance McDonalds, just off the top of my head], and there may legitimately be multple companies at a single address within a city and state [for instance inside a shopping mall or office building], but for now we will consider that these at least warrant some level of human attention and will include them in the report. Matches on single fields are a piece of cake, but I'm coming unstuck when I get to multiple fields, especially when some are conditional.
``` WITH q AS ( SELECT Company.*, ROW_NUMBER() OVER (PARTITION BY CompanyState, CompanyCity, CompanyName ORDER BY CompanyID) AS rnName, ROW_NUMBER() OVER (PARTITION BY CompanyState, CompanyCity, CompanyAddress ORDER BY CompanyID) AS rnAddress FROM Company ) SELECT * WHERE rnName > 1 OR rnAddress > 1 ``` Note, though, that if your data will look like this: ``` CompanyID CompanyName CompanyAddress --------- ----------- -------------- 1 McDonalds Avenue 1 2 McDonalds Avenue 2 3 Starbucks Avenue 2 ``` , then both records `2` and `3` will be deleted (which is what you requested but probably not what you wanted) If you just want to list all rows having duplicates, then issue: ``` SELECT * FROM Company co WHERE EXISTS ( SELECT 1 FROM Company cn WHERE cn.CompanyState = co.CompanyState AND cn.CompanyCity = co.CompanyCity AND cn.CompanyName = co.CompanyName AND cn.CompanyID <> co.CompanyID ) OR EXISTS ( SELECT 1 FROM Company ca WHERE ca.CompanyState = co.CompanyState AND ca.CompanyCity = co.CompanyCity AND ca.CompanyAddress = co.CompanyAddress AND ca.CompanyID <> co.CompanyID ) ``` This will work in `SQL Server 2000` too. Having indexes on `(CompanyState, CompanyCity, CompanyName)` and `(CompanyState, CompanyCity, CompanyAddress)` will greatly improve this query.
``` SELECT C1.CompanyID, C2.CompanyID FROM Company C1 INNER JOIN Company C2 ON (C2.CompanyName = C1.CompanyName OR C2.CompanyAddress = C1.CompanyAddress) AND C2.CompanyCity = C1.CompanyCity AND C2.CompanyState = C2.CompanyState AND C2.CompanyID > C1.CompanyID ``` If you have three or more matches then they will appear multiple times in the list. There are various ways to handle that depending on what exactly you want to get back from the query. I would also strongly suggest that you look into better front-end coding to restrict how addresses are getting into your system as well as user training.
How do I extract duplicate records from a table using multiple fields?
[ "", "sql", "sql-server", "t-sql", "" ]
Probably a problem many of you have encountered some day earlier, but i'm having problems with rendering of special characters in Flash (as2 and as3). So my question is: What is the proper and fool-proof way to display characters like ', ", ë, ä, etc in a flash textfield? The data is collected from a php generated xml file, with content retrieved from a SQL database. I believe it has something to do with UTF-8 encoding of the retrieved database data (which i've tried already) but I have yet to find a solid solution.
*Just* setting the header to UTF-8 won't work, it's a bit like changing the covers on a book from english to french and expecting the contents to change with it. What you need to to is to make sure your text is UTF-8 from beginning to end, store it as that in the database, if you can't do that, make sure you encode your output properly. If you get all those steps down it should all work just fine in flash, assuming you've got the proper glyphs embedded unless you're using a system font. AS2 has a setting called useSystemCodepage, this may *seem* to solve the problem, but will likely make it break even more for users on different codepages, try to avoid this unless you're really sure of what you're doing. Sometimes having those extra letters in your language actually helps ;)
If your special characters are a part of Unicode set (and they should be, otherwise you're basically on your own), you just need to ensure that the font you're using to render the text has all of the necessary glyphs, and that the database output produces proper unicode text. Some fonts don't neccessarily include all the unicode glyphs, but only a subset of them (usually dropping international glyphs and special characters). Make sure the font has them (test the font out in a word processor, for example). Also, if you're using embedded fonts, be sure to embed all the characters you need to use.
Proper rendering of special characters in Flash, parsed from XML and generated with PHP/MySQL
[ "", "php", "xml", "flash", "" ]
I'm maintaining a legacy embedded device which interacts with the real world. Generally speaking, this device collects data from sensors, processes the data using its internal algorithm, and displays warning when data reaches a certain "bad" state. For debugging purposes, we wish this device will send us on a regular basis many of the data it receives, as well as the data after it processed it. We reached to the conclusion that most of the data can be described in a tabular form, something along the lines of ``` sensor|time|temprature|moisture ------+----+----------+-------- 1 |3012|20 |0.5 2 |3024|22 |0.9 ``` We obviously need to support more than one form of table. So basically we need a protocol that is able to accept a certain set of tables description , and then to deliver table data according to its description. An example pseudo code for sending data is: ``` table_t table = select_table(SENSORS_TABLE); sensors_table_data_t data[] = { {1,3012,20,0.5}, {1,3024,22,0.9} }; send_data(table,data); ``` An example pseudo code for receiving data is: ``` data_t *data = recieve(); switch (data->table) { case SENSORS_TABLE: puts("sensor|time|temprature|moisture"); for (int i=0;i<data->length;i++) printf( "%5s|%4s|%9s|%9s\n", data->cell[i]->sensor, data->cell[i]->time, data->cell[i]->temprature, data->cell[i]->moisture); break; case USER_INPUT_TABLE: ... } ``` Defining the tables could be done either off line both at the device and at the client computer communicating with it, or online. We can add a simple handshake protocol to agree upon table's format at the device's boot-time. Since this is a legacy device, it supports only RS232 communication, and since its CPU is pretty slow (equivalent to 486), we cannot afford using any XML-like data transfer methods. Those are too expensive (either computation-time-wise, or bandwidth-wise). Sending raw SQL commands was also considered and rejected due to bandwidth considerations. **[edit]** For clarification, too reduce the overhead of sending the table header each time, I'm trying to avoid sending the table header each time I'm sending data. So that each time I'm sending a table row, I'll just have to send the tables id. I also would like to note that most of the data I wish to pass is numerical, so text-based protocols are too wasteful. Lastly I've seen Google's protocol buffers, it's close enough but it doesn't support C. **[/edit]** Any idea about a known protocol or implementation like what I described? Any better idea to send this data? I'm aware to the fact that this protocol is not very hard to design, I had in mind a two phase protocol: 1) Handshake: send the headers of all tables you wish to fill. Each table description would include information about the size of each column. 2) Data: send the table index (according to handshake) followed by the actual data. Data will be followed by a checksum. But I wish to avoid the small details of such design, and use some ready-made protocol. Or even better, use an available implementation.
I am not aware of any protocol which does this (there might be one, but I don't know it.) I'm sure you've thought of this: why not pass the *format* as a binary data stream as well? pseudocode: ``` struct table_format_header { int number_of_fields; /* number of fields that will be defined in table */ /* sent before the field descriptions themselves */ }; struct table_format { char column_name[8]; /* name of column ("sensor"); */ char fmt_specifier[5]; /* format specifier for column */ ... (etc) } ``` Then you can compute the fields/columns (somehow), transmit the `header` struct so that the recipient can allocate buffers, and then iteratively transmit `table_format` structs for each of those fields. The struct would have all the information you need pertaining to that header - name, number of bytes in field, whatever. If space is really constricted, you can use bit-fields (`int precision:3`) to specify the different attributes
**You may want to try protocol buffers.** ``` http://code.google.com/p/protobuf/ ``` > Protocol Buffers are a way of encoding > structured data in an efficient yet > extensible format. Google uses > Protocol Buffers for almost all of its > internal RPC protocols and file > formats. Building off rascher's comment, protobufs compile the format so it's ridiculous efficient to transmit and receive. It's also extensible in case you want to add/remove fields later. And there are great APIs (e.g. protobuf python).
binary format to pass tabular data
[ "", "sql", "c", "database", "embedded", "protocols", "" ]
I am very in tune with relational modeling but new to LDAP modeling and am looking for best practices for designing LDAP schemas. Would love to know what are the equivalents of third normal form and other practices in the world of LDAP? Links to white papers that expand on this subject are greatly appreciated.
Pick a standard schema, such as [core](https://www.rfc-editor.org/rfc/rfc2256), [cosine](http://www.faqs.org/rfcs/rfc4524.html), [inetOrgPerson](https://www.rfc-editor.org/rfc/rfc2798), [eduPerson](http://middleware.internet2.edu/eduperson/), [Java Objects](http://www.ietf.org/rfc/rfc2713.txt), [etc.](http://docs.sun.com/source/816-6699-10/schemaov.html) appropriate for your intended purpose. Most LDAP servers come with a collection of defaults. Prefer the existing elements, but if you need to [extend the schema](http://www.openldap.org/doc/admin22/schema.html), prefix with comCompany (your company's domain name, or other unique identifier) to avoid conflicts from future standard elements.
Our experience shows the design of the schema and the DIT is very dependent on the purpose of the of the LDAP server. For the schema, it is, generally, best to stick with the industry or LDAP server vendor's "standard". For the structure of the DIT, unless it is for a file and print service (ie Active Directory) or OES (Netware) then generally a "flat" structure scales better. If it is a large implementation (ie>100k) then groups should be avoided, if possible. -jim
LDAP Modeling Best Practices
[ "", "sql", "database-design", "active-directory", "ldap", "" ]
For a debugging and logging library, I want to be able to find, at runtime, a list of all of the source files that the project has compiled and linked. I assume I'll be including some kind of header in each source file, and the preprocessor \_\_FILE\_\_ macro can give me a character constant for that file, so I just need to somehow "broadcast" that information from each file to be gathered by a runtime function. The question is how to elegantly do this, and especially if it can be done from C as opposed to C++. In C++ I'd probably try to make a class with a static storage to hold the list of filenames. Each header file would create a file-local static instance of that class, which on creation would append the FILE pointer or whatever into the class's static data members, perhaps as a linked list. But I don't think this will work in C, and even in C++ I'm not sure it's guaranteed that each element will be created.
I wouldn't do that sort of thing right in the code. I would write a tool which parsed the project file (vcproj, makefile or even just scan the project directory for \*.c\* files) and generated an additional C source file which contained the names of all the source files in some kind of pre-initialized data structure. I would then make that tool part of the build process so that every time you do a build this would all happen automatically. At run time, all you would have to do is read that data structure that was built.
I agree with Ferruccio, the best way to do this is in the build system, not the code itself. As an expansion of his idea, add a target to your build system which dumps a list of the files (which it has to know anyway) to a C file as a string, or array of strings, and compile this file into your source. This avoids a lot of complication in the source, and is expandable, if you want to add additional information, like the version number from your source code control system, who built the executable, etc.
Registering each C/C++ source file to create a runtime list of used sources
[ "", "c++", "c", "logging", "singleton", "static-members", "" ]
> **Possible Duplicate:** > [When should you use 'friend' in C++?](https://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c) I see a lot of people recommending a function/class to be made a friend of another class here in SO though there are other alternatives. Shouldn't friend be sparingly used in C++? I feel other options must be considered before deciding on using the friend feature. Opinions/suggestions are welcome.
Without specific examples this is hard to decide. While `friend` isn't strictly necessary it does have its uses. If, as you claim, there are better alternatives then obviously use *them*, by simple definition of the word “better”. Or maybe the decision which solution is better isn't that clean-cut after all. Personally, I prefer to avoid it when possible but I prefer to use it over method duplication: for example, I do not like to write a `print` method just to avoid making `operator <<` a `friend` because I don't see the benefit of the duplicate method.
Some say `friend` is a violation of encapsulation. In my opinion, it is the exact contrary. Without `friend`, we would end up with either: * huge monolithic classes, that does plenty of things they were not meant to, just to avoid letting outer classes access their internals * badly encapsulated classes: to separate concerns and write classes with one and only one responsability, we would need to provide public access to internal data needed by the related set of classes. `friend` is a good way to overcome this issue, since it lets you free to separate responsabilities in several classes, while at the same time letting you restrict access to implementation details to the few functions or types which need them.
friend class/function in c++
[ "", "c++", "friend", "" ]
I have a very strange behavior that only seems to happen on one form. Basically I am creating an instance of a `Form`, and calling `Show()` to display the form non-blocking. In that form's `Load` event handler, I have some logic that may call `this.Close()` under certain circumstances. This closes the form, but then the form `Show()` method in the client code throws an `ObjectDisposedException`. The stack trace from the ObjectDisposedException is as follows: > at System.Windows.Forms.Control.CreateHandle() > at System.Windows.Forms.Form.CreateHandle() > at System.Windows.Forms.Control.get\_Handle() > at System.Windows.Forms.ContainerControl.FocusActiveControlInternal() > at System.Windows.Forms.Form.SetVisibleCore(Boolean value) > at System.Windows.Forms.Control.Show() > ...etc. This is what I'm seeing happen: 1. `Control.Show()` is called 2. my form is launched 3. the `OnFormLoad` method is called 4. the `FormLoad` event handler is called, inside of which I call `this.Close()` 5. the `OnFormClosing` method is called 6. the `FormClosing` event handler is called 7. `Dispose` is called on my form and all it's user controls and then somewhere toward the end of the `Control.Show()` method, it tries to get a handle to the form, which freaks out and throws an exception because the object is marked disposed. My real question is, why can I do this exact same thing on every other form I have without exceptions? Is it a GC issue? I've tried putting a `GC.Collect()` call right after the `this.Close()` and it makes no difference. Like I said, it happens 100% of the time on this form, and never anywhere else, regardless of child user controls, scope of the form variable, etc. Any ideas?
I know this is an old issue but no one seemed to have posted the obvoius answer. You say you call `Control.Show()` and then `Form.Close()` and then the form is Disposed of. Well, unless you use MDI or use `ShowDialog` that's just as documented. Though, the short version of the `Close()` documentation is "Closes the form", it actually also disposes it implicitly under certain conditions. See the remarks section: <http://msdn.microsoft.com/en-us/library/system.windows.forms.form.close.aspx> If you want to show a form again. Use the `Hide()` method instead of `Close()`. Hope that helps other searching souls. And guys, don't stop searching at "I don't know why it works sometimes". That becomes buggy software with lots of defensive "I'll call this method again just in case" stuff. Not good.
The best way to do so : ``` this.BeginInvoke(new MethodInvoker(this.Close)); ``` this is the most simple way you wont get ObjectDisposedException
Closing a form from the Load handler
[ "", "c#", "winforms", "objectdisposedexception", "" ]
I'm creating a browser based game and at the moment I'm designing the script that updates the position of my character when he/she clicks on a different part of the map. I am using a bit of ajax to do this which send a request to a php file called position\_update.php. But for it to work I need to send two values along with it so it knows what the new position is, how do I do this? Below is my link that send the request to php file. ``` <a onClick="positionUpdate();"><img src="images/transparent.gif" border="0" /></a> ``` As a note, I'm using the php $\_GET super global to retrieve the values when they're sent. Thanks, Stanni
You need to hit the URL: ``` position_update.php?var1=val1&var2=val2 ``` PHP will parse the get string into $\_GET
BTW, you should ensure that degrades gracefully by having an equivalent href value that works for non-js users.
submit php variables with javascript (link?)
[ "", "php", "ajax", "" ]
Here is my code: ``` <?php $host = "127.0.0.1"; $portListen = 1234; $portSend = 1240; // create socket $sSender = socket_create(AF_INET, SOCK_STREAM, 0); socket_connect($sSender, $host, $portListen); socket_write($sSender, "test", strlen ("test")); $sListen = socket_create(AF_INET, SOCK_STREAM, 0); socket_set_option($sListen, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($sListen, $host, $portSend); socket_listen($sListen,1); $dataSock = socket_accept($sListen); echo socket_read($dataSock, 3, PHP_NORMAL_READ); // close sockets socket_close($sSender); socket_close($sListen); ?> ``` I send "test" to another application, it receives, and send back "ack". Problem is, I can only do it once. If I refresh, I get the address is already used error. I tried the solutions suggested on [php.net](http://my.php.net/manual/en/function.socket-close.php) but to no avail. Trying to socket\_shutdown() before socket\_close() only give me not connected warning, and upon refreshing will give me a never ending loading. From what I understand the reason socket is not immediately closed is because there is still data in the buffer. But as you can see I explicitly state to listen to only 1 connection. Plus I am only sending 3 characters from my application and reading 3 in this script. What am I doing wrong? edit: The reason I'm using 2 sockets is because I cannot listen() after write() which give me socket is already connected error. Skipping listen() and going straight for read() after write() give me invalid argument error.
I see, after having a few hours sleep and re-analyzing my code and the documentations, I managed to fix everything. You guys are right, 1 socket is indeed enough and the correct way: ``` <?php $host = "127.0.0.1"; $portListen = 1234; $sSender = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); socket_connect($sSender, $host, $portListen) or die("Could not connect\n"); socket_write($sSender, "test", strlen ("test")) or die("Could not write output\n"); echo socket_read($sSender, 3, PHP_NORMAL_READ); socket_close($sSender); ?> ``` So simple!
After a connection is closed, the socket enters a linger state so that if (during the close) packets were lost and retransmitted, the response would be a clean acknowledgement instead of `RST` (reset) indicating no such socket was open. It's part of the TCP specification, you can't make it stop happening. `Listen(1)` doesn't mean accept only one connection, it means maintain a queue of up 1 connections waiting for an application to `accept()` them. So as soon as you accept the first, the socket is ready to listen for more. Like everybody else, I'm wondering why the odd design, but I assume it's a boiled-down example that presents your problem and doesn't necessarily present your real plan.
PHP: socket listen problem
[ "", "php", "sockets", "" ]
I create software using PHP. I'm going to sell this software so I need to protect my source code so that nobody can view it. How can I protect my PHP code so that the software still functions the same? I also need to bind the software to a particular, authorized PC. It should not run on any other PC. How can I do that? Should I encrypt using LAN MAC address? Does anyone have any other ideas?
I put together the following list a ways back - don't know if they are all current, or how many are now free, but you should find something useful here: About: 1. [Wikipedia article: PHP Accelerator](http://en.wikipedia.org/wiki/PHP_accelerator) 2. [Comparison of APC, Zend, xCache, & the Zend Framework](http://blog.digitalstruct.com/2007/12/23/php-accelerators-apc-vs-zend-vs-xcache-with-zend-framework) Software: 1. [Safeyar](http://www.safe.setyar.com/) ([Best](http://www.safe.setyar.com/)) 2. [PHP's APC](http://php.net/apc) ([PECL page](http://pecl.php.net/package/APC)) 3. [RoadSend](http://www.roadsend.com/home/index.php?pageID=compiler) 4. [Turck-mmcache](http://turck-mmcache.sourceforge.net/index_old.html) 5. [eAccelerator](http://eaccelerator.net/wiki/PoweredByeA) 6. [PHP-Accelerator](http://www.php-accelerator.co.uk) 7. [SourceGuardian](http://www.sourceguardian.com) 8. [NuSphere Nu-coder](http://www.nusphere.com/products/nucoder.htm?) 9. [Gridinsoft](http://www.gridinsoft.com/protect.php) 10. [IonCube SA-Encoder.php](http://www.ioncube.com/sa_encoder.php) Another thread on SO that adds a few more (check it out): [Can I encrypt PHP source or compile it so others can't see it? and how?](https://stackoverflow.com/questions/470409/can-i-encrypt-php-source-or-compile-it-so-others-cant-see-it-and-how) 1. [Zend Guard](http://www.zend.com/en/products/guard/) 2. [BCompiler](http://php.net/bcompiler) ([PECL page](http://pecl.php.net/package/bcompiler)) 3. [PHC](http://www.phpcompiler.org/)
What you may be looking for is not cryptography per se, but rather obfuscation. If you Google for "php obfuscate", many choices show up. The first one is from [Raizlabs](http://www.raizlabs.com/software/phpobfuscator/).
Obfuscate PHP code
[ "", "php", "obfuscation", "source-code-protection", "" ]
I'm debugging some Python that takes, as input, a list of objects, each with some attributes. I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number. Is there a more concise way than this? ``` x1.foo = 1 x2.foo = 2 x3.foo = 3 x4.foo = 4 myfunc([x1, x2, x3, x4]) ``` Ideally, I'd just like to be able to say something like: ``` myfunc([<foo=1>, <foo=2>, <foo=3>, <foo=4>]) ``` (Obviously, that is made-up syntax. But is there something similar that really works?) Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.
I like Tetha's solution, but it's unnecessarily complex. Here's something simpler: ``` >>> class MicroMock(object): ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... >>> def print_foo(x): ... print x.foo ... >>> print_foo(MicroMock(foo=3)) 3 ```
I found this: <http://www.hydrogen18.com/blog/python-anonymous-objects.html>, and in my limited testing it seems like it works: ``` >>> obj = type('',(object,),{"foo": 1})() >>> obj.foo 1 ```
Is it possible to create anonymous objects in Python?
[ "", "python", "anonymous-types", "" ]
this may seem trivial but I'm setting up, on a profile form page I'm building, a countries and states select box such that when you select the US or Canada then the states box would display states of the selected countries else it would display a None Applicable instead. My countries and states are in a database and I'm populating m y selects from that - I would like a simple yet proper way to do this - I noticed that for some reason disabling select options is not supported in all browsers :( - or is there any nice free snippet online I could use [maybe I'm feeling too lazy to code this here] I'm using JQuery for the javascripting here though. --- Edited Thanks for the replies - the cascading drop down seems to do what I need but I'm looking for a php based solution. How have mainstream websites accomplished this btw. Because I don't want to leave it to the user and end with entries including American/ Canadian states with countries that are not the US/Canada. --- The Ajax idea is what I had in mind but the thing is that the application form I'm building has a section where you can add contact addresses. Its been built such that you can add multiple addresses to the same contact. Theres an add button which just duplicates the address inputs using a javascript function so basically when you submit the form you have data like : \_POST['address[]'], \_POST['city[]'], \_POST['state[]'],\_POST['country[]'] The thing is binding this action to each instance of state and countries when created.
I think I would not even show the state selector, if neither US nor Canada has been selected from the country selector. This approach has two advantages, users from all other countries are not bothered by meaningless content, you don't have to deal with unwanted input. Now I would save the value of the country selector via AJAX and then send/activate the additional selector div with the response, if needed. After your edit: How flexible are you then? If you are stuck with some existing code then a cron job which eliminates unnecessary state entries might be another way. I mean you could also handle the state later on retrieval but I assume there is also preexisting code which creates addresses and that code doesn't check if the state makes sense...
Attach an onchanged handler to the c]Country dropdown. In the handler, use Ajax to retrieve a State/Province list for the selected country, the populate the State/Province dropdown with that list and enable the State/province dropdown. In the static HTML, disable the State/Province dropdown.
States and Countries select box - best way to do it?
[ "", "php", "jquery", "select", "combobox", "countries", "" ]
I'm using the pthread library on Linux. I'm assigning a string in thread A, and then trying to print the string in thread B. However, the string just prints out empty (I have verified that it works in thread A). Note: The string resides inside an object, which I suspect may be getting cleaned up or re-instantiated empty... The container object doesn't give me a seg fault or anything, just all the values are empty. Is this because threads cannot access memory from other threads, or because the memory is being unallocated once thread A stops? Or is it neither; it could well be a bug in my code, but I just wanted to rule this out... ### Update: Turns out it was a memory issue. With thanks to your answers, I have also [answered this my self](https://stackoverflow.com/questions/724536/does-memory-stay-allocated-when-a-c-thread-exits/730868#730868), please do comment on my answer if you agree/disagree.
Turns out, the issue was caused by incorrect use of memory, as expected. I'm 99% sure the following example is accurate; it's pretty much pseudo code, so wont compile, obviously. ### Update: Just added a 3rd solution thanks to nusi. ### The wrong way (with stack memory): ``` std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { MyType1 mt1; mt1.Test = "Test 1"; myMap[0] = mt1; } void onlyFunctionRunFromThread2() { MyType1 mt1 = myMap[0]; // This actually does print "Test 1", so the memory is being accessed. std::cout << mt1.Test << endl; /* However, because we're using stack memory here, this value is lost * when we go back to thread #1. */ mt1.Test = "Test 2"; } void secondFunctionFromThread1() { MyType1 mt1 = myMap[0]; // This will actually print out "Test 1", where "Test 2" is expected! std::cout << mt1.Test << endl; } ``` ### The *complicated*, correct method (using heap memory): See also the simple method which uses stack memory. ``` std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { // Use heap memory so the memory stays allocated. MyType1 *mt1 = new MyType1(); mt1->Test = "Test 1"; myMap[0] = *mt1; } void onlyFunctionRunFromThread2() { /* Now, get a pointer to the object; we can't use stack memory * here because the values assigned would be lost as soon as * we try and access them from secondFunctionFromThread1() */ MyType1 *mt1 = &myMap[0]; // As expected, this prints "Test 1" std::cout << mt1->Test << endl; /* Now, because we're assigning to memory on the heap, this will * stay assigned until the entire application exits, yay! */ mt1->Test = "Test 2"; } void secondFunctionFromThread1() { /* Not sure if using heap memory here is neccecary, but we'll do * it anwyay just to play on the safe side... let me know if this * is pointless... */ MyType1 *mt1 = &myMap[0]; // Hurray, this prints "Test 2"!!! :) std::cout << mt1->Test << endl; } ``` ### The *simple*, correct method (using stack memory correctly): Thanks to nusi for [his answer](https://stackoverflow.com/questions/724536/does-memory-stay-allocated-when-a-c-thread-exits/731025#731025). ``` std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { MyType1 mt1; mt1.Test = "Test 1"; myMap[0] = mt1; } void onlyFunctionRunFromThread2() { /* Using the & before the variable turns it into a reference, so * instead of using stack memory, we use the original memory. * NOTE: Is this explanation correct? */ MyType1 &mt1 = myMap[0]; // This actually does print "Test 1", so the memory is being accessed. std::cout << mt1.Test << endl; // We're assigning to the reference, so this works. mt1.Test = "Test 2"; } void secondFunctionFromThread1() { MyType1 mt1 = myMap[0]; // Prints "Test 1" as expected. std::cout << mt1.Test << endl; } ```
Threads, unlike processes, share a common memory space inside a process (each thread has its own stack, but heaps are typically shared). Therefore, when you quit a thread, memory allocated from the shared heap is not freed automatically. But, for example, if you have allocated a string object on the stack and passed it somewhere by a simple pointer, the destructor will free the memory when the thread exits.
Does memory stay allocated when a C++ thread exits?
[ "", "c++", "multithreading", "pthreads", "" ]
I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest). Then I realized I didn't even know if a NN is good for minimization. What do you think?
Neural networks are classifiers. They separate two classes of data elements. They learn this separation (usually) by preclassified data elements. Thus, I say: No, unless you do a major stretch beyond breakage.
It sounds to me like this is a problem more suited to [genetic algorithms](http://en.wikipedia.org/wiki/Genetic_algorithm) than neural networks. Neural nets tend to need a bounded problem to solve, requiring training against known data, etc. - whereas genetic algorithms work by finding better and better approximate solutions to a problem without requiring training.
Can a neural network be used to find a functions minimum(a)?
[ "", "python", "artificial-intelligence", "neural-network", "minimization", "" ]
I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys. ex: ``` data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) ``` I want to sort the list in reverse order by value of 'date'
You can do it this way: ``` list.sort(key=lambda item:item['date'], reverse=True) ```
``` from operator import itemgetter your_list.sort(key=itemgetter('date'), reverse=True) ``` ### Related notes * don't use `list`, `dict` as variable names, they are builtin names in Python. It makes your code hard to read. * you might need to replace dictionary by `tuple` or [`collections.namedtuple`](http://docs.python.org/library/collections.html#collections.namedtuple) or custom struct-like class depending on the context ``` from collections import namedtuple from operator import itemgetter Row = namedtuple('Row', 'title date') rows = [Row(row.title, row.created_on) for row in data] rows.sort(key=itemgetter(1), reverse=True) ``` Example: ``` >>> lst = [Row('a', 1), Row('b', 2)] >>> lst.sort(key=itemgetter(1), reverse=True) >>> lst [Row(title='b', date=2), Row(title='a', date=1)] ``` Or ``` >>> from operator import attrgetter >>> lst = [Row('a', 1), Row('b', 2)] >>> lst.sort(key=attrgetter('date'), reverse=True) >>> lst [Row(title='b', date=2), Row(title='a', date=1)] ``` Here's how `namedtuple` looks inside: ``` >>> Row = namedtuple('Row', 'title date', verbose=True) class Row(tuple): 'Row(title, date)' __slots__ = () _fields = ('title', 'date') def __new__(cls, title, date): return tuple.__new__(cls, (title, date)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Row object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result def __repr__(self): return 'Row(title=%r, date=%r)' % self def _asdict(t): 'Return a new dict which maps field names to their values' return {'title': t[0], 'date': t[1]} def _replace(self, **kwds): 'Return a new Row object replacing specified fields with new values' result = self._make(map(kwds.pop, ('title', 'date'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result def __getnewargs__(self): return tuple(self) title = property(itemgetter(0)) date = property(itemgetter(1)) ```
sorting a list of dictionary values by date in python
[ "", "python", "" ]
**Sorry everyone. It appears that I am a dumbass! The query works fine when I run it against the live database versus my test database...gotta pay more attention to that stuff!** I am having a problem with the statement shown below. It works fine if I run it against one database (sans the DBCATALOG.dbo), so no problem there. When I try running the statement as is, I get an incorrect syntax near ‘<’. I also tried using a tool to create a union for all of our databases (see second statement). This results in an invalid object name error (Invalid object name 'TF7-User-Demo-ScheduledRestore-03.dbo.LinkedDocumentFolderTable', Invalid object name 'TF7-TestDatabase-ScheduledRestore.dbo.LinkedDocumentFolderTable', etc.). It seems to be tied to the .[dbo], but I just don’t know what causes the problem. I can’t find anything in the book stating a count can’t be performed across multiple databases…. ``` SELECT CNT=COUNT(*) FROM <DBCATALOG>.[dbo].[LinkedDocumentFolderTable] WHERE IsUnmanagedFolder = 1 SELECT 'TF7-User-Demo-ScheduledRestore-03' AS DBCatalog, * FROM(SELECT COUNT(*) FROM [TF7-User-Demo-ScheduledRestore-03].[dbo].[LinkedDocumentFolderTable] WHERE IsUnmanagedFolder = 1)rsOne UNION ALL SELECT 'TF7-TestDatabase-ScheduledRestore' AS DBCatalog, * FROM(SELECT COUNT(*) FROM [TF7-TestDatabase-ScheduledRestore].[dbo].[LinkedDocumentFolderTable] WHERE IsUnmanagedFolder = 1)rsOne ```
Your syntax seems to be weird. Try next: ``` SELECT 'TF7-User-Demo-ScheduledRestore-03' AS DBCatalog, COUNT(*) FROM [TF7-User-Demo-ScheduledRestore-03].[dbo].[LinkedDocumentFolderTable] WHERE IsUnmanagedFolder = 1 ``` Also do you have all neccessary permissions set? (I'd better not ask, do you have such databases like TF7-User-Demo-ScheduledRestore-03 on same server present at all?)
I'm not totally sure what you're actually trying to do, but those angle (< >) and square ([ ]) brackets aren't valid to have in the queries. Which database engine are you using?
Problem with Count Statement for Multiple Databases
[ "", "sql", "" ]
I have a web service I'm trying to use on one of my sites. When I call the web service (which is created in C#) I get an error on several lines where try to execute an SP, which was created as an assembly. This web service works on our development environment but not on live. Our live and dev environments run on the same server, but different databases. The error is: Sql Exception: Failed to initialize the Common Language Runtime (CLR) v2.0.50727 due to memory pressure. Please restart SQL server in Address Windowing Extensions (AWE) mode to use CLR integration features. CLR is enabled on both live and dev. No temp tables are used. I believe its already in AWE mode. WSE was installed on the server and I'm using .Net 2.0 The SP I'm trying to call in the web service takes a string as an argument and returns a byte[]. Is there a size limitation on web services? Any suggestions? Edit: We're using MSSQL 2005
The boss man had to increase the amount of ram available to the system as most of it was dedicated to sql server. This cleared up the issue.
If the process is working on your dev server I'd have to say that it's not a limitation of the system as it's clearly demonstrated working. I'm afraid it's probably a case of crawling over both systems (IIS & SQL Server) on each box comparing configurations. I think the error message you are getting is indicating that AWE mode isn't enabled on the production box, so that would be the first thing to check. Good luck!
.Net Web Service Memory Pressure Error
[ "", "c#", "web-services", "memory-management", "assemblies", "clr", "" ]
We are binding a list of custom objects to an ASP.NET DropDownList in C# but we want to allow for the DropDownList to not have anything selected initially. One way of doing this might be to create an intermediate list of strings, populate the first one with an empty string and then populate the rest of the list with the custom object information. This doesn't seem very elegant however, does anyone have a better suggestion?
Yes, create your list like so: ``` <asp:DropDownList ID="Whatever" runat="server" AppendDataBoundItems="True"> <asp:ListItem Value="" Text="Select one..." /> </asp:DropDownList> ``` (Note the use of **`AppendDataBoundItems="True"`**) And then when you bind, the bound items are put after the empty item rather than replacing it.
You could add to the databound event: ``` protected void DropDownList1_DataBound(object sender, EventArgs e) { DropDownList1.Items.Insert(0,new ListItem("","")); } ```
Add empty item to dropdownlist of custom objects in C#
[ "", "c#", "asp.net", "" ]
I have particular division in my web page. i want to print that div only when click "print" in my web page. i have some javascript code. But that is not well formatted. Is there any javascript to print particular division from my web page? Thanks in advance * Gnaniyar Zubair
You can specify CSS stylesheets [with the attribute `media="print"`](http://www.w3.org/TR/CSS2/media.html) and apply the style `display: none;` to all elements except those which you want printed. For example: print.css ``` * { display: none; } div.print_block { display: block; } ``` page.html ``` <HEAD> <LINK rel="stylesheet" type="text/css" media="print" href="print.css" /> </HEAD> <DIV class="print_block"> ... </DIV> ```
If you want to hide some divs when printing, you can set them to "display: none" in a print media section of your stylesheet, and they won't appear. eg, in your stylesheet: ``` @media print { div.header { display: none; } div.printable { page-break-inside: avoid; page-break-after: always; } } ``` This answer is almost exactly the same as the two which beat me by 4 minutes :-) , just a note that you don't need a whole separate stylesheet if you don't want to ... Also, the "page-break-inside: avoid;" and "page-break-after: always;" clauses are good for printing out a few divs, each on its own page.
Print using Javascript?
[ "", "javascript", "css", "printing", "" ]
what I'm trying to do is have a project-wise static dictionary so I can access a single list from anywhere in my code. Until now, I came up with this solution, a public static class with a public property: ``` public static class Common { public static StringDictionary Domains { get { StringDictionary list = new StringDictionary(); list.Add("212", "Location A"); list.Add("555", "Location B"); list.Add("747", "Location C"); list.Add("000", "Location D"); return list; } } } ``` That I use in this way (I use it to replace the content of a cell in a gridview): ``` if (Common.Domains.ContainsKey(e.Row.Cells[5].Text)) { e.Row.Cells[5].Text = Common.Domains[e.Row.Cells[5].Text]; } else { e.Row.Cells[5].Text = "n/a"; } ``` But I don't know if this is an efficient solution, and/or if there are other (better) ways to do this... Can somebody give a hint? Thanks in advance, Andrea.
You probably don't want to re-create the list every time the property is accessed. Move the construction into the static constructor: ``` public static class Common { private static StringDictionary _domains; static Common() { _domains = new StringDictionary(); _domains.Add("212", "Location A"); _domains.Add("555", "Location B"); _domains.Add("747", "Location C"); _domains.Add("000", "Location D"); } public static StringDictionary Domains { get { return _domains; } } } ``` And you should be aware, that the dictionary returned is not read-only. So a client of this class could modify the collection (e.g. add/remove some entries).
@Jeff Fritz is correct in his answer, but I just wanted to add a little more about the shared access of this field among multiple threads. *StringDictionary* is only thread-safe for read operations, and not write operations, so you'll want to be careful not to modify this collection without proper locking, and you'll also want to lock the collection when iterating over it. To iterate: ``` lock(Common.Domains) { foreach(var domain in Common.Domains) { } } ``` To add a domain *outside* the static constructor: ``` lock(Common.Domains) { Common.Domains.Add("111", "Location 3"); } ``` In general, I'd be very careful when sharing a non-readonly collection via a static field so that the field isn't modified. You may want to make *StringDictionary* a *ReadOnlyCollection* instead and mark the field "readonly": ``` public static readonly ReadOnlyCollection<Pair<string, string>> domains ``` You won't get O(1) lookups, but I'm assuming this collection will be very small, so that won't matter anyway.
StringDictionary as a common static list?
[ "", "c#", "stringdictionary", "" ]
What's the easiest way to add an `option` to a dropdown using jQuery? Will this work? ``` $("#mySelect").append('<option value=1>My option</option>'); ```
This did NOT work in IE8 (yet did in FF): ``` $("#selectList").append(new Option("option text", "value")); ``` This DID work: ``` var o = new Option("option text", "value"); /// jquerify the DOM object 'o' so we can use the html method $(o).html("option text"); $("#selectList").append(o); ```
Personally, I prefer this syntax for appending options: ``` $('#mySelect').append($('<option>', { value: 1, text: 'My option' })); ``` If you're adding options from a collection of items, you can do the following: ``` $.each(items, function (i, item) { $('#mySelect').append($('<option>', { value: item.value, text : item.text })); }); ```
Adding options to a <select> using jQuery?
[ "", "javascript", "jquery", "html-select", "" ]
(I'm using Visual Studio 2008, though I remember having similar problems with older versions as well.) I've tried several different methods (many of them mentioned in [this other question](https://stackoverflow.com/questions/320677/how-do-i-set-the-icon-for-my-application-in-visual-studio-2008)), but I am still having some strange issues: 1. When including an icon as a resource, it does show up as the executable file's icon immediately, but for the icon to show up on the taskbar, I have to restart the computer. Until then, it continues to show up as whatever the previous icon was. Cleaning the solution, restarting VS, doesn't have any effect. Not a really big issue, as it won't affect a released exe, but it would be nice to know where it's keeping the old icon cached and how to get rid of it. 2. No matter what I do, the icon displayed when alt-tabbing is the default app icon (square and white and generic). This includes embedding the icon in the executable, as well as setting `ICON_BIG` with `WM_SETICON`. As for the second matter, my code looks something like: ``` hIcon = (HICON)( LoadImage( NULL, szFilename, IMAGE_ICON, 32, 32, LR_LOADFROMFILE ) ); if( hIcon ) SendMessage( hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon ); ``` However, after sending `WM_SETICON`, `GetLastError()` returns 6, "The handle is invalid.". `hWnd` is a valid window handle, and `hIcon` appears to be a valid icon handle. I've tried searching for reasons why `WM_SETICON` could cause that error, and at the very least, to figure out WHICH handle it thinks is invalid, but no luck yet. I've cleared the error code immediately before calling `SendMessage()`, so it has to be set somewhere in the processing of the message. I tried an alternate method, loading the icon from the exe itself, where the ID of the resource is `101` (it's the first and only resource included): ``` hIcon = (HICON)( LoadImage( GetModuleHandle( NULL ), MAKEINTRESOURCE( 101 ), IMAGE_ICON, 48, 48, 0 ) ); if( hIcon ) SendMessage( hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon ); ``` ... but the same thing happens; after calling `SendMessage()`, `GetLastError()` gives the same error status. I've tried different dimensions (such as 48x48, all of which are present in the icon file), but to no different effect. I know it's definitely finding and loading the images, because if I specify a size that doesn't exist or an invalid resource ID or the wrong filename (depending on how I am loading it), it fails out long before `SendMessage()`. Strangely, if I specify `ICON_SMALL` instead of `ICON_BIG`, the call succeeds with no error status, but from [the docs](http://msdn.microsoft.com/en-us/library/ms632643.aspx), I need to use `ICON_BIG` to set the icon used while alt-tabbing. Also, if I use `ICON_BIG` but load the 16x16 icon, I get no error status, but nothing changes. Any ideas about what could be causing `WM_SETICON` to fail? Anything terribly wrong with any of the code I've posted (aside from formatting/style/casting issues, as it's simplified to just the basics)?
I've revisited this to see if I can close out my question. I have been unable to get the app's icon to show up in the alt-tab list just through embedding it in the executable; it will show up in the taskbar, as the file's icon in Explorer, and elsewhere just fine. I figured I'd try something simpler for setting the icon manually, and went with `LoadIcon()` instead, as the code below shows: ``` HICON hIcon = LoadIcon( GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1) ); if( hIcon ) { SendMessage( GetHandle(), WM_SETICON, ICON_BIG, (LPARAM)hIcon ); DestroyIcon( hIcon ); } // ... Same for ICON_SMALL ``` This seems to have done the trick. I really don't know why, but so far it's the only change that had any effect. It's really not an issue I should spend any more time on, so I'll just go with this.
OK, this worked a treat for me : ``` HICON hIconSmall =(HICON)LoadImage(handleToYourApplicationInstance, MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON,16, 16, 0); HICON hIconLarge =(HICON)LoadImage(handleToYourApplicationInstance, MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON,256, 256, 0); // Big for task bar, small loaded otherwise. SendMessage(yourWindowHandle, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall) ; SendMessage(yourWindowHandle, WM_SETICON, ICON_BIG, (LPARAM)hIconLarge) ; ```
Problems with setting application icon
[ "", "c++", "visual-studio-2008", "icons", "" ]
I am trying to create nested repeaters dynamically using ITemplate. This repeater is like that I am passing `List<Control>` and it generates repeater. Issue is that when I databound outer repeater. Only the last nested repeater shows. Following is screen shot. [![screen shot](https://i.stack.imgur.com/PaT4Y.png)](https://i.stack.imgur.com/PaT4Y.png) **Markup** --- ``` <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Restricted_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table style="border:solid 1px black;"> <tr> <td> <asp:PlaceHolder ID="phControls" runat="server" /> </td> </tr> </table> </div> </form> </body> </html> ``` --- **Code Behind** --- ``` using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class Restricted_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { CreateNestedRepeater(); } private void CreateNestedRepeater() { Repeater childRpt = new Repeater(); List repeatingRuleControls = new List(); repeatingRuleControls.Add(new TextBox()); repeatingRuleControls.Add(new TextBox()); repeatingRuleControls.Add(new TextBox()); RepeatingRuleTemplate repeatingRuleTemplate = new RepeatingRuleTemplate(ListItemType.Item, repeatingRuleControls); childRpt.HeaderTemplate = new RepeatingRuleTemplate(ListItemType.Header, repeatingRuleControls); childRpt.ItemTemplate = repeatingRuleTemplate; childRpt.FooterTemplate = new RepeatingRuleTemplate(ListItemType.Footer, null); childRpt.DataSource = new DataRow[4]; Repeater parentRpt = new Repeater(); repeatingRuleControls = new List(); repeatingRuleControls.Add(new TextBox()); repeatingRuleControls.Add(new TextBox()); repeatingRuleControls.Add(new TextBox()); repeatingRuleControls.Add(childRpt); RepeatingRuleTemplate parentrepeatingRuleTemplate = new RepeatingRuleTemplate(ListItemType.Item, repeatingRuleControls); parentRpt.HeaderTemplate = new RepeatingRuleTemplate(ListItemType.Header, repeatingRuleControls); parentRpt.ItemTemplate = parentrepeatingRuleTemplate; parentRpt.FooterTemplate = new RepeatingRuleTemplate(ListItemType.Footer, null); parentRpt.DataSource = new DataRow[4]; parentRpt.DataBind(); phControls.Controls.Add(parentRpt); } public class RepeatingRuleTemplate : ITemplate { ListItemType templateType; List innerControls; public RepeatingRuleTemplate(ListItemType type, List controls) { templateType = type; innerControls = controls; } public void InstantiateIn(Control container) { PlaceHolder ph = new PlaceHolder(); switch (templateType) { case ListItemType.Header: ph.Controls.Add(new LiteralControl("")); ph.Controls.Add(new LiteralControl("")); foreach (Control control in innerControls) { Label label = new Label(); label.Text = control.ID; ph.Controls.Add(new LiteralControl("")); ph.Controls.Add(label); ph.Controls.Add(new LiteralControl("")); } ph.Controls.Add(new LiteralControl("")); break; case ListItemType.Item: ph.Controls.Add(new LiteralControl("")); foreach (Control control in innerControls) { if (control.GetType() != typeof(Repeater)) { ph.Controls.Add(new LiteralControl("")); TextBox textBox = new TextBox(); textBox.ID = control.ID; ph.Controls.Add(textBox); ph.Controls.Add(new LiteralControl("")); } else { ph.Controls.Add(new LiteralControl("")); ph.Controls.Add(control as Repeater); //(control as Repeater).DataSource = new DataRow[4]; // (control as Repeater).DataBind(); ph.Controls.Add(new LiteralControl("")); } } ph.Controls.Add(new LiteralControl("")); //ph.DataBinding += new EventHandler(Item_DataBinding); break; case ListItemType.Footer: ph.Controls.Add(new LiteralControl("")); break; } container.Controls.Add(ph); } public List Controls { get { return innerControls; } } } } ``` ---
Ok guys I figured it out .... Thanks to everyone though. I was doing a mistake. The template class was wrong.I fixed it and now it is working like Charm Follwoing is the class ``` public class RepeatingRuleTemplate : ITemplate { ListItemType templateType; List innerControls; ``` `public RepeatingRuleTemplate(ListItemType type, List<Control> controls) { templateType = type; innerControls = controls; } public void InstantiateIn(Control container) { PlaceHolder ph = new PlaceHolder(); switch (templateType) { case ListItemType.Header: ph.Controls.Add(new LiteralControl("<table border=\"0\">")); ph.Controls.Add(new LiteralControl("<tr>")); foreach (Control control in innerControls) { Label label = new Label(); label.Text = control.ID; ph.Controls.Add(new LiteralControl("<td>")); ph.Controls.Add(label); ph.Controls.Add(new LiteralControl("</td>")); } ph.Controls.Add(new LiteralControl("</tr>")); break; case ListItemType.Item: ph.Controls.Add(new LiteralControl("<tr>")); foreach (Control control in innerControls) { //ph.Controls.Add(new LiteralControl("<td>")); //ph.Controls.Add(control as TextBox); //ph.Controls.Add(new LiteralControl("</td>")); if (control.GetType() != typeof(Repeater)) { ph.Controls.Add(new LiteralControl("<td>")); TextBox textBox = new TextBox(); textBox.ID = control.ID; ph.Controls.Add(textBox); ph.Controls.Add(new LiteralControl("</td>")); } else { ph.Controls.Add(new LiteralControl("<td>")); Repeater rpt = new Repeater(); rpt.DataSource = (control as Repeater).DataSource; rpt.ItemTemplate = (control as Repeater).ItemTemplate; rpt.HeaderTemplate = (control as Repeater).HeaderTemplate; rpt.FooterTemplate = (control as Repeater).FooterTemplate; rpt.DataBind(); ph.Controls.Add(rpt); //(control as Repeater).DataSource = new DataRow[4]; // (control as Repeater).DataBind(); ph.Controls.Add(new LiteralControl("</td>")); } } ph.Controls.Add(new LiteralControl("</tr>")); //ph.DataBinding += new EventHandler(Item_DataBinding); break; case ListItemType.Footer: ph.Controls.Add(new LiteralControl("</table>")); break; } container.Controls.Add(ph); } public List<Control> Controls { get { return innerControls; } } }`
You need to write handler for parentRpt.ItemDataBound event and set DataSource property of childRpt and then call child.Rpt.DataBind() from there.
Dynamic Repeater in C#.net
[ "", "c#", ".net", "asp.net", "" ]
What's my best bet for parsing HTML if I can't use BeautifulSoup or lxml? I've got some code that uses SGMLlib but it's a bit low-level and it's now deprecated. I would prefer if it could stomache a bit of malformed HTML although I'm pretty sure most of the input will be pretty clean.
Python has a [native HTML parser](https://docs.python.org/3/library/html.parser.html), however the Tidy wrapper Nick suggested would probably be a solid choice as well. Tidy is a very common library, (written in C is it?)
Perhaps [µTidylib](http://utidylib.berlios.de/) will meet your needs?
Parsing HTML in Python
[ "", "python", "html-parsing", "" ]
I have a column of data containing a string with the following format: ``` blablablabla(XYZ) ``` and I would like to discard everything outside the () - and the parenthesis themselves - and to set update that field with the value inside the (). This implies that, in this particular case, the "blablabla" would be discarded and that entry would only contain XYZ. I know that I have to use SQL UPDATE, but i'm not sure on how to build the where condition properly. Many thanks, Hal EDIT: i forgot to say that it was in SQL Server 2008. Thank you all for your answers, they all worked (i tested). Too bad i can't mark all as correct. I'm really amazed, the answers were all so quick.
This assumes that there is *exactly one* pair of *correctly nested* parentheses (and is T-SQL syntax): ``` DECLARE @bla VARCHAR(50) SET @bla = 'blablablabla(XYZ)asdsdsad' SELECT SUBSTRING( @bla, CHARINDEX('(', @bla) + 1, CHARINDEX(')', @bla) - CHARINDEX('(', @bla) - 1 ) ``` Yields: ``` 'XYZ' ``` --- EDIT: This checks for various ill-formatted strings and could be used in a WHERE clause (e.g. `WHERE ... <> 'no match'`): ``` SELECT CASE WHEN /* check for '(' and ')' */ CHARINDEX('(', @bla) > 0 AND CHARINDEX(')', @bla) > CHARINDEX('(', @bla) /* check for 'bla(bla(XYZ)bla' */ AND CHARINDEX('(', @bla, CHARINDEX('(', @bla) + 1) = 0 /* check for 'bla(XYZ)bla)bla' */ AND CHARINDEX(')', @bla, CHARINDEX(')', @bla) + 1) = 0 THEN SUBSTRING(@bla, CHARINDEX('(', @bla) + 1, CHARINDEX(')', @bla) - CHARINDEX('(', @bla) - 1 ) ELSE 'no match' END ```
In `MySQL`: ``` UPDATE mytable SET column = SUBSTRING(column, INSTR(column, '(') + 1, INSTR(column, ')') - INSTR(column, '(') - 1) WHERE column RLIKE ('\\(.*\\)') ```
SQL Update - Everything inside ()
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "" ]
I was writing a Stored procedure today, and I ran into a problem where if one of the values is null (whether it be from a `SELECT` statement or whether it be a passed in parameter) my expression would evaluate to false where it ought to evaluate to true. ``` SET ANSI_NULLS ON; DECLARE @1 INT; DECLARE @2 INT; DECLARE @3 INT; DECLARE @4 INT; SET @1 = 1; SET @2 = NULL; SET @3 = 3; SET @4 = 3; IF ((@1 <> @2) OR (@3 <> @4)) BEGIN SELECT 1; END ELSE BEGIN SELECT 2; END SELECT @1, @2, @3, @4 ``` Returns: ``` 2 1, NULL, 3, 3 ``` I expected it to return: ``` 1 1, NULL, 3, 3 ``` I know I'm missing something simple, anybody have any idea what it is? ### Related Question > [SQL: Why are `NULL` Values filtered Out within this `WHERE` clause?](https://stackoverflow.com/questions/683627/sql-why-are-null-values-filtered-out-within-this-where-clause/)
One way of dealing with this is you can wrap your `NULL` values in a known unexpected value, i.e. `-1`: ``` IF ((ISNULL(@1, -1) <> ISNULL(@2, -1)) OR (ISNULL(@3, -1) <> ISNULL(@4, -1))) BEGIN SELECT 1; END ELSE BEGIN SELECT 2; END ``` Obviously if `-1` was a possibility then use a different number. If there is no non-possible value, then you will have to use `CASE` statements. A concise way of assigning `NULL` values to a 'safe' value follows: > `SET @1 = ISNULL(@1, -1)` This allows the contional test code to remain 'clutter-free'.
Any comparison that involves a NULL will evaluate to NULL instead of True or False. Hence the ELSE block of your code gets executed. Because although Null is not the same as False, it definitely isn't the same as True.
Dealing with Nulls in Comparison Tests in SQL Server 2005
[ "", "sql", "sql-server", "t-sql", "" ]
I have an XSLT with a C# script in it: ``` <msxsl:script language="C#" implements-prefix="user"> <msxsl:using namespace="System.Xml"/> <msxsl:using namespace="System.Xml.XPath"/> <![CDATA[ public string GetMenuPath(XPathNodeIterator node) { XPathNavigator dataSourceNode = node.Current; return dataSourceNode.Name; } ]]> </msxsl:script> ``` And somewhere in the XSLT this function is called: ``` <xsl:value-of select="user:GetMenuPath(current())"/> ``` But as I try to run the XSLT transformation on the XML input (the input does not matter), it stop immediately with the error "msxsl:script cannot be empty". I have absolutely no idea why... I use nxslt with .NET Framework. Thank you for help !
Thank you for your answers, I found out the origin of the problem now. It was because I was using the "style" tag instead of "nxslt" for calling the XSLT transformation. "style" works as long as there is no extension script. ``` <nxslt style="transformation.xsl" in="input.xml" out="output.xls" verbose="true"> ```
Does it give you the line that the transformation stops on? Is it where it is calling from or in the script tag?
C# script in XSLT: "msxsl:script cannot be empty" error
[ "", "c#", "xslt", "" ]
If I were to remove my CSS stylesheet and set all the properties via a JavaScript file, would that be possible? That is, would there be anything I couldn't access via the JS DOM API?
Everything in CSS can be accessed through JS, but bear in mind that users with JS disabled won't get any style at all! * CSS is for styling * JavaScript is for changing functionality Don't merge them unless strictly necessary.
The only ones I can think of are possibly IE CSS expressions (such as ones commonly used to fix PNGs in IE6). However I don't think this is generally a good idea, as you want to keep your content (HTML), layout (CSS) and logic (javascript) seperate for maintainability reasons. Not to mention if people visit your site with javascript disabled.
Are there any CSS properties that the JavaScript DOM can't access?
[ "", "javascript", "css", "dom", "" ]
I am trying to catpure the enter key from a textarea using javascript. The problem is that although I am able to find out that the "enter" key was pressed, I am not unable to avoid it from coming in the textarea. I dont want the enter key i.e. "\n" to be displayed in the text area. Any suggestions on how to achieve that? Thank you.
Try setting this function as the onKeyDown event for the text area: ex: `onkeydown="javascript:return fnIgnoreEnter(event);"` ``` function fnIgnoreEnter(thisEvent) { if (thisEvent.keyCode == 13) { // enter key return false; // do nothing } } ```
More recent and much cleaner: use `event.key` instead of `event.keyCode`. **No more arbitrary number codes!** ``` function onEvent(event) { if (event.key === "Enter") { return false; } }; ``` [Mozilla Docs](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) [Supported Browsers](http://caniuse.com/#feat=keyboardevent-key)
Javascript capture key
[ "", "javascript", "" ]
Ok, so I've read about this a number of times, but I'm yet to hear a clear, easy to understand (and memorable) way to learn the difference between: ``` if (x | y) ``` and ``` if (x || y) ``` ..within the context of C#. Can anyone please help me learn this basic truth, and how C# specifically, treats them differently (because they seem to do the same thing). If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise?
`||` is the *logical-or* operator. See **[here](http://msdn.microsoft.com/en-us/library/aa691310(VS.71).aspx)**. It evaluates to `true` if at least one of the operands is true. You can only use it with boolean operands; it is an error to use it with integer operands. ``` // Example var one = true || bar(); // result is true; bar() is never called var two = true | bar(); // result is true; bar() is always called ``` `|` is the *or* operator. See **[here](http://msdn.microsoft.com/en-us/library/kxszd0kx(VS.71).aspx)**. If applied to boolean types, it evaluates to `true` if at least one of the operands is true. If applied to integer types, it evaluates to another number. This number has each of its bits set to 1 if at least one of the operands has a corresponding bit set. ``` // Example var a = 0x10; var b = 0x01; var c = a | b; // 0x11 == 17 var d = a || b; // Compile error; can't apply || to integers var e = 0x11 == c; // True ``` For boolean operands, `a || b` is *identical* to `a | b`, with the single exception that `b` is not evaluated if `a` is true. For this reason, `||` is said to be "short-circuiting". > If the difference a given piece of code has between them is irrelevant, which should I default to as a best-practise? As noted, the difference isn't irrelevant, so this question is partially moot. As for a "best practice", there isn't one: you simply use whichever operator is the correct one to use. In general, people favor `||` over `|` for boolean operands since you can be sure it won't produce unnecessary side effects.
When used with boolean operands the `|` operator is a logical operator just as `||`, but the difference is that the `||` operator does short circuit evaluation and the `|` operator does not. This means that the second operand is always evaluated using the `|` operator, but using the `||` operator the second operand is only evaluated if the first operand evaluates to false. The result of the expression is always the same for both operatrors, but if the evaluation of the second operand causes something else to change, that is only guaranteed to happen if you use the `|` operator. Example: ``` int a = 0; int b = 0; bool x = (a == 0 || ++b != 0); // here b is still 0, as the "++b != 0" operand was not evaluated bool y = (a == 0 | ++b != 0); // here b is 1, as the "++b != 0" operand was evaluated. ``` The short-circuit evaluation of the `||` operator can be used to write shorter code, as the second operand only is evaluated if the first operand is true. Instead of writing like this: ``` if (str == null) { Console.WriteLine("String has to be at least three characters."); } else { if (str.Length < 3) { Console.WriteLine("String has to be at least three characters."); } else{ Console.WriteLine(str); } } ``` You can write like this: ``` if (str == null || str.Length < 3) { Console.WriteLine("String has to be at least three characters."); } else{ Console.WriteLine(str); } ``` The second operand is only evaluated if the first is false, so you know that you can safely use the string reference in the second operand as it can not be null if the second operand is evaluated. In most cases you would want to use the `||` operator rather than the `|` operator. If the first operand is false, there is no need to evaluate the second operand to get the result. Also, a lot of people (evidently) doesn't know that you can use the `|` operator with boolean operands, so they would get confused when seeing it used that way in the code.
A clear, layman's explanation of the difference between | and || in c#?
[ "", "c#", "bitwise-operators", "logical-operators", "" ]
I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away. I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel. This is just for personal educational purposes. The program works! I really want to get better at python and therefore I'd like to ask the following questions: 1. My style looks messy compared to PHP (what I'm used to). Do you have any suggestions around style improvements. 2. Am I using the correct libraries? Am I using them correctly? 3. Am I using the correct datatypes? Am I using them correctly? I have a good programming background, but it took me quite a while to develope a decent style for PHP (PEAR-coding standards, knowing what tools to use and when). The source (one file, 92 lines of code) <http://code.google.com/p/floep/source/browse/trunk/floep>
Usually is preferred that what follows after the end of sentence `:` is in a separate line (also don't add a space before it) ``` if options.verbose: print "" ``` instead of ``` if options.verbose : print "" ``` You don't need to check the len of a list if you are going to iterate over it ``` if len(threadlist) > 0 : for server in threadlist : ... ``` is redundant, a more 'readable' is (python is smart enough to not iterate over an empty list): ``` for server in threadlist: ... ``` Also a more 'pythonistic' is to use list's comprehensions (but certainly is a debatable opinion) ``` server = [] for i in grouplist : servers+=getServers(i) ``` can be shortened to ``` server = [getServers(i) for i in grouplist] ```
Before unloading any criticism, first let me say congratulations on getting your first Python program working. Moving from one language to another can be a chore, constantly fumbling around with syntax issues and hunting through unfamiliar libraries. The most quoted style guideline is [PEP-8](http://www.python.org/dev/peps/pep-0008/), but that's only a guide, and at least some part of it is ignored...no, I mean deemed not applicable to some specific situation with all due respect to the guideline authors and contributors :-). I can't compare it to PHP, but compared to other Python applications it is pretty clear that you are following style conventions from other languages. I didn't always agree with many things that other developers said you **must** do, but over time I recognized why using conventions helps communicate what the application is doing and will help other developers help you. --- Raise exceptions, not strings. ``` raise 'Server or group ' + sectionname + ' not found in ' + configfile ``` becomes ``` raise RuntimeError('Server or group ' + sectionname + ' not found in ' + configfile) ``` --- No space before the ':' at the end of an 'if' or 'for', and don't put multiple statements on the same line, and be consistent about putting spaces around operators. Use variable names for objects and stick with `i` and `j` for loop index variables (like our masterful FORTRAN forefathers): ``` for i in grouplist : servers+=getServers(i) ``` becomes: ``` for section in grouplist: servers += getServers(section) ``` --- Containers can be tested for contents without getting their length: ``` while len(threadlist) > 0 : ``` becomes ``` while threadlist: ``` and ``` if command.strip() == "" : ``` becomes ``` if command.strip(): ``` --- Splitting a tuple is usually not put in parenthesis on the left hand side of a statement, and the command logic is a bit convoluted. If there are no args then the " ".join(...) is going to be an empty string: ``` (options,args) = parser.parse_args() if options.verbose : print "floep 0.1" command = " ".join(args) if command.strip() == "" : parser.error('no command given') ``` becomes ``` options, args = parser.parse_args() if options.verbose: print "floep 0.1" if not args: parser.error('no command given') command = " ".join(args) ``` --- A python for loop has an unusual 'else' clause which is executed if the loop goes through all of the elements without a 'break': ``` for server in threadlist : foundOne = False if not server.isAlive() : ...snip... foundOne = True if not foundOne : time.sleep(0.010) ``` becomes ``` for server in threadlist: if not server.isAlive(): ...snip... break else: time.sleep(0.010) ``` --- Getting a list of lines and then joining them back together is a bit long winded: ``` result = proc.readlines() strresult = '' for line in result : strresult+=line self.result = strresult ``` becomes ``` self.result = proc.read() ``` --- Your library use is good, check out the subprocess module, it's a little more up-to-date. Your datatypes are fine. And you'll get lots of other anwsers :-)
My first python program: can you tell me what I'm doing wrong?
[ "", "python", "" ]
I'm looking for a (free) library which allows me to draw a [CFG](http://en.wikipedia.org/wiki/Control_flow_graph) (control flow graph). Something like [yFiles](http://yworks.com/), but free or preferably open source? Ideally this library would allow the user to navigate the graph (and modify it), i.e. the graph isn't just a static a priori rendered bitmap. Ideas? **Update:** [Glee](http://research.microsoft.com/en-us/downloads/f1303e46-965f-401a-87c3-34e1331d32c5/default.aspx) in combination with the mentioned QuickGraph library seems to work pretty nice. thx **Update2:** [Graph#](http://graphsharp.codeplex.com/) seems to be the most powerful library currently. There is also a nice [tutorial](http://sachabarber.net/?p=815) on how to use it.
You might want to check out [QuickGraph](http://www.codeplex.com/quickgraph). [NodeXL](http://www.codeplex.com/NodeXL) might also be of interest (visualization library). It's WPF, but you can use a container to host it if you need WinForms.
Try out this (Efficient Sugiyama algorithm is your friend): [Graph#](http://codeplex.com/graphsharp)
C# graph drawing library?
[ "", "c#", "graphics", "graph-theory", "" ]
Can anyone explain why the following doesn't compile? ``` byte b = 255 << 1 ``` The error: > Constant value '510' cannot be converted to a 'byte' I'm expecting the following in binary: ``` 1111 1110 ``` The type conversion has stumped me.
Numeric literals in C# are `int`, not `byte` (and the bit shift will be evaluated by the compiler, hence only the 510 remains). You are therefore trying to assign a value to a `byte` which does not fit. You can mask with 255: ``` byte b = (255 << 1) & 0xFF ``` to reduce the result to 8 bits again. Unlike Java, C# does not allow overflows to go by undetected. Basically you'd have two sensible options when trying to assign 510 to a byte: Either clamp at the maximum value, then you'd get 255, or throw away the bits that do not fit, in which case you'd get 254. You can also use `unchecked`, as [lassevk mentioned](https://stackoverflow.com/questions/737781/left-bit-shifting-255-as-a-byte/737810#737810): ``` byte b = unchecked((byte)(255 << 1)); ```
You are shifting 255 by 1 bit, then trying to assign it to a byte. `255 << 1 is 510`, and 510 won't fit in to a byte.
Left bit shifting 255 (as a byte)
[ "", "c#", "bit-manipulation", "bit-shift", "" ]
I am using C# 3.0 and NUnit. I'm wondering if there is a standard way to perform unit tests on code that executes after some amount of time. For example, I have a simple static class that I can register methods with, and have them be called n milliseconds later. I need to assure that code in the delegate methods is being called. For example, the following test will always pass, because there are no assertions made until after the method has exited. ``` [Test] public void SampleTest() { IntervalManager.SetTimeout(delegate{ Assert.Equals(now.Millisecond + 100, DateTime.Now.Millisecond); }, 100); } ``` Is it even possible to unit test code that doesn't execute immediately? Cheers, Paul
How about this? It causes the test to block for some expected maximum time for the callback to fire and complete before bailing, reporting an error. ``` public void Foo() { AutoResetEvent evt = new AutoResetEvent(false); Timer t = new Timer(state => { // Do work evt.Set(); }, null, 100, Timeout.Infinite); if (evt.WaitOne(500)) { // method called and completed } else { // timed out waiting } } ```
So what exactly are you testing? Are you testing that Timers work? Or that your code properly sets up a Timer so that on expiration the timer executes a callback? Without knowing what the code looks like, I'm assuming that what you really want to test is the latter. My answer would be that (1) this is probably going to be hard with static methods and (2) you'll probably need to use dependency injection and inject the mock timers, etc. that don't actually run the resulting method but record via expectations that the proper calls were made by your code.
Unit Testing code that doesn't execute immediately
[ "", "c#", "unit-testing", "c#-3.0", "nunit", "xna", "" ]
What follows is a typical dispose pattern example: ``` public bool IsDisposed { get; private set; } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!IsDisposed) { if (disposing) { //perform cleanup here } IsDisposed = true; } } ~MyObject() { Dispose(false); } ``` I understand what dispose does, but what I don't understand is why you would want to call dispose(false) in the destructor? If you look at the definition it would do absolutely nothing, so why would anyone write code like this? Wouldn't it make sense to just *not* call dispose from the destructor at all?
The finalizer is used as a fall-back if the object is not disposed properly for some reason. Normally the `Dispose()` method would be called which removes the finalizer hookup and turns the object into a regular managed object that the garbage collector easily can remove. Here is an example from MSDN of a class that has managed and unmanaged resources to clean up. Notice that the managed resources are only cleaned up if `disposing` is true, but unmanaged resources is always cleaned up. ``` public class MyResource: IDisposable { // Pointer to an external unmanaged resource. private IntPtr handle; // Other managed resource this class uses. private Component component = new Component(); // Track whether Dispose has been called. private bool disposed = false; // The class constructor. public MyResource(IntPtr handle) { this.handle = handle; } // Implement IDisposable. // Do not make this method virtual. // A derived class should not be able to override this method. public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } // Dispose(bool disposing) executes in two distinct scenarios. // If disposing equals true, the method has been called directly // or indirectly by a user's code. Managed and unmanaged resources // can be disposed. // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if(!this.disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if(disposing) { // Dispose managed resources. component.Dispose(); } // Call the appropriate methods to clean up // unmanaged resources here. // If disposing is false, // only the following code is executed. CloseHandle(handle); handle = IntPtr.Zero; // Note disposing has been done. disposed = true; } } // Use interop to call the method necessary // to clean up the unmanaged resource. [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(IntPtr handle); // Use C# destructor syntax for finalization code. // This destructor will run only if the Dispose method // does not get called. // It gives your base class the opportunity to finalize. // Do not provide destructors in types derived from this class. ~MyResource() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } } ```
> "The idea here is that > Dispose(Boolean) knows whether it is > being called to do explicit cleanup > (the Boolean is true) versus being > called due to a garbage collection > (the Boolean is false). This > distinction is useful because, when > being disposed explicitly, the > Dispose(Boolean) method can safely > execute code using reference type > fields that refer to other objects > knowing for sure that these other > objects have not been finalized or > disposed of yet. When the Boolean is > false, the Dispose(Boolean) method > should not execute code that refer to > reference type fields because those > objects may have already been > finalized." There's much (much!) more info in the [“Dispose, Finalization, and Resource Management Design Guidelines”](http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/). Edit: link.
Why call dispose(false) in the destructor?
[ "", "c#", "dispose", "" ]
I have some data that I have stored in a list and if I print out the list I see the following: ``` . . . 007 A000000 Y 007 B000000 5 007 C010100 1 007 C020100 ACORN FUND 007 C030100 N 007 C010200 2 007 C020200 ACORN INTERNATIONAL 007 C030200 N 007 C010300 3 007 C020300 ACORN USA 007 C030300 N 007 C010400 4 . . . ``` The dots before and after the sequence are to represent that there is other data that is similarily structured but might or might not not be part of this seventh item (007). if the first value in the seventh item is '007 A000000 Y' then I want to create a dictionary listing of some of the data items. I can do this and have done so by just running through all of the items in my list and comparing their values to some test values for the variables. For instance a line of code like: ``` if dataLine.find('007 B')==0: numberOfSeries=int(dataLine.split()[2]) ``` What I want to do though is ``` if dataLine.find(''007 A000000 Y')==0: READ THE NEXT LINE RIGHT HERE ``` Right now I am having to iterate through the entire list for each cycle I want to shorten the processing because I have about 60K files that have between 500 to 5,000 lines in each. I have thought about creating another reference to the list and counting the datalines until dataLine.find(''007 A000000 Y')==0. But that does not seem like it is the most elegant solution.
Okay-while I was Googling to make sure I had covered my bases I came across a solution: I find that I forget to think in Lists and Dictionaries even though I use them. Python has some powerful tools to work with these types to speed your ability to manipulate them. I need a slice so the slice references are easily obtained by ``` beginPosit = tempans.index('007 A000000 Y') endPosit = min([i for i, item in enumerate(tempans) if '008 ' in item]) ``` where tempans is the datalist now I can write ``` for line in tempans[beginPosit:endPosit]: process each line ``` I think I answered my own question. I learned alot from the other answers and appreciate them but I think this is what I needed Okay I am going to further edit my answer. I have learned a lot here but some of this stuff is over my head still and I want to get some code written while I am learning more about this fantastic tool. ``` from itertools import takewhile beginPosit = tempans.index('007 A000000 Y') new=takewhile(lambda x: '007 ' in x, tempans[beginPosit:]) ``` This is based on an earlier answer to a similar question and [Steven Huwig's](https://stackoverflow.com/questions/337223/python-item-for-item-until-stopterm-in-item#337285) answer
You can use `itertools.groupby()` to segment your sequence into multiple sub-sequences. ``` import itertools for key, subseq in itertools.groupby(tempans, lambda s: s.partition(' ')[0]): if key == '007': for dataLine in subseq: if dataLine.startswith('007 B'): numberOfSeries = int(dataLine.split()[2]) ``` --- `itertools.dropwhile()` would also work if you really just want to seek up to that line, ``` list(itertools.dropwhile(lambda s: s != '007 A000000 Y', tempans)) ['007 A000000 Y', '007 B000000 5', '007 C010100 1', '007 C020100 ACORN FUND', '007 C030100 N', '007 C010200 2', '007 C020200 ACORN INTERNATIONAL', '007 C030200 N', '007 C010300 3', '007 C020300 ACORN USA', '007 C030300 N', '007 C010400 4', '.', '.', '.', ''] ```
Program Control-Flow in Python
[ "", "python", "list", "enumerate", "" ]
im looking to write a daemon that: * reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file * updates a record in the database saying something like "this job is processing" * reads the aforementioned archive's contents and inserts a row into a database w/ information culled from file meta data for each file found * duplicates each file to s3 * deletes the zip file * marks the job as "complete" * read next message in queue, repeat this should be running as a service, and initiated by a message queued when someone uploads a file via the web frontend. the uploader doesn't need to immediately see the results, but the upload be processed in the background fairly expediently. im fluent with python, so the very first thing that comes to mind is writing a simple server with twisted to handle each request and carry out the process mentioned above. but, ive never written anything like this that would run in a multi-user context. its not going to service hundreds of uploads per minute or hour, but it'd be nice if it could handle several at a time, reasonable. i also am not terribly familiar with writing multi-threaded applications and dealing with issues like blocking. how have people solved this in the past? what are some other approaches i could take? thanks in advance for any help and discussion!
i opted to use a combination of celery (<http://ask.github.com/celery/introduction.html>), rabbitmq, and a simple django view to handle uploads. the workflow looks like this: 1. django view accepts, stores upload 2. a celery `Task` is dispatched to process the upload. all work is done inside the `Task`.
I've used [Beanstalkd](http://xph.us/software/beanstalkd/) as a queueing daemon to very good effect (some near-time processing and image resizing - over 2 million so far in the last few weeks). Throw a message into the queue with the zip filename (maybe from a specific directory) [I serialise a command and parameters in JSON], and when you reserve the message in your worker-client, no one else can get it, unless you allow it to time out (when it goes back to the queue to be picked up). The rest is the unzipping and uploading to S3, for which there are other libraries. If you want to handle several zip files at once, run as many worker processes as you want.
suggestions for a daemon that accepts zip files for processing
[ "", "python", "django", "zip", "daemon", "" ]
I want to autogenerate some java classes from interfaces. My first thought was to write a code generator, and integrate it as a maven plugin. I was thinking of creating a maven plugin with a codegen goal that is called during the build process. So if I choose this route, how do I provide the plugin with the interfaces to be processed? And where should the generated files go? Are there any existing plugins that can be configured to generate default class implementations?
Sources should go in {project.build.directory}/generated-sources/[plugin-id]/ Most plugins take configuration passed through the plugin configuration section in the pom. You can use default values as well, or an annotation and classpath scanning. A plugin like the [maven-jspc-plugin](http://mojo.codehaus.org/jspc-maven-plugin/usage.html) generates code, which you could take a look at. The "Better Builds With Maven" e-book also contains a reasonably comprehensive chapter on writing plugins.
Maybe have a look at the XDoclet Maven plugin- XDoclet is often used for generating sources from doclet-style markup in classes (e.g. autogenerating MBean interfaces from implementations) and that sounds similar to what you're doing.
Code generation in Maven
[ "", "java", "maven-2", "plugins", "code-generation", "" ]
I need to wrap an IE ajax request to notify me when it happens. ie i need to know when open is called on this: var xhr = new ActiveXObject("Microsoft.XMLHTTP"); The only way to do that(i think) is to implement the ActiveXObject constructor to proxy open calls to the real constructor/object. Can you help me do that? also: i dont need to create the actual xhr object, so please dont tell me to use X framework because its easy. all i need to know is when **open** is called (not by my code) on an MS xhr object. Thank you very much!
Since the OP has posted a similar question, and I posted an answer which also happens to fit *this* question, he asked me to link to my answer, instead of repeating it here. * Q: [Extending an ActiveXObject in javascript](https://stackoverflow.com/questions/797960/extending-an-activexobject-in-javascript) * A: [A drop-in transparent wrapper for `MSXML2.XMLHTTP`](https://stackoverflow.com/questions/797960/extending-an-activexobject-in-javascript/798611#798611)
Perhaps you can try something like this: ``` XMLHttpRequest.prototype.real_open = XMLHttpRequest.prototype.open; var your_open_method = function(sMethod, sUrl, bAsync, sUser, sPassword) { alert('an XHR request has been made!'); this.real_open(sMethod, sUrl, bAsync, sUser, sPassword); } XMLHttpRequest.prototype.open = your_open_method; ``` Of course, instead of the alert you can have your own tracking code. I tried it out and it works on 'plain javascript' requests and also requests made with jquery. I think it should work regardless of the framework that was used to make the request. **EDIT April 21** I don't really know how an ActiveXObject can be extended. My guess is that something like this should work: ``` XHR = new ActiveXObject("Microsoft.XMLHTTP"); var XHR.prototype.old_open = XHR.prototype.open; var new_open = function(sMethod, sUrl, bAsync, sUser, sPassword) { alert('an IE XHR request has been made!'); this.old_open(sMethod, sUrl, bAsync, sUser, sPassword); } XHR.prototype.open = new_open; ``` Unfortunately (or maybe not) I don't have IE, so I can't test it. But give it a spin and let me know if it did the trick.
How to modify ActiveXObject JS constructor?
[ "", "javascript", "ajax", "binding", "proxy", "" ]
I am wondering if one could use the C# Express version to do Compact Framework development. I've done some Google searches but I can't find a defiant answer. I have installed C# Express but there isn't a project template to select for "smart device" development. I will continue my search but I was hoping that the stackoverflow community may be able to assist in finding this information.
I don't think it is possible, at least not directly, given that C# Express edition is crippled to only support basic projects and does not allow addins.
To do CF development, you need the runtimes and compiler pieces for it. Those pieces come with the following: * Visual Studio 2003 Professional or better * Visual Studio 2005 Standard or better * Visual Studio 2008 Professional or better Microsoft hasn't announced what level of Studio you'll need in version 10 to have Smart Device capabilities (we've been pushing for a low cost or free version). That said, you can still get into Studio at a fairly low cost with one of the following programs: * [Empower ISV](https://partner.microsoft.com/40011351) * [DreamSpark](http://www.dreamspark.com) * [BizSpark](http://www.microsoft.com/bizspark)
Compact Framework development using C# Express Version
[ "", "c#", "compact-framework", "visual-studio-express", "" ]
I am making an AJAX call (with jQuery) to retrieve a `PartialView`. Along with the HTML I'd like to send back a JSON representation of the object the View is displaying. The crappy way that I've been using is embedding properties as hidden inputs in the HTML, which quickly becomes unwieldy and tightly couples far too much stuff. I could just send the JavaScript in a `<script>` tag after the HTML, but I'm really anal about keeping those things separate. That would look like this: ``` <%@ Control Language="C#" AutoEventWireup="true" Inherits="System.Web.Mvc.ViewUserControl<Person>" %> <div class="person"> First Name: <%= Html.TextBox("FirstName", Model.FirstName) %> Last Name: <%= Html.TextBox("LastName", Model.LastName) %> </div> <script type="text/javascript"> // JsonSerialized object goes here </script> ``` Another option I considered is to make a second AJAX call to an action that returns `JsonResult`, but that also feels like bad design.
I think I found a pretty good way to do this, just wrap the `JSON` up in an `HtmlHelper` extension. Here's the class: ``` using System.Web.Script.Serialization; public static class JsonExtensions { public static string Json(this HtmlHelper html, string variableName) { return Json(html, variableName, html.ViewData.Model); } public static string Json(this HtmlHelper html, string variableName, object model) { TagBuilder tag = new TagBuilder("script"); tag.Attributes.Add("type", "text/javascript"); JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); tag.InnerHtml = "var " + variableName + " = " + jsonSerializer.Serialize(model) + ";"; return tag.ToString(); } } ``` And you call it via: ``` <%= Html.Json("foo") %> <%= Html.Json("bar", Model.Something) %> ``` The one catch that I can think of is that it isn't a completely *perfect* separation; you are still technically putting JavaScript in the HTML. *But*, it doesn't make an extra call to the server, and the markup in the IDE is still very clean.
The same solution as Andrew, but maybe a bit more MVC'ish... Create a new class which inherits from ViewPage. Override its Render method to render the page itself, and then stuff that into the output Andrew suggested. So that all the hacking occurs in the Render method, where it should happen. Now each view that you create you change the line: ``` <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<MyModel>" %> ``` with ``` <%@ Page Title="" Language="C#" Inherits="CustomViewPage<MyModel>" %> ``` I didn't check it myself, but guess it should work. If you want I can try and build it.
Returning a PartialView with both HTML and JavaScript
[ "", "javascript", "asp.net-mvc", "ajax", "" ]
I've got a situation where i have one system running a master application that communicates with slave applets on other systems, problem is, i can't guarentee that the slave applets will be running, nor that an operator can physically utilize the system to start the applet (and I'm also assuming they don't know how to use Remote desktop, these are minimum wage test operators) **Is there an easy way to remotely launch an executeable on another system?** security is not a concern here as this is a closed network.
If you're on the same network and have access credentials (username+password) to the remote computer, then Mark Russinovich's [PsExec](http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx) is just the tool you need.
WMI is your friend. See the following article which covers starting processes locally and remotely using WMI: [How To: (Almost) Everything In WMI via C# Part 2: Processes (CodeProject)](http://www.codeproject.com/KB/cs/EverythingInWmi02.aspx) Kev
How can I start an application on a different system remotely?
[ "", "c#", ".net", "windows", "networking", "" ]
How to keep the source code well documented/commented? Is there a tool to generate a skeleton for comments on the Unix platform for C++? In general, how many lines of comments is recommended for a file with around 100 lines of code?
Generally, it's best to let the code itself explain **what** it does, whereas the comments are there to describe **why** it's like that. There is no number to stick to. If your 100 lines speak for themselves, don't comment at all or just provide a summary at the beginning. If there is some knowledge involved that's beyond what the code does, explain it in a comment. If you're code is too complicated to explain itself, then that may be a reason to refactor. This way, when you change the implementation you don't need to change the comments as well, as your comments do not duplicate the code. Since the reasons for the design seldom change it's safe to document them in comments for clarity.
Personally I think skeleton comments are a horrible, horrible idea. I understand that sometimes it's nice to save couple of keystrokes and perhaps get argument signatures in comment... but resulting n+1 empty useless comments (when editor has added boilerplates and coder has left them as is) are just more irritating. I do think comments are needed, at any rate -- if only code one writes is too trivial to ned explanation, chances are code in question is useless (i.e. could have been automated and needn't be hand-written). I tend to comment my code reasonably well because I have learnt that usually I need it myself first. That others can use them is just an added bonus.
Comments in source code
[ "", "c++", "documentation", "comments", "" ]
I want to define my own datatype that can hold a single one of six possible values in order to learn more about memory management in c++. In numbers, I want to be able to hold 0 through 5. Binary, It would suffice with three bits (101=5), although some (6 and 7) wont be used. The datatype should also consume as little memory as possible. Im not sure on how to accomplish this. First, I tried an enum with defined values for all the fields. As far as I know, the values are in hex there, so one "hexbit" should allow me to store 0 through 15. But comparing it to a char (with sizeof) it stated that its 4 times the size of a char, and a char holds 0 through 255 if Im not misstaken. ``` #include <iostream> enum Foo { a = 0x0, b = 0x1, c = 0x2, d = 0x3, e = 0x4, f = 0x5, }; int main() { Foo myfoo = a; char mychar = 'a'; std::cout << sizeof(myfoo); // prints 4 std::cout << sizeof(mychar); // prints 1 return 1; } ``` Ive clearly misunderstood something, but fail to see what, so I turn to SO. :) Also, when writing this post I realised that I clearly lack some parts of the vocabulary. Ive made this post a community wiki, please edit it so I can learn the correct words for everything.
A `char` is the smallest possible type. If you happen to know that you need several such 3 bit values in a single place you get use a structure with bitfield syntax: ``` struct foo { unsigned int val1:3; unsigned int val2:3; }; ``` and hence get 2 of them within one byte. In theory you could pack 10 such fields into a 32-bit "int" value.
C++ 0x will contain [Strongly typed enumerations](http://en.wikipedia.org/wiki/C++0x#Strongly_typed_enumerations) where you can specify the underlying datatype (in your example char), but current C++ does not support this. The standard is not clear about the use of a char here (the examples are with int, short and long), but they mention *the underlying integral type* and that would include char as well. As of today Neil Butterworth's answer to create a class for your problem seems the most elegant, as you can even extend it to contain a nested enumeration if you want symbolical names for the values.
Define smallest possible datatype in c++ that can hold six values
[ "", "c++", "memory", "binary", "memory-management", "hex", "" ]
I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was. So is it possible given a users POP email server details to access their sent mail? If so any examples in Python or fetchmail?
POP3 only handles receiving email; sent mail is sent via SMTP in these situations, and may be sent via a different ISP to the receiver (say, when you host your own email server, but use your current ISP to send). As such, this isn't directly possible. IMAP could do it, as this offers server side email folders as well as having the server handle the interface to both send and receive SMTP traffic
Pop doesn't support sent email. Pop is an inbox only, Sent mail will be stored in IMAP, Exchange or other proprietary system.
Is it possible to Access a Users Sent Email over POP?
[ "", "python", "email", "pop3", "fetchmail", "" ]
I'm trying to match C style comments form a file, but only if the comment don't start with a certain labels introduced by `@` For example from ``` /* some comment to match */ /* another comment. this should match also */ /*@special shouldn't match*/ ``` Is this possible using regular expressions only? I'm trying this using JavaScript implementation of regular expressions.
``` /\*\s*(?!@)(?:(?!\*/).)*\*/ ``` Breaks down as: ``` /\* // "/*" \s* // optional space (?!@) // not followed by "@" (?: // don't capture... (?!\*/). // ...anything that is not "*/" )* // but match it as often as possible \*/ // "*/" ``` Use in "global" and "dotall" mode (e.g. the dot should match new lines as well) *The usual word of warning:* As with all parsing jobs that are executed with regular expressions, this will fail on nested patterns and broken input. [emk points out a nice example](https://stackoverflow.com/questions/681379/regular-expression-match-only-if-subpattern-doesnt-match/681402#681402) of (otherwise valid) input that will cause this expression to break. This can't be helped, regex is not for parsing. If you are positive that things like this can never occur in your input, a regex might still work for you.
You could start with something like this: ``` /\*[^@] ``` But in general, you don't watch to match C-style comments with regular expressions, because of nasty corner-cases. Consider: ``` "foo\" /* " " */ " ``` There's no comment in that code (it's a compile-time concatenation of two string literals), but you're not going to have much luck parsing it without a real parser. (Technically, you *could* use a regular expression, because you only need a simple finite state machine. But it's a very disgusting regular expression.)
Regular expression match only if subpattern doesn't match
[ "", "javascript", "regex", "" ]
In this very simple ASP.NET application, **Visual Web Developer 2008 Express CAN debug** the JavaScript code fine, but the full version of **Visual Studio 2005 CANNOT debug it**, namely: when I click on a line in the main.js file **it gives me a red circle with a question** mark on it, the mouse hover revealing: "This break point will not be reached, no symbols were loaded for this document." **What do I have to do to my Visual Studio 2005 so that it debugs JavaScript code like my Visual Web Developer 2008?** **Default.aspx:** ``` <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestJavascriptDebugging2005._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <script type="text/javascript" src="javascript/main.js"></script> </head> <body> <form id="form1" runat="server"> <div> <p>This is HTML and <script type="text/javascript">test()</script>.</p> <p><button onclick="doIt(this)">Test</button></p> </div> </form> </body> </html> ``` **javascript/main.js:** ``` function test() { document.write("this is from javascript code2"); } function doIt(element) { alert("This is the javascript function2."); } ```
Check if the following things are followed: i. Enable script debugging in IE. ii. Open the client side script in the script explorer, and there you are happy debugging. For details on how to accomplish this, please go through the following link from which I originally picked up this trick. 1. Debugging client [javascript](https://web.archive.org/web/20111231175002/http://geekswithblogs.net:80/lazydeveloper/archive/2006/07/10/84552.aspx) in VS2005. 2. A [Kb](https://www.microsoft.com/en-us/download/details.aspx?id=55984) from Microsoft explaining the same.
Integrated JavaScript debugging is a new feature of VS2008 - or at least, it's [much improved](http://weblogs.asp.net/scottgu/archive/2007/07/19/vs-2008-javascript-debugging.aspx)... If you search for "visual studio 2008 new features javascript debugging" you'll get lots of informative hits. It's not unreasonable for a newer version of an IDE (even the Express edition) to have more features than an older version. EDIT: Although JavaScript debugging was present in VS2005, it's better integrated in VS2008, and one of the new features is the ability to place breakpoints in JS code.
Why will Visual Studio 2005 not debug my JavaScript code?
[ "", "javascript", "visual-studio", "debugging", "visual-studio-2005", "" ]
At the moment my build process consists of repackaging the war file with all required java libraries under WEB-INF/lib and then copying the war file to development/demo/production server to be redeployed by tomcat. The packaged war file's size is about 41M and it has at the moment something like 40M of external java libraries. There has to be a better way. How have you solved this issue? My development machine is a windows box with Eclipse as my IDE and Ant as my build tool. The servers are all linux boxes with Tomcat 5.5. Should I maybe add the jar files to the war package at server side?
I can see what you are saying, and have had the same frustration with some of our webapps, but for consistency sake, I would suggest you keep things as they are. If copying the libraries to the tomcat/lib directory you may run into issues with the system classpath vs. the webapp classpath. By keeping things as they are you are sure you are deploying the same stuff in development/demo as you are in production. Life sucks when you are manually tweaking stuff in production, or you have some crazy error because you forgot to update XYZ.jar from version 1.6 to 1.6.1\_b33 in production and now it's behaving differently than what you believe is the exact same code on demo. When working with something vital enough to have dev/demo/production systems, I think consistency is much more of an issue than .war file size.
We use the rsync tool for this (in our case, using cygwin under windows) to copy the deployments to the servers (which run linux). We use exploded WAR/EAR files (i.e. a directory structure called MyApp.war rather than a zip file called MyApp.war), rsync will only transfer the files that have changed. In general use, rsync will transfer our 30-40 megabyte exploded EARs in about 5 seconds.
How to avoid copying 40M of java lib's within a WAR when the WAR's size is 41M?
[ "", "java", "tomcat", "ant", "build-process", "" ]
I want to create a Winsock UDP socket that only sends data to a client. I want the kernel to choose an available port for me. On the other hand, I want to indicate which local IP to use, since I'm running a few nics. I've tried combing through the maze of socket options, as well as binding with the port in the socket address set to 0 to no avail. My code is in Win32 C++.
Please excuse the lack of error checking: ``` char pkt[...]; size_t pkt_length = ...; sockaddr_in dest; sockaddr_in local; WSAData data; WSAStartup( MAKEWORD( 2, 2 ), &data ); local.sin_family = AF_INET; local.sin_addr.s_addr = inet_addr( <source IP address> ); local.sin_port = 0; // choose any dest.sin_family = AF_INET; dest.sin_addr.s_addr = inet_addr( <destination IP address> ); dest.sin_port = htons( <destination port number> ); // create the socket SOCKET s = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); // bind to the local address bind( s, (sockaddr *)&local, sizeof(local) ); // send the pkt int ret = sendto( s, pkt, pkt_length, 0, (sockaddr *)&dest, sizeof(dest) ); ```
The answer of Graeme Perrow doesn't work anymore because inet\_addr is deprecated. Use inet\_pton instead like this: ``` #include <string> #include <WinSock2.h> #include <Ws2tcpip.h> #pragma comment(lib, "ws2_32.lib") using namespace std; int main() { const char* pkt = "Message to be sent"; const char* srcIP = < source IP address >; const char* destIP = < destination IP address >; sockaddr_in dest; sockaddr_in local; WSAData data; WSAStartup(MAKEWORD(2, 2), &data); local.sin_family = AF_INET; inet_pton(AF_INET, srcIP, &local.sin_addr.s_addr); local.sin_port = htons(0); dest.sin_family = AF_INET; inet_pton(AF_INET, destIP, &dest.sin_addr.s_addr); dest.sin_port = htons(< destination port number >); SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); bind(s, (sockaddr *)&local, sizeof(local)); sendto(s, pkt, strlen(pkt), 0, (sockaddr *)&dest, sizeof(dest)); closesocket(s); WSACleanup(); return 0; } ```
How to set up a Winsock UDP socket?
[ "", "c++", "winapi", "sockets", "udp", "winsock", "" ]
``` $ mkdir foo $ cd foo $ hg init . $ hg log abort: Is a directory $ hg history abort: Is a directory ``` Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE\_I386 i386 ``` $ hg --version Mercurial Distributed SCM (version 1.2.1) $ python --version Python 2.5.4 ``` (all installed via macports) Thoughts? The google gives us nothing. Update: (as root): ``` $ hg init /tmp/foo $ cd /tmp/foo; hg log (works) ``` (as user): ``` $ hg init /tmp/bar $ cd /tmp/bar; hg log abort: Is a directory ``` So Travis was right (see comments) it does look like a permission problem somewhere but where? This is a stock install of Leopard barely a week old and stock installs of macport versions of python and mercurial. I hope that isn't mercurial's idea of a good error message when it has a permission problem. 2nd update (from dkbits suggestions below): ``` $ sudo dtruss hg log [snip] ... stat("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site- packages/mercurial/templates/gitweb\0", 0xBFFFC7DC, 0x1000) = 0 0 open_nocancel("/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/mercurial/templates/gitweb\0", 0x0, 0x1B6) = 3 0 fstat(0x3, 0xBFFFC900, 0x1B6) = 0 0 close_nocancel(0x3) = 0 0 write_nocancel(0x2, "abort: Is a directory\n\0", 0x16) = 22 0 ``` Also, the temp directory is where you expected it to be. Permissions look okay on it.
I took another look and it is actually caused by the .hgrc line: style = gitweb Why that is I'm not sure but the error message sure sucks still.
Not a direct answer to your question, but I've successfully been using the Mercurial pre-packaged binaries from [here](http://mercurial.berkwood.com/) with the standard Python 2.5.1 install on OSX 10.5 without issue. ``` $ mkdir foo $ cd foo $ hg init . $ hg log $ hg history $ hg --version Mercurial Distributed SCM (version 1.2.1) $ python --version Python 2.5.1 ```
mercurial + OSX == fail? hg log abort: Is a directory
[ "", "python", "macos", "mercurial", "" ]
My code i want to display in a textbox ``` <a href="http://www.erate.co.za/CompanyProfile.aspx?ID=112"> <img src="http://www.erate.co.za/CompanyAdd.bmp" alt="Go rate us on www.eRate.co.za" border="0" style="width: 136px; height: 88px" /></a> ``` But i get the ID from a Reader like this ``` reader.Item("ID").ToString ``` Now i want to set txtCode.text to this but it does not work ``` txtCode.Text = "<a href="http://www.erate.co.za/CompanyProfile.aspx?ID=" + reader.Item("ID").ToString + "> <img src="http://www.erate.co.za/CompanyAdd.bmp" alt="Go rate us on www.eRate.co.za" border="0" style="width: 136px; height: 88px" /></a>" ``` How would i do this? Etienne
In VB, quote characters are escaped with another quote: ``` txtCode.Text = "<a href=""http://www.erate.co.za/CompanyProfile.aspx?ID=" & reader.Item("ID").ToString() & ">" txtCode.Text &= "<img src=""http://www.erate.co.za/CompanyAdd.bmp"" alt=""Go rate us on www.eRate.co.za"" border=""0"" style=""width: 136px; height: 88px"" /></a>" ``` How do I know it's VB and not C#? Because this line works for you: ``` reader.Item("ID").ToString ``` In C#, it would have to be: ``` reader.Item["ID"].ToString() ```
``` txtCode.Text = @"<a href=""http://www.erate.co.za/CompanyProfile.aspx?ID=" + reader.Item("Desc_Work").ToString() + @"> <img src=""http://www.erate.co.za/CompanyAdd.bmp"" alt=""Go rate us on www.eRate.co.za"" border=""0"" style=""width: 136px; height: 88px"" /></a>"; ``` Try that, see if that works.
How to set a hyperlink to a text box in code. - with other HTML tags
[ "", "c#", "asp.net", "html", "vb.net", "" ]
I've been doing PHP/MySQL web development for a while and I'm fairly competent in it. Lately however, I've learnt Java and fallen in love with it, and I'd really like to do more Java work now. I've gotten my first opportunity with a client who needs a web 2.0ish web app built, and he has agreed to let me use anything I want to, including Java. However, I haven't done any web dev. in Java before, I've only went through the [official Java tutorial](http://java.sun.com/docs/books/tutorial/), learnt a bit about applets and build a 2D pacman game, and have done some simple work in [Google Web Toolkit](http://code.google.com/webtoolkit/). I need to get started with this project in the next 2-3 days max, so I don't have much time to read long books about the topic. This is what I've learnt so far: * Setup a Tomcat on my dev machine to work with Eclipse * Learnt the basics of servlets, the `doPost()`, `doGet()` and `init()` methods, etc * Built a mini MVC app which displays a HTML page, lets you pick something from a dropdown and when you hit submit, it retrieves your submitted value through `request.getParameter()` in the `doPost()` function, and then forwards on to a JSP page which shows which value you picked. I think these are the next few things I'd need to learn: * How to access/use databases * Sessions and Cookies * Possibly more about the syntax of JSP pages. There seem to be hundreds of topics about Java web dev which I don't know anything about., but I don't have time to learn everything. I need someone to point out any other crucial things I'd need to learn, in order to build this web app (with perhaps 20 screens) using Java and Google Web Toolkit. Also, I'm coming from a [CodeIgniter](http://codeigniter.com) background which is an MVC framework in PHP that makes things like form validation, sessions management (it uses database sessions), pagination, and common tasks like these very easy. If there is a similar, lightweight framework in Java that can take care of things like this, please mention it as well. Thanks.
There are so many different Java Enterprise technologies it's pretty hard to know where to start. As previously mentioned, the head first JSP & Servlets book is excellent. I currently work on an Enterprise app that was made years ago with just Servlets. We have migrated over to JSP's as time has gone on but we are not using any of the newer frameworks. So it is for sure a valid way to do it, although dated. The thing about java, is that most enterprise development is a conjunction of a bunch of different technologies. For example, you could create an app using JSP's for the views with a Servlet back-end, using Hibernate for you DB connections, JDOM for your XML, JUnit for your testing framework, Log4j or AspectJ for your logging framework, Lucene for search, JBoss for deployment (and deployment can be pretty non-trivial) etc. etc. etc. You aren't going to go out and learn all of those technologies in the next 3 days. What I would suggest is (as previously mentioned) to pick a framework, and there are many to choose from such as Tapestry, JSF, Wicket, Struts, etc. that will abstract away a lot of the underlying technologies. Any java technology you pick will have a good community behind it willing to help. Another thing to consider, since you seem to be in a hurry to get things working, is that (in my opinion at least) Java is not a FAST language to build things in. It is very verbose and unless you grasp the nuances of good Java web design it is very easy to shoot yourself in the foot. Perhaps you should look at some of the other technologies that are available on the JVM (so that you have all the Java libs available) such as Groovy. Groovy allows you the ability to program with Java syntax if you choose, or a dynamic Ruby-like syntax. Additionally, Grails is pretty much a Rails clone for Groovy and will let you write a web app in no time at all. Whatever you choose to do, good luck and welcome to the wonderful world of Java Web Apps.
You should skip basic servlets and use a web framework, from Struts + Tiles (simple to get to grips with - a few hours at most) to Spring, etc. In your case I would also use Hibernate for database abstraction - you don't get up to speed with JDBC in such a short time.
What do I need to learn to build a web app in Java?
[ "", "java", "jsp", "tomcat", "servlets", "" ]
I'd like to implement the ViewModel part of WPF's MVVM pattern without referencing WPF assemblies. The problematic part is command routing, which requires that ViewModels implement properties of type `ICommand` so that command bindings can work. Now, I can avoid the `ICommand` and simply declare the properties as `object`. Everything still works, so that's that. But what bothers me is, **I still have to declare them**, and I really don't want to, because they feel like **boiler plate code**. My ViewModels currently look like this: ``` public class HelloWorldViewModel : ViewModel { [BoundProperty] public string Name { get; set; } [CommandHandler("SayHello")] public bool CanSayHello() { return Name != "" && Name != null; } [CommandHandler("SayHello")] public void SayHello() { View.ShowMessage("Hello, {0}!", Name); } public object SayHello { get; private set; } } ``` The `CommandHandlerAttribute` enables runtime discovery of command handlers (an `Action` and an optional `Func<bool>`), while the `BoundPropertyAttribute` is really **an aspect** that injects itself into the property setter and calls `INotifyPropertyChanged`. I accompish this by using a **compile time IL weaver**. Ideally, I'd like to make the last line (the SayHello property) implicit, too. There would be no point in having it there in the source if it wasn't for WPF's requirement. So, naturally, I'm thinking of using the `CommandHandlerAttribute` aspect to inject the necessary IL into class and essentially **creating the property post-compile**. This is quite hard, although a good IL weaver (such as **PostSharp**) can go a long way to make it easier. Before I embark on this journey, I'd like to hear what you all think of my approach. Is it sound? Is there a better way? How would/do you do it?
To me this sounds too clever by far. There's too much "magic" happening. In particular, I dislike the magic strings and other aspects of your CommandHandlerAttribute. That said, if I were to go down this route, I'd use something akin to the EventAggregator but for commands. IOW, SayHello wouldn't exist on your ViewModel at all. What ever magic creates the command bindings to SayHell() and CanSayHello() would instead locate the command in the global CommandAggregator. As long as we're using magic strings for this, the commands in the CommandAggregator could be lazily created, thus requiring no "boiler plate" coding on your part. All that's left is to create some XAML magic (markup extension) to specify the command on the ICommandSource. ``` <Button Command="{my:AggregateCommand SayHello}"/> ```
i advice you to see how this was implemented, and it will help: **"Kind Of Magic"** Effortless INotifyPropertyChanged [http://visualstudiogallery.msdn.microsoft.com/d5cd6aa1-57a5-4aaa-a2be-969c6db7f88a][1] as an example for adding it to one property: ``` [Magic] public string Name { get { return _name; } set { _name = value; } } string _name; ``` Another example for adding it to all the class properties: ``` [Magic] public class MyViewModel: INotifyPropertyChanged { public string Name { get; set; } public string LastName { get; set; } ..... } ```
Injecting properties into .NET classes post-compile
[ "", "c#", "wpf", "mvvm", "postsharp", "code-injection", "" ]
In most JSON serializers/deserializers, the "key" part in a javascript dictionary/hash array is written as a string. What is the benefit of using a string as the key as opposed to just typing the intended name in? For example, say I define two objects `k1` and `k2` like so: ``` var k1 = { a: 1, b: 2, c: 3 }; // define name normally var k2 = { "a": 1, "b": 2, "c": 3 }; // define name with a string ``` And I then ran the following tests: ``` alert(k1 == k2); // false (of course) alert(k1.a == k2.a); // true alert(k1["b"] == k2["b"]); // true alert(uneval(k1)); // returns the k1 object literal notation. alert(uneval(k2)); // returns the same string as above line. alert(uneval(k1) == uneval(k2)); // true ``` So what's the point of having the keys be in double-quotation marks (a string) as in the way `k2` was defined instead of just typing the key names in as in the way `k1` was defined? --- I just saw this over at [Ajaxian](http://ajaxian.com/archives/chrome-extension-api-how-we-wish-we-have-named-parameters) pointing to [Aaron Boodman's blog entry](http://www.aaronboodman.com/2009/04/yo-dawg.html): ``` chromium.tabs.createTab({ "url": "http://www.google.com/", "selected": true, "tabIndex": 3 }); ``` Since he also use camel case for tabIndex, I don't see any point in using a string at all. Why not: ``` chromium.tabs.createTab({ url: "http://www.google.com/", selected: true, tabIndex: 3 }); ``` Why would a JS ninja follows the convention of turning `url`, `selected` and `tabIndex` into a string?
Because [JSON](http://www.json.org/) is a subset of the actual JavaScript literal syntax. For simplicity in implementing JSON parsers, double quotes are always required around strings, and as keys in JSON are strings, they are required there. Not all legal JavaScript is legal JSON. While you can define object literals in JavaScript without the quotes, if you want interoperable JSON, you're going to need to put them in.
Because doing so, you avoid to use, by error, a javascript reserved keyword, like "do" for example. Using the string notation kept you on the safe side.
Why should the "key" part in a JS hash/dict be a string?
[ "", "javascript", "dictionary", "coding-style", "" ]
I've seen different questions on SO about not being able to use parameterless constructors or not setting field initializers, but I think my question kind of goes a step beyond that. What I would like to know is, how would I go about setting up the "default" value of a struct I need to define? Say I'm making a TaxID struct, and the default value needs to be 999-99-9999 for whatever reason. This is already done with other structs in .NET, namely the DateTime. Any time you declare a DateTime the value is immediately set to Jan 1 0001 12:00 AM. Why does it get set to this value and not 0/0/0000 00:00:0000 AM? There must be something going on behind the scenes that makes the value actually make "sense" at it's "default", even given the restrictions put on us by c# with regards to structs.
In general, this should be avoided. If you need to require a good, default case which would require construction, you should consider changing to a class. One of the core design guidelines for structs is: Do ensure that a state where all instance data is set to zero, false, or null (as appropriate) is valid. For details, see [the design guidelines](http://msdn.microsoft.com/en-us/library/ms229031.aspx). --- I just looked this section up in the design guidelines 2nd edition, and they have an example in detail there using properties and non-conventional overrides to work around this, as well. The basic concept was to save the value privately in a way that 0 is the "good default", and do some form of transform in every property and method override (including ToString). In their case, they used a positive integer as an example, and always save curVal-1 in the private member, so the default value (0) is treated like a value of 1. They added a constructor with an int val, and save value-1 internally, etc. This seems like a lot of hidden, unexpected overhead, though - so I'd personally still recommend (and use) a class in this case. --- Edit in response to comments --- DateTime, as your example, is the way it is because 0 == 1/1/0001 at Midnight. DateTime uses a single, ulong to represent ticks from 1/1/0001. That is why ([from here](http://msdn.microsoft.com/en-us/library/system.datetime.aspx)): "The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) " This is the full range of ulong in ticks. A "0" in the struct of DateTime is treated as 1/1/0001 when you convert to a string - the values aren't 1 + 1 + .... - it's a single 0.
> Any time you declare a DateTime the value is immediately set to Jan 1 0001 12:00 AM. Why does it get set to this value and not 0/0/0000 00:00:0000 AM? There must be something going on behind the scenes that makes the value actually make "sense" at it's "default", even given the restrictions put on us by c# with regards to structs. More likely it implicitly initializes a ticks field to `default(int)` = 0, and 0 ticks means `DateTime.MinValue` when you go to get the value.
How do you specify what a default state of a derived struct should be in C#?
[ "", "c#", ".net", "struct", "" ]
As an extension to this question [Are `const_iterators` faster?](https://stackoverflow.com/questions/755347/are-constiterators-faster), I have another question on `const_iterators`. How to remove constness of a `const_iterator`? Though iterators are generalised form of pointers but still `const_iterator` and `iterator`s are two different things. Hence, I believe, I also cannot use `const_cast<>` to covert from `const_iterator` to `iterator`s. One approach could be that you define an iterator which moves 'til the element to which `const_iterator` points. But this looks to be a linear time algorithm. Any idea on what is the best way to achieve this?
There is a solution with constant time complexity in C++11: for any sequence, associative, or unordered associative container (including all of the Standard Library containers), you can call the range-erase member function with an empty range: ``` template <typename Container, typename ConstIterator> typename Container::iterator remove_constness(Container& c, ConstIterator it) { return c.erase(it, it); } ``` The range-erase member functions have a pair of `const_iterator` parameters, but they return an `iterator`. Because an empty range is provided, the call to erase does not change the contents of the container. [Hat tip to Howard Hinnant and Jon Kalb for this trick.](https://twitter.com/#!/JonathanKalb/status/202815932089896960)
Unfortunately linear time is the only way to do it: ``` iter i(d.begin()); advance (i,distance<ConstIter>(i,ci)); ``` where iter and constIter are suitable typedefs and d is the container over which you are iterating.
How to remove constness of const_iterator?
[ "", "c++", "stl", "iterator", "const-iterator", "" ]