Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
There seem to be three main ways to output content from Wordpress using its built-in functions, with `WP_Query` being the recommended one: * [WP\_Query](http://codex.wordpress.org/Function_Reference/WP_Query) * [query\_posts](http://codex.wordpress.org/Template_Tags/query_posts) * [get\_posts](http://codex.wordpress.org/Template_Tags/get_posts) What are the differences between them? (I understand that `WP_Query` is the class, and the other two are methods). What is the cleanest way to have multiple loops on the same page, without any of them interfering with each other? I'm looking for examples of how you program your WP loops; e.g. output 2 separate post lists by category, with attachments, meta data etc. This is the best reference I found so far: * [Define Your Own WordPress Loop Using WP\_Query](http://weblogtoolscollection.com/archives/2008/04/13/define-your-own-wordpress-loop-using-wp_query/)
I've used both WP\_Query and get\_posts. On one of my sidebar templates, I use the following loop to display posts from a particular category by using custom fields with a key of 'category\_to\_load' which contains the category slug or category name. The real difference comes in the implementation of either method. The get\_posts method looks like so in some of my templates: ``` <?php global $post; $blog_posts = get_posts( $q_string ); foreach( $blog_posts as $post ) : setup_postdata( $post ); ?> <div class="blog_post"> <div class="title"> <h2> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h2> <span class="date"><?php the_time( 'F j, Y' ); ?> by <?php the_author(); ?></span> </div> <?php the_excerpt(); ?> </div> <?php endforeach; ?> ``` Where the `WP_Query` implementation looks like this: ``` $blog_posts = new WP_Query( 'showposts=15' ); while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>" class="blog_post"> <div class="title"> <h2> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h2> <span class="date"><?php the_time( 'F jS, Y' ) ?> <!-- by <?php the_author() ?> --></span> </div> <div class="entry"> <?php the_content(); ?> </div> <p class="postmetadata"><?php the_tags( 'Tags: ', ', ', '<br />' ); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?> <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></p> </div> <?php endwhile; ?> ``` The main difference is that you don't have to reset the global $post variable and you also don't have to set up the post data by calling setup\_postdata($post) on each post object when you use WP\_query. You can also use the lovely have\_posts() function on the WP\_Query function, which is not available using get\_posts(). You shouldn't use the query\_posts() function unless you really mean to because it modifies the main loop for the page. See the [docs](http://codex.wordpress.org/Template_Tags/query_posts#Parameters). So if you're building a special page to display your blog on, then calling query\_posts may mess up the page's loop, so you should use WP\_Query. That's just my two cents. My ultimate suggestion, your first choice should be WP\_Query. -Chris
From the WP docs for get\_posts: > get\_posts() can also take the parameters that query\_posts() can since both functions now use the same database query code internally. The only difference between the two functions is that get\_posts returns an array with post records, while query\_posts stores the records in the query object for retrieval by the template functions (has\_posts, the\_post, etc). They both use the WP\_Query object to execute the query. Creating a second loop is covered in the [Wordpress docs](http://codex.wordpress.org/The_Loop#Multiple_Loops). There are some links there for other examples of multiple loops. You'll notice that everyone does it differently, but they all seem happy with their results.
What is the best method for creating your own Wordpress loops?
[ "", "php", "wordpress", "loops", "" ]
I've dabbled with MySQL and personally, I find it vastly inferior to better RDBMSs like Postgres; while I admit it's come a long way and improved, even the latest version to my knowledge does not even support `CHECK` constraints to verify data integrity (it allows the keyword but doesn't do anything with it). As someone who is looking at switching away from Microsoft technologies and into open source, I am appalled by the sheer number of PHP-backed applications that will **only** work with MySQL as the underlying database. A number of these apps are really good and would save a lot of work in development, but the fact they haven't been abstracted to be database agnostic is usually a deal-killer for me and my technical associates. So I am curious - I understand why MySQL is so popular and why it's almost always used with PHP, but why do so many PHP-backed sites refuse to be properly developed to allow for other databases, but instead force MySQL when there are much better and more "database-like" options out there? I'm getting increasingly frustrated by these apps that I want to use, but they only work with MySQL and I won't bring myself to use it because personally I find Postgres a much better database, and because I personally feel that your database should enforce it's own constraints instead of doing this only at the code level. I realize MySQL is popular, and it's not a *bad* system, but I hate when I find a great application and it'll only work when the database is MySQL because the developers used MySQL-specific modules and/or syntax.
Most PHP developers develop with PHP because it's free, easy to get going, and powerful. All of the same qualities are shared with MySQL, so it's a natural fit. That being said, many professional developers create data-abstraction layers that would allow them easy integration with other backends. But most projects don't need those types of things.
I'm sure its the same reason there's so many ASP.NET stuff that only supports MSSQL. Its the traditional database paired with the language just by convention. Plus using/building database independent solutions is hard and one of those things that "you aint gonna need" when most so many other people follow that convention. When its needed its one of those things that can be "page faulted" in. If you need to get a php app to use another DB, the php is probably open source, perhaps you can do the work yourself.
Why are there so many PHP sites that only provide for MySQL as a database?
[ "", "php", "mysql", "" ]
What's the most efficient way to put as many bytes as possible from a ByteBuffer `bbuf_src` into another ByteBuffer `bbuf_dest` (as well as know how many bytes were transferred)? I'm trying `bbuf_dest.put(bbuf_src)` but it seems to want to throw a BufferOverflowException and I can't get the javadocs from Sun right now (network problems) when I need them. >:( argh. --- edit: darnit, @Richard's approach (use put() from the backing array of `bbuf_src`) won't work if bbuf\_src is a ReadOnly buffer, as you can't get access to that array. What can I do in that case???
OK, I've adapted @Richard's answer: ``` public static int transferAsMuchAsPossible( ByteBuffer bbuf_dest, ByteBuffer bbuf_src) { int nTransfer = Math.min(bbuf_dest.remaining(), bbuf_src.remaining()); if (nTransfer > 0) { bbuf_dest.put(bbuf_src.array(), bbuf_src.arrayOffset()+bbuf_src.position(), nTransfer); bbuf_src.position(bbuf_src.position()+nTransfer); } return nTransfer; } ``` and a test to make sure it works: ``` public static boolean transferTest() { ByteBuffer bb1 = ByteBuffer.allocate(256); ByteBuffer bb2 = ByteBuffer.allocate(50); for (int i = 0; i < 100; ++i) { bb1.put((byte)i); } bb1.flip(); bb1.position(5); ByteBuffer bb1a = bb1.slice(); bb1a.position(2); // bb3 includes the 5-100 range bb2.put((byte)77); // something to see this works when bb2 isn't empty int n = transferAsMuchAsPossible(bb2, bb1a); boolean itWorked = (n == 49); if (bb1a.position() != 51) itWorked = false; if (bb2.position() != 50) itWorked = false; bb2.rewind(); if (bb2.get() != 77) itWorked = false; for (int i = 0; i < 49; ++i) { if (bb2.get() != i+7) { itWorked = false; break; } } return itWorked; } ```
As you've discovered, getting the backing array doesn't always work (it fails for read only buffers, direct buffers, and memory mapped file buffers). The better alternative is to duplicate your source buffer and set a new limit for the amount of data you want to transfer: ``` int maxTransfer = Math.min(bbuf_dest.remaining(), bbuf_src.remaining()); // use a duplicated buffer so we don't disrupt the limit of the original buffer ByteBuffer bbuf_tmp = bbuf_src.duplicate (); bbuf_tmp.limit (bbuf_tmp.position() + maxTransfer); bbuf_dest.put (bbuf_tmp); // now discard the data we've copied from the original source (optional) bbuf_src.position(bbuf_src.position() + maxTransfer); ```
transferring bytes from one ByteBuffer to another
[ "", "java", "javadoc", "nio", "" ]
I'm sending emails that have invoices attached as PDFs. I'm already - elsewhere in the application - creating the invoices in an .aspx page. I'd like to use Server.Execute to return the output HTML and generate a PDF from that. Otherwise, I'd have to use a reporting tool to "draw" the invoice on a PDF. That blows for lots of reasons, not the least of which is that I'd have to update both the .aspx page and the report for every minor change. What to do...
There is no way to generate a PDF from an HTML string directly within .NET, but there are number of third party controls that work well. I've had success with this one: <http://www.html-to-pdf.net> and this: <http://www.htmltopdfasp.net> The important questions to ask are: 1. Does it render correctly as compared to the 3 major browsers: IE, FF and Safari/Chrome? 2. Does it handle CSS fine? 3. Does the control have it's own rendering engine? If so, bounce it. You don't want to trust a home grown rendering engine - the browsers have a hard enough problem getting everything pixel perfect. 4. What dependencies does the third party control require? The fewer, the better. There are a few others but they deal with ActiveX displays and such.
We use a product called ABCPDF for this and it works fantastic. <http://www.websupergoo.com/abcpdf-1.htm>
Generate PDF from ASP.NET from raw HTML/CSS content?
[ "", "c#", "asp.net", "html", "pdf", "" ]
I've heard ubuntu 9.4 will but it's still in alpha. Are there any stable distros that come with python 2.6 or at least don't depend on it so much so reinstalling python won't break anything?
Arch Linux - <http://www.archlinux.org/>
You can install python 2.6 in Ubuntu 8.10 just fine. ``` ./configure --prefix=/usr/local make sudo make altinstall --prefix=/usr/local ``` Then just run python with: ``` python2.6 ``` If you want to use it in a shebang line, just use: ``` #!/usr/bin/env python2.6 ``` Your scripts will still work when Jaunty 9.04 is around with native python2.6.
Is there any linux distribution that comes with python 2.6 yet?
[ "", "python", "linux", "" ]
Suppose I have a `Base` class: ``` class Base { friend SomeOtherClass; }; ``` And there is another (different) class that inherits from `Base`: ``` class AnotherClass : public Base {} ``` Is friendship inherited as well?
In principle, a derived class inherits every member of a base class except: ``` * its constructor and its destructor * its operator=() members * its friends ``` So, no. Friends are not inherited.
No it isn't. **Edit:** To quote from the C++ Standard, section 11.4/8 > Friendship is neither inherited nor > transitive.
Is friendship inherited in C++?
[ "", "c++", "inheritance", "friend", "access-control", "" ]
I have some Javascript which "animates" a colour change on an HTML element, as follows: ``` var element = document.getElementById("someid"); while (i < 255) { element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')'; i++; slowMeDown(); // This function runs for a few ms to slow the process down } ``` As you can see, this changes the color from black to white going through 255 shades of grey in between. I would like to make it visibly "fade" so that the user can see the text gradually disappear. However, the browser (Chrome and IE - not tested on Firefox yet) only refreshes at the end of the function, so the color simply changes from black to white. Does anyone know how to make the browser repaint during the loop so that I can see the text fade?
``` function changeColor() { changeColorIncremental(0); } function changeColorIncremental(i) { var element = document.getElementById("someid"); element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')'; if (i < 255) { // Note the 50 millisecond wait below. Decrease this to speed up // the transition, and increase it to slow it down. setTimeout('changeColorIncremental(' + (i + 1) + ')', 50); } } ```
You should look into JQuery. It will do all of this for you using the [Effects functions](http://docs.jquery.com/Effects) or plugins. However in answer to the question: Normally web browsers only use a single UI update thread that is also used to execute Javascript code. Therefore the browser will execute your loop entirely and only then update the page once it is complete (ie all RGG = 255,255,255). Try using window.setTimeout or window.setInterval to call a function that increments the RGB values. This allows the browser UI update thread to update the display after each call (between the interval or timeout). (I believe all the major browsers operate this way including Firefox). Note: setInterval and setTimeout execute code on the single same UI thread. They simply add a timer callback to the window message loop and this gets called and executed at the correct time. Therefore, if other Javascript code or a UI update was executing at the time, the timer function must wait. So the function is not guaranteed to occur at exactly the time specified. Also (on Windows) the maximum resolution is much less then 1 millisecond, often about 1/20th of a second or about 50 milliseconds.
How do I make an HTML element repaint within a Javascript loop?
[ "", "javascript", "colors", "" ]
Stuck on a (rather simple) regex problem in PHP. Buried in a mess of text is this section: ``` &lt;tr&gt; &lt;td id=&quot;descriptionArea&quot;&gt; Customer request to remove &quot;Intro - 01/13/09&quot; video clip. &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt; ``` I want whatever is between: ``` descriptionArea&quot;&gt; ``` ...and... ``` &lt;/td&gt; ``` A friend suggested: ``` $pattern = '&lt;td=&quot;descriptionArea&quot;&gt;\s*(.*?)\s*&lt;'; $clean = preg_replace("'[\n\r\s\t]'","",$text); // to rid of line breaks preg_match($pattern, $clean, $matches); print_r($matches); ``` But I get the following error: ``` Warning: preg_match() [function.preg-match]: Unknown modifier 'q' ``` I suppose the second question is whether preg\_match is the correct PHP function for this, also. Should I be using ereg instead? Thanks for your help.
When using the `preg_*` functions, the first character or the pattern is treated as delimiter: > The expression must be enclosed in the delimiters, a forward slash (`/`), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (`\`). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style `()`, `{}`, `[]`, and `<>` matching delimiters. > — [Regular Expressions (Perl-Compatible) – Introduction](http://docs.php.net/manual/en/intro.pcre.php) So you don’t need to escape or replace the `&` characters as others said. Instead use proper delimiters and escape those characters inside the expression: ``` '/&lt;td id=&quot;descriptionArea&quot;&gt;(.*?)&lt;\/td&gt;/' ```
You'll want to escape out the "&", like wombleton says, and also enclose your pattern with forward slashes, like $pattern = "/pattern/"; The below code returns an array with some ugly stuff in it but at least it returns a match.. :) ``` $description = " &lt;tr&gt; &lt;td id=&quot;descriptionArea&quot;&gt; Customer request to remove &quot;Intro - 01/13/09&quot; video clip. &lt;br/&gt; &lt;/td&gt; &lt;/tr&gt;"; $pattern = "/&lt;td.*[&]quot;descriptionArea[&]quot;[&]gt;\s*(.*?)\s*.*?lt/"; $clean = preg_replace("'[\n\r\s\t]'","",$description); // to rid of line breaks preg_match($pattern, $clean, $matches); var_dump($matches); ``` **EDIT** Here's a nicer version. Get rid of all the HTML encoding so you can use a standard HTML-parsing regex: ``` $pattern = '/<.*?id="descriptionArea">(.*?)<\/td>/'; $clean = preg_replace("'[\n\r\t]'","",htmlspecialchars_decode($description)); preg_match($pattern, $clean, $matches); ```
Regex Basics: grab text between two constants
[ "", "php", "regex", "" ]
I'm trying to figure out if there's a way I can somehow notify a web browser of an event from a web server. I know Ajax lets you asynchronously make a request to update a section of a page. I guess I could have a timer periodically ask for updates. But, I'd prefer to avoid a polling scheme, if possible. Is there a better way to go and still remain with a browser-based solution?
Check out ["comet"](http://en.wikipedia.org/wiki/Comet_(programming)) techniques, where you basically hold a connection open to a server which pushes data back at you.
Well, you could try to set the "ignore-user-abort"-flag on, and make sure that the script doesn't terminates (while condition) sleep()). After you have echo'ed the information you need to transfer, flush() the text to the browser. But i would't recommend this solution. Instead: Go with ajax, and use a polling scheme. Most up-to-date framework support it out of the box.
can you asyncronously notify a web browser?
[ "", "javascript", "ajax", "" ]
I have an array in this format: ``` Array ( [0] => Array ( [28th February, 2009] => 'bla' ) [1] => Array ( [19th March, 2009] => 'bla' ) [2] => Array ( [5th April, 2009] => 'bla' ) [3] => Array ( [19th April, 2009] => 'bla' ) [4] => Array ( [2nd May, 2009] => 'bla' ) ) ``` I want to sort them out in the ascending order of the dates (based on the month, day, and year). What's the best way to do that? Originally the emails are being fetched in the MySQL date format, so its possible for me to get the array in this state: ``` Array [ ['2008-02-28']='some text', ['2008-03-06']='some text' ] ``` Perhaps when its in this format, I can loop through them, remove all the `'-'` (hyphen) marks so they are left as integars, sort them using `array_sort()` and loop through them yet again to sort them? Would prefer if there was another way as I'd be doing 3 loops with this per user. Thanks. Edit: I could also do this: ``` $array[$index]=array('human'=>'28 Feb, 2009', 'db'=>'20080228', 'description'=>'Some text here'); ``` But using this, would there be any way to sort the array based on the 'db' element alone? Edit 2: Updated initial var\_dump
Use the ISO (`yyyy-mm-dd`) format rather than the "english" format, and then just use the [`ksort`](http://www.php.net/manual/en/function.ksort.php) function to get them in the right order. There's no need to remove the hyphens, `ksort` will do an alphanumeric comparison on the string keys, and the `yyyy-mm-dd` format works perfectly well as the lexical order is the same as the actual date order. **EDIT** I see you've now corrected your question to show that you've actually got an array of arrays, and that the sort key is in the sub-arrays. In this case, you should use `uksort` as recommended elsewhere, but I would recommend that you go with your own edit and sort based on the DB formatted date, rather than by parsing the human readable format: ``` function cmp($a, $b) { global $array; return strcmp($array[$a]['db'], $array[$b]['db']); } uksort($array, 'cmp'); ```
Actually, use this: ``` usort($array, "cmp"); function cmp($a, $b){ return strcmp($b['db'], $a['db']); } ``` :)
How to sort a date array in PHP
[ "", "php", "arrays", "arraylist", "associative-array", "sorting", "" ]
**Background** I have a project named *PersonLibrary* which has two files. 1. Person.h 2. Person.cpp This library produces a static library file. Another project is *TestProject* which uses the *PersonLibrary* (Added though project dependencies in VS008). Everything worked fine until I added a non-member function to *Person.h*. *Person.h* looks like ``` class Person { public: void SetName(const std::string name); private: std::string personName_; }; void SetPersonName(Person& person,const std::string name) { person.SetName(name); } ``` *Person.cpp* defines *SetName* function. When I try to use *SetPersonName* from *TestProject*, I get *error LNK2005: already defined*. Here is how I used it ``` #include "../PersonLibrary/Person.h" int main(int argc, char* argv[]) { Person person; SetPersonName(person, "Bill"); return 0; } ``` **Workarounds tried** 1 - I have removed the *Person.cpp* and defined the whole class in *Person.h*. Error gone and everything worked. 2 - Changed the *SetPersonName* modifier to *static*. Like the below ``` static void SetPersonName(Person& person,const std::string name) { person.SetName(name); } ``` **Questions** 1. Why the code shown first is not working as I expected? 2. What difference *static* made here? 3. What is the approapriate solution for this problem? Thanks
You either have to * move `SetPersonName`'s definition to a .cpp file, compile and link to the resulting target * make `SetPersonName` inline This is a well known case of One Definition Rule violation. The static keyword makes the function's linkage internal i.e. only available to the translation unit it is included in. This however is hiding the real problem. I'd suggest move the definition of the function to its own implementation file but keep the declaration in the header.
When you compile you're library, its lib file contains a definition for SetPersonName. When you compile your program that uses the library, since it includes the header, and you've written the code inline in the header it also compiles in a definition for SetPersonName. Two definitions for the same function aren't (generally) allowed. The static keyword tells the compiler that the function shouldn't be exposed outside of the current translation unit (discrete piece of code you are compiling), so the definition in the library isn't visible to the linker. The appropriate solution to this problem depends on your goals. Header files with static function declarations is almost never what you want. From a design standpoint I would recommend getting rid of SetPersonName altogether, and just use Person::SetName. However, failing that, I would implement it much like you've done for the rest of your functionality, declarations in the header, and implementation in the .cpp. Inline functions associated with a library will tend to diminish many of the advantages of using a library in the first place.
error LNK2005: already defined - C++
[ "", "c++", "linker", "" ]
I'm trying to fix the test suite on an project which I've inherited from another programmer for some java database code. The project itself is using hibernate and MySQL for the DB stuff, but for the purposes of the test cases dbunit is being used. I can correctly load and initialize hibernate's session factory, but I keep getting exceptions when I try to run my tests in Eclipse, namely "org.dbunit.dataset.NoSuchTableException: mytablename". I know that all the files are in the right place, and that the actual XML file I'm passing into dbunit is ok (I'm using the FlatXmlDataSet type). My setUp() method in the database test case base class looks like this: ``` @Override protected void setUp() throws Exception { super.setUp(); IDataSet dataSet = new FlatXmlDataSet(new File(mDataFile)); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); IDatabaseConnection connection = new DatabaseConnection(session.connection()); DatabaseConfig config = connection.getConfig(); config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory()); DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet); session.getTransaction().commit(); } ``` Right after the CLEAN\_INSERT database operation, the exception gets thrown complaining about **the last table in my XML file**, regardless of which table this is. I have verified the DTD and XML schema by hand and with Eclipse, even going to the point of making sure the ordering of the tables in the two files matched. I'd rather not paste those files in here (as it would involve a lot of search-replacing), but trust me that I've looked through dbunit examples and made sure that the syntax matches. Any ideas on what could be wrong? I've been googling for hours and can't come up with anything useful. **Edit:** One thing I forgot to mention, is that when I place a breakpoint at the line which throws, I can look through dataSet's structure and see that all of my tables are actually in there, along with all of the test data. So at least that part seems to be working correctly. @Bogdan: Hrm... good idea. I'll try loading the data with a regular INSERT. @sleske: Also a good suggestion. Thanks for the hints; hopefully this will set me on the right path to fixing this problem.
sleske was indeed right -- much more information was needed to solve this problem, which means I wasn't asking the right question. Although both suggestions here were helpful, I would feel bad marking one as being the correct answer, given that I wasn't asking the correct question, so I'll instead document here what I did to get this working. Basically, the problem was caused by other types of schema mismatches. The test DB's DTD and XML matched, but the DTD no longer matched the **actual** schema listed in the hbm.xml files (ie, what we are using in the production DB), and the test database in the XML file was missing certain columns which were later marked as NOT NULL. Also, the XML included tables which did not have .hbm.xml config files, as the original authors of this code never got around to writing the features which would be using these tables. So even though they were specified in the DTD, the absence of a corresponding HBM mapping caused problems. Also, I had to rewrite some of our database test case base class code based on what I found [in this blog post about using hibernate and dbunit together](http://bill.dudney.net/roller/bill/date/20040521). Finally, I needed to fix our build process so that a "hibernate-test.cfg.xml" file was used in place of the real configuration, and then everything worked fine. Now I just need to figure out why some of the test cases are throwing exceptions. :)
The `DatabaseOperation.CLEAN_INSERT` is essentially a combination of `DatabaseOperation.DELETE_ALL` and `DatabaseOperation.INSERT`. Since the `DatabaseOperation.DELETE_ALL` clears the tables in reversed order, I suspect that it does not fail when clearing the last table, but when clearing the first one. Are you sure that the tables from your data set actually exist in the database you are using while testing? The error you are getting would suggest that they don't.
NoSuchTableException being thrown from dbunit test cases
[ "", "java", "exception", "dbunit", "" ]
I'm interested in the best practices of using LDAP authentication in a Java-based web application. In my app I don't want to store username\password, only some ids. But I want to retrieve addition information (Name, Last name) if any exists in an LDAP catalog.
My team uses LDAP as a standard way of authentication. Basically, we treat LDAP as any another database. To add user to application, you have to pick one from LDAP or create it in LDAP; when user is deleted from application, it stays in LDAP but has no access to application. You basically need to store only LDAP username locally. You can either read LDAP data (e-mail, department etc) from LDAP each time, or pull it in application in some way, though reading it from LDAP is probably simpler and smarter since LDAP data can change. Of course, if you need reporting or use LDAP data extensively, you might want to pull it from LDAP (manually or with batch task). The nice thing is that once a user is disabled in LDAP, it's disabled in all applications at once; also, user has same credentials in all applications. In corporate environment, with a bunch of internal applications, this is a major plus. Don't use LDAP for users for only one application; no real benefits in that scenario.
For general best practices with LDAP, see ["LDAP: Programming practices"](http://www.ldapguru.info/ldap/ldap-programming-practices.html).
LDAP Best Practices
[ "", "java", "jakarta-ee", "ldap", "" ]
The network between our company and Sun's javadocs seems to be down. Where can I get a copy of the javadocs for a given package, so that I can keep my own stash to handle network outages in the future? Are there any mirrors for the Sun javadocs?
Down for me too (java.sun.com seems to be MIA at the moment). Some form of the JDK docs are here: <http://www.docjar.com/docs/api/java/>
For each major release there is a large doc package, e.g. [here for JDK 1.6](http://java.sun.com/javase/6/download.jsp#docs). (I hope the link is correct, picked it out of the docs I downloaded a while ago. Can't connect to SUN either from here.)
Downloading Sun javadocs / mirror websites
[ "", "java", "javadoc", "" ]
Given the following HQL Query: ``` FROM Foo WHERE Id = :id AND Bar IN (:barList) ``` I set `:id` using the Query object's `setInteger()` method. I would like to set `:barList` using a `List` of objects, but looking at the Hibernate documentation and list of methods I cannot see an obvious choice of which to use. Any ideas?
Use `Query.setParameterList()`, [Javadoc here](http://docs.jboss.org/hibernate/core/3.2/api/org/hibernate/Query.html#setParameterList%28java.lang.String,%20java.util.Collection%29). There are four variants to pick from.
I'm not sure about HQL, but in JPA you just call the query's `setParameter` with the parameter and collection. ``` Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)"); q.setParameter("names", names); ``` where `names` is the collection of names you're searching for ``` Collection<String> names = new ArrayList<String(); names.add("Joe"); names.add("Jane"); names.add("Bob"); ```
Hibernate HQL Query : How to set a Collection as a named parameter of a Query?
[ "", "java", "hibernate", "hql", "" ]
I came across several interfaces while learning JDBC - Connection, Statement, ResultSet etc... Does this imply that some classes somewhere, hidden from me, are implementing these interfaces, and providing their references when I need it? Is this because they need to be implemented differently depending on the Driver I'm using?
> Is this because they need to be implemented differently depending on the Driver I'm using? For example. It's general best practice to code to an interface instead of an implementation (= class, in this context), for multiple reasons. One of them has been mentioned by you: related but different implementations can share a common interface. Another point is that one particular implementation can be changed behind the scenes without requiring changing the interface as well: let's say the next implementation of the driver needs to use another class. It's enough to implement the existing interface. Now imagine that instead of interfaces, the code dealt with class types. Now, if the implementation changed, these interfaces would need to be changed as well. This would mean that every user (including you) of the API had to change their code as well!
Yes, you are right. Implementation for these interfaces can be found in the database JDBC drivers.
Who/What implements Interfaces that I can use directly?
[ "", "java", "interface", "" ]
Short question: Has anybody got any C# code to parse robots.txt and then evaluate URLS against it so see if they would be excluded or not. Long question: I have been creating a sitemap for a new site yet to be released to google. The sitemap has two modes, a user mode (like a traditional sitemap) and an 'admin' mode. The admin mode will show all possible URLS on the site, including customized entry URLS or URLS for a specific outside partner - such as `example.com/oprah` for anyone who sees our site on Oprah. I want to track published links somewhere other than in an Excel spreadsheet. I would have to assume that someone might publish the `/oprah` link on their blog or somewhere. We don't actually want this 'mini-oprah site' to be indexed because it would result in non-oprah viewers being able to find the special Oprah offers. So at the same time I was creating the sitemap I also added URLS such as `/oprah` to be excluded from our `robots.txt` file. **Then** (and this is the actual question) I thought 'wouldn't it be nice to be able to show on the sitemap whether or not files are indexed and visible to robots'. This would be quite simple - just parse robots.txt and then evaluate a link against it. However this is a 'bonus feature' and I certainly don't have time to go off and write it (even thought its probably not that complex) - so I was wondering if anyone has already written any code to parse robots.txt ?
Hate to say that, but just google "C# robots.txt parser" and click the first hit. It's a [CodeProject article about a simple search engine implemented in C# called "Searcharoo"](http://www.codeproject.com/KB/IP/Searcharoo_4.aspx), and it contains a class Searcharoo.Indexer.RobotsTxt, described as: > 1. Check for, and if present, download and parse the robots.txt file on the site > 2. Provide an interface for the Spider to check each Url against the robots.txt rules
I like the code and tests in <http://code.google.com/p/robotstxt/> would recommend it as a starting point.
Anybody got any C# code to parse robots.txt and evaluate URLS against it
[ "", "c#", "robots.txt", "" ]
I've been working on a web application that should be able to accept tags and search queries in multiple languages. That's not asking too much, is it? Now, on my development MAMP server everything is great. I add multilingual tags, search in any language I want etc. On the other hand, on the production WAMP server, multilingual characters give trouble. And not even all the time, just some of the time, or some of the characters, I'm not sure yet. What happens is that they get extra characters and then their URL decoding isn't proper. Both Environments use PHP 5, MySQL and Apache. My guess is that I got a setting wrong somewhere. Any Ideas? * update: I'm now sure it's particular letters (the hebrew ל,מ א for example) * update: easily reproducible: always the same letters get wrong encoding. * content type is `text/html; charset=utf-8` Also, I've pinpointed it a bit further: I use the search string: **ליבני** On the results page I see this: * In the address bar the search phrase is correct, properly url-encoded. * In the HTML itself I see the string "**�\_יבני**" which is "`%D7_%D7%99%D7%91%D7%A0%D7%99`" which means the **ל** has been encoded to "`%D7_`" instead of "`%D7%9C`" as it should have. I don't really know where to go further. Any ideas? anyone?
It turns out the problem is somewhere within PHP's parse\_url(). I guess that in some versions, on some platforms, parse\_url() doesn't handle UTF characters correctly. It was spotted on windows [at least one more time](http://joomlacode.org/gf/project/joomla/tracker/?action=TrackerItemEdit&tracker_item_id=14708). I was able to workaround it for now. Thanks for everybody's time and attention, Omer.
Charsets are rally a simple concept. The confusing thing about them, is that there are multiple levels where it must be done correctly. If you mess up in one place, it will usually show in a completely different place. So the slightly condescending, but also very true answer to your problem is that you need to know what you're doing, instead of just poking at it with a stick until it kind of looks okay. I recommend the following reading: * <http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet> * <http://www.phpwact.org/php/i18n/charsets> * <http://www.joelonsoftware.com/articles/Unicode.html> * <http://kore-nordmann.de/blog/php_charset_encoding_FAQ.html>
Character encoding seems to work on a MAMP server but not on a WAMP server
[ "", "php", "apache", "wamp", "url-encoding", "utf", "" ]
I use Java for client-side development with Swing. I love Swing; I believe it is one of the better GUI frameworks there. What I miss, however, is the support for declarative validation. Like [this snippet](http://en.wikibooks.org/wiki/XForms/Facet_Validation) from XForms. Do you know any library which allows validating data entry in forms in a declarative way, not by writing ugly validation document listeners for every component there?
You could try one of the implementations of [JSR 303 Bean Validation](http://jcp.org/en/jsr/detail?id=303). I don't think it is finalized yet but there are a few implementations around like [Hibernate Validator](http://www.hibernate.org/412.html "Hibernate Validator") and [Agimatec Validation](http://code.google.com/p/agimatec-validation/ "Agimatec Validation"). I haven't tried either but reading through some examples of how Bean Validation will be used makes it look promising. Here is an [interview](http://java.dzone.com/articles/bean-validation-rest-us-%E2%80%93 "Spec Lead") with the spec lead. What I like most about the proposal is that the validation rules can be reused in different layers and with different frameworks. You can choose between annotations and xml for doing the 'declaring'. Lastly you might want to check out [Swing Java Builders](http://code.google.com/p/javabuilders/) which provides a declarative way for defining GUIs and doing validation and data binding with Swing.
You may look at my attempt to build a Swing GUI builder, that uses JSR303 validation with Hibernate Validator: <http://code.google.com/p/swing-formbuilder/>
Declarative validation of forms in Java/Swing
[ "", "java", "validation", "swing", "declarative", "" ]
How many parameters can you pass to a string.Format() method? There must be some sort of theoretical or enforced limit on it. Is it based on the limits of the params[] type or the memory usage of the app that is using it or something else entirely?
OK, I emerge from hiding... I used the following program to verify what was going on and while Marc pointed out that a string like this "{0}{1}{2}...{2147483647}" would succeed the memory limit of 2 GiB before the argument list, my findings did't match yours. Thus the hard limit, of the number of parameters you can put in a string.Format method call has to be **107713904**. ``` int i = 0; long sum = 0; while (sum < int.MaxValue) { var s = sizeof(char) * ("{" + i + "}").Length; sum += s; // pseudo append ++i; } Console.WriteLine(i); Console.ReadLine(); ``` Love the discussion people!
Not as far as I know... well, the theoretical limit would be the int32 limit for the array, but you'd hit the string length limit long before that, I guess... Just don't go mad with it ;-p It may be better to write lots of small fragments to (for example) a file or response, than one huge hit. **edit** - it **looked** like there was a limit in the IL (0xf4240), but apparently this isn't quite as it appears; I can make it get quite large (2^24) before I simply run out of system memory... --- Update; it seems to me that the bounding point is the format string... those {1000001}{1000002} add up... a quick bit of math (below) shows that the maximum **useful** number of arguments we can use is 206,449,129: ``` long remaining = 2147483647;// max theoretical format arg length long count = 10; // i.e. {0}-{9} long len = 1; int total = 0; while (remaining >= 0) { for(int i = 0 ; i < count && remaining >= 0; i++) { total++; remaining -= len + 2; // allow for {} } count *= 10; len++; } Console.WriteLine(total - 1); ```
string.Format() parameters
[ "", "c#", "language-features", "" ]
I am trying to install this <https://www.php.net/manual/en/book.ssh2.php> on a Centos 5 (a fork of RHEL 5). I installed libssh2 (yum install libssh2) which is located in /usr/lib, and when I install SSH2 extension (via pecl install -f ssh2) I get this message > checking for ssh2 files in default path... not found > configure: error: The required libssh2 library was not found. You can obtain that package from <http://sourceforge.net/projects/libssh2/> > ERROR: `/tmp/pear/download/ssh2-0.11.0/configure --with-ssh2=/usr' failed If I set /usr/lib, I get the same message > ERROR: `/tmp/pear/download/ssh2-0.11.0/configure --with-ssh2=/usr/lib' failed Where is the problem?
Installing libssh2 via tar.gz from <http://sourceforge.net/projects/libssh2/> help a lot (--with-ssh2=/usr/local/include/). But : ``` yum install libssh2-devel ``` ...is a better idea.
``` $ sudo pecl channel-update pecl.php.net $ sudo apt-get install libssh2-1-dev $ sudo pecl install -a ssh2-0.12 $ echo 'extension=ssh2.so' | sudo tee /etc/php5/mods-available/ssh2.ini > /dev/null $ sudo php5enmod ssh2 ```
Install PECL SSH2 extension for PHP
[ "", "php", "ssh", "" ]
I have a sample application which has something like below. ``` <a href="javascript:{}" id="anchorlnk">Go</a> ``` which javascript function does the link call?
It does nothing, the `{}` on the link creates a new empty object that is unused, is *not* a function call... Maybe your events are binded on the page load, and someone put this just to do nothing. You could use simply href="#"
People use different techniques to do nothing :) More examples are: ``` href="javascript:;" href="javascript://" href="javascript:void();" ``` If you use ``` href="#" ``` then you probably will have an onclick event handler, make sure you return false at the end of your "onclick code", otherwise the page will be scrolled to the top which can be very unpleasent to the user.
What does this expression mean: "javascript:{}"
[ "", "javascript", "html", "" ]
I have heard about a buffer overflow and I would like to know how to cause one. Can someone show me a small buffer overflow example? New(And what they are used for?)
A buffer overflow is basically when a crafted section (or buffer) of memory is written outside of its intended bounds. If an attacker can manage to make this happen from outside of a program it can cause security problems as it could potentially allow them to manipulate arbitrary memory locations, although many modern operating systems protect against the worst cases of this. While both reading and writing outside of the intended bounds are generally considered a bad idea, the term "buffer overflow" is generally reserved for *writing* outside the bounds, as this can cause an attacker to easily modify the way your code runs. There is a good article on Wikipedia about [buffer overflows](http://en.wikipedia.org/wiki/Buffer_overflow) and the various ways they can be used for exploits. In terms of how you could program one yourself, it would be a simple matter of: ``` char a[4]; strcpy(a,"a string longer than 4 characters"); // write past end of buffer (buffer overflow) printf("%s\n",a[6]); // read past end of buffer (also not a good idea) ``` Whether that compiles and what happens when it runs would probably depend on your operating system and compiler.
Classical example of a buffer-overflow: ``` // noone will ever have the time to type more than 64 characters... char buf[64]; gets(buf); // let user put his name ``` The buffer overflow alone does most often not happen purposely. It happens most often because of a so-called "off-by-one" error. Meaning you have mis-calculated the array-size by one - maybe because you forgot to account for a terminating null character, or because some other stuff. But it can also be used for some evil stuff. Indeed, the user long knew this hole, and then inserts say 70 characters, with the last ones containing some special bytes which overwrite some stack-slot - if the user is really tricky he/she will hit the return-address slot in the stack, and overwrites it so it jumps forward into that just inserted buffer: Because what the user entered was not his name, but his shell-code that he previously compiled and dumped out. That one will then just executed. There are some problems. For example, you have to arrange not to have a "\n" in that binary code (because gets would stop reading there). For other ways that mess with dangerous string functions, the binary zero is problematic because string functions stop copying there to the buffer. People have used `xor` with two times the same value to produce a zero too, without writing a zero byte explicitly. That's the classic way of doing it. But there are some security blocks that can tell that such things happened and other stuff that make the stack non-executable. But i guess there are way better tricks than i just explained. Some assembler guy could probably now tell you long stories about that :) ### How to avoid it **Always** use functions that take a maximal-length argument too, if you are not **100%** sure that a buffer is really large enough. Don't play such games as "oh, the number will not exceed 5 characters" - it will fail some day. Remember that one rocket where scientists said that the number will not exceed some magnitude, because the rocket would never be that fast. But some day, it *was* actually faster, and what resulted was an integer overflow and the rocket crashed (it's about a bug in [Ariane 5](http://en.wikipedia.org/wiki/Ariane_5_Flight_501), one of the most expensive Computer bugs in history). For example, instead of gets use `fgets`. And instead of `sprintf` use `snprintf` where suitable and available (or just the C++ style things like istream and stuff)
What is a buffer overflow and how do I cause one?
[ "", "c++", "buffer-overflow", "fortify-source", "" ]
Lets say you have the following entities in your database: [Image http://lh6.ggpht.com/\_UpGtM3B8h1U/Sa7SqfWmgDI/AAAAAAAAAHE/epqtm7EnoFg/test.gif](http://lh6.ggpht.com/_UpGtM3B8h1U/Sa7SqfWmgDI/AAAAAAAAAHE/epqtm7EnoFg/test.gif) You want to be able to add a note to all three of the other entity tables (User, Client and Project). How would you set this up? 1. Add a tableName and a FKId to the Note table? 2. Create a separate table for each associated Note group (ie., ClientNote, UserNote) 3. Create a separate field in Note for each Foreign key (UserId, ClientId, etc) I seem to be going back and forth between option 2 and 3, although I'd be up for 1 if there were an elegant implementation. Option 2 is attractive because there are no nulls. Option 3 is attractive because a note feels like a note no matter what it is associated with. Any thoughts?
I would typically go with option 2. I don't stress about the number of tables in a database within reason. The big question is, are these notes going to be handled as a single item? For example, are you going to ever say, "Show me all notes, regardless of whether it's for a client or user or project." I can't think of any situations where that would be useful. You're going to typically say, "Show me THIS CLIENT'S notes" or "Show me THIS PROJECT'S notes." Since they are not logically one item I suggest not trying to model them physically as one item.
I think, you should definitively avoid solution 1 in this case. You loose the integrety reference, it becomes impossible to query your database without dynamic SQL and you always need 2 queries to select some notes! You should never use this way in simples cases like here. As I see it, I go with option 4 (adding a field note\_id on project, client and user). If you need multiple notes for one row, it's not a problem. You simply add an extra table (lets say note\_set) that makes the n-1 relation. client(client\_id, note\_set\_id) user(user\_id, note\_set\_id) project(project\_id, note\_set\_id) note\_set(note\_set\_id) note(note\_id, note\_set\_id, title, body) the major problem of this solution, is that given a note you cannot find the initial "entity" without making an UNION on the three tables. It doesn't seems a big problem to me but, if it is, then go with option 3. Finally, option 2 is good as well but it's not what I call "reuse". Please excuse my english.
How do you structure your entities you intend to reuse?
[ "", "sql", "database-design", "" ]
For debugging, I would like to add some counter variables to my class. But it would be nice to do it without changing the header to cause much recompiling. If Ive understood the keyword correctly, the following two snippets would be quite identical. Assuming of course that there is only one instance. ``` class FooA { public: FooA() : count(0) {} ~FooA() {} void update() { ++count; } private: int count; }; ``` vs. ``` class FooB { public: FooB() {} ~FooB() {} void update() { static int count = 0; ++count; } }; ``` In **FooA**, count can be accessed anywhere within the class, and also bloats the header, as the variable *should* be removed when not needed anymore. In **FooB**, the variable is only visible within the one function where it exists. Easy to remove later. The only drawback I can think of is the fact that FooB's count is shared among all instances of the class, but thats not a problem in my case. * Is this correct use of the keyword? I assume that once **count** is created in **FooB**, it stays created and is not re-initialized to zero every call to update. * Are there any other caveats or headsup I should be aware of? **Edit:** After being notified that this would cause problems in multithreaded environments, I clarify that my codebase is singlethreaded.
Your assumptions about static function variables are correct. If you access this from multiple threads, it may not be correct. Consider using InterlockedIncrement().
What you really want, for your long term C++ toolbox is a threadsafe, general purpose debug counters class that allows you to drop it in anywhere and use it, and be accessible from anywhere else to print it. If your code is performance sensitive, you probably want it to automatically do nothing in non-debug builds. The interface for such a class would probably look like: ``` class Counters { public: // Counters singleton request pattern. // Counters::get()["my-counter"]++; static Counters& get() { if (!_counters) _counters = new Counters(); } // Bad idea if you want to deal with multithreaded things. // If you do, either provide an Increment(int inc_by); function instead of this, // or return some sort of atomic counter instead of an int. int& operator[](const string& key) { if (__DEBUG__) { return _counter_map.operator[](key); } else { return _bogus; } } // you have to deal with exposing iteration support. private: Counters() {} // Kill copy and operator= void Counters(const Counters&); Counters& operator=(const Counters&); // Singleton member. static Counters* _counters; // Map to store the counters. std::map<string, int> _counter_map; // Bogus counter for opt builds. int _bogus; }; ``` Once you have this, you can drop it in at will wherever you want in your .cpp file by calling: ``` void Foo::update() { // Leave this in permanently, it will automatically get killed in OPT. Counters::get()["update-counter"]++; } ``` And in your main, if you have built in iteration support, you do: ``` int main(...) { ... for (Counters::const_iterator i = Counters::get().begin(); i != Countes::get().end(); ++i) { cout << i.first << ": " << i.second; } ... } ``` Creating the counters class is somewhat heavy weight, but if you are doing a bunch of cpp coding, you may find it useful to write once and then be able to just link it in as part of any lib.
Static vs. member variable
[ "", "c++", "debugging", "static", "variables", "" ]
I have two SQL queries, where the first one is: ``` select Activity, SUM(Amount) as "Total Amount 2009" from Activities, Incomes where Activities.UnitName = ? AND Incomes.ActivityId = Activities.ActivityID GROUP BY Activity ORDER BY Activity; ``` and the second one is: ``` select Activity, SUM(Amount) as "Total Amount 2008" from Activities, Incomes2008 where Activities.UnitName = ? AND Incomes2008.ActivityId = Activities.ActivityID GROUP BY Activity ORDER BY Activity; ``` (Dont mind the '?', they represent a parameter in birt). What i want to achieve is the following: I want an SQL query that returns the same as the first query, but with an additional (third) column which looks exactly like "Total Amount 2008" (from the 2nd query).
Some DBMSs support the `FROM (SELECT ...) AS alias_name` syntax. Think of your two original queries as temporary tables. You can query them like so: ``` SELECT t1.Activity, t1."Total Amount 2009", t2."Total Amount 2008" FROM (query1) as t1, (query2) as t2 WHERE t1.Activity = t2.Activity ```
``` SELECT Activity, arat.Amount "Total Amount 2008", abull.Amount AS "Total Amount 2009" FROM Activities a LEFT OUTER JOIN ( SELECT ActivityId, SUM(Amount) AS Amount FROM Incomes ibull GROUP BY ibull.ActivityId ) abull ON abull.ActivityId = a.ActivityID LEFT OUTER JOIN ( SELECT ActivityId, SUM(Amount) AS Amount FROM Incomes2008 irat GROUP BY irat.ActivityId ) arat ON arat.ActivityId = a.ActivityID WHERE a.UnitName = ? ORDER BY Activity ```
Join two sql queries
[ "", "sql", "database", "join", "" ]
``` byte x = -1; for(int i = 0; i < 8; i++) { x = (byte) (x >>> 1); System.out.println("X: " + x); } ``` As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia). Also, from the java docs: "The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. " Which means that >>> would shift a 0 to the left most bit every time. So I expect this code to be iteration: bit representation of x 0: 11111111 1: 01111111 2: 00111111 3: 00011111 ...so on However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position. So I then try >>, and same result. What's going on? I would expect my output to be: X: -1, x: 127, x: 63, etc.
Whoever thought that bytes should be signed when Java was invented should be taken out and beaten with a wet stick of celery until they cry :-) You can do what you want by casting up to an int and ensuring you never shift a 1 into the top bit, something like this: ``` byte x = -1; int x2 = ((int)x) & 0xff; for(int i = 0; i < 8; i++) { x2 = (x2 >>> 1); System.out.println("X: " + x2); } ``` Your particular problem is because >>> is casting up to an int to do the shift, then you're casting it back to a byte, as shown here: ``` byte x = -1; int x2 = ((int)x) & 0xff; int x3; int x4 = x2; for(int i = 0; i < 8; i++) { x2 = (x2 >>> 1); System.out.println("X2: " + x2); x3 = (x >>> 1); x = (byte)x3; x4 = (x4 >>> 1); System.out.println("X: " + x3 + " " + x + " " + x4); } ``` Which outputs: ``` X2: 127 X: 2147483647 -1 127 X2: 63 X: 2147483647 -1 63 X2: 31 X: 2147483647 -1 31 X2: 15 X: 2147483647 -1 15 X2: 7 X: 2147483647 -1 7 X2: 3 X: 2147483647 -1 3 X2: 1 X: 2147483647 -1 1 X2: 0 X: 2147483647 -1 0 ``` You can clearly see that x and x3 don't work (even though x3 shifts correctly, casting it back to byte in x sets it to -1 again). x4 works perfectly.
Remember that: * operands of **bitwise operations** are always **promoted to at least an int**! * casts always involve **sign extension**. So when you do (x >>> n), even though you defined x as a byte, for the purposes of the shift, it will be first converted to an int. If the byte being converted is negative, then all of the "extra bits" (so, the leftmost 24 bits of the resulting int) added to make it up to an int will be set to 1. Or put another way, if the original byte was -1, the thing you're actually shifting is -1 as an *int*, i.e. 32-bit number with all 32 bits set to 1. Shifting this right by 1-8 places will still result in the bottom 8 bits all set to 1, hence when you cast back to a byte, you end up with a byte with all 8 bits set to 1, or in other words, a byte value of -1.
java bit manipulation
[ "", "java", "bit-manipulation", "byte", "" ]
I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate. Would you explain to me the differences and when to use which? What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it. When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.
From the technical standpoint, other answers have addressed the differences. From a semantics perspective, events are actions raised by an object when certain conditions are met. For example, my Stock class has a property called Limit, and it raises an event when the stock prices reaches the Limit. This notification is done via an event. Whether anyone actually cares about this event and subscribes to it is beyond the concern of the owner class. A delegate is a more generic term to describe a construct similar to a pointer in C/C++ terms. All delegates in .Net are multicast delegates. From a semantics perspective, they are generally used as a kind of input. In particular, they are a perfect way to implement the [Strategy Pattern](http://en.wikipedia.org/wiki/Strategy_pattern). For example, if I want to sort a List of objects, I can provide a Comparator strategy to the method to tell the implementation how to compare two objects. I have used the two methods in production code. Tons of my data objects notify when certain properties are met. Most basic example, whenever a property changes, a PropertyChanged event is raised (see INotifyPropertyChanged interface). I have used delegates in code to provide different strategies of turning certain objects into string. This particular example was a glorified ToString() list of implementations for a particular object type to display it to users.
The keyword `event` is a scope modifier for multicast delegates. Practical differences between this and just declaring a multicast delegate are as follows: * You can use `event` in an interface. * Invocation access to the multicast delegate is limited to the declaring class. The behaviour is as though the delegate were private for invocation. For the purposes of assignment, access is as specified by an explicit access modifier (eg `public event`). As a matter of interest, you can apply `+` and `-` to multicast delegates, and this is the basis of the `+=` and `-=` syntax for the combination assignment of delegates to events. These three snippets are equivalent: ``` B = new EventHandler(this.MethodB); C = new EventHandler(this.MethodC); A = B + C; ``` Sample two, illustrating both direct assignment and combination assignment. ``` B = new EventHandler(this.MethodB); C = new EventHandler(this.MethodC); A = B; A += C; ``` Sample three: more familiar syntax. You are probably acquainted with the assignment of null to remove all handlers. ``` B = new EventHandler(this.MethodB); C = new EventHandler(this.MethodC); A = null; A += B; A += C; ``` Like properties, events have a full syntax that no-one ever uses. This: ``` class myExample { internal EventHandler eh; public event EventHandler OnSubmit { add { eh = Delegate.Combine(eh, value) as EventHandler; } remove { eh = Delegate.Remove(eh, value) as EventHandler; } } ... } ``` ...does *exactly* the same as this: ``` class myExample { public event EventHandler OnSubmit; } ``` The add and remove methods are more conspicuous in the rather stilted syntax that VB.NET uses (no operator overloads).
Difference between events and delegates and its respective applications
[ "", "c#", "events", "delegates", "" ]
How do I hide the navigation bar for popups in javascript?
``` window.open("http://www.google.com", "mywindow", "location=0,toolbar=0"); ``` See [this site](http://www.javascript-coder.com/window-popup/javascript-window-open.phtml) for more attributes.
The above suggestion should work under most circumstances. Beware of using pop-up's at all though; they may be inhibited by the browser, or the visitor may have set their browser to open new windows in tabs instead, causing unexpected results (especially if their tabs are opening in the background). Depending on your purpose, you may want to consider using [jQuery's dialog()](http://docs.jquery.com/UI/Dialog) instead.
How do I hide the navigation bar for popups in javascript?
[ "", "javascript", "" ]
I'm getting this error `The type or namespace name 'DataVisualization' does not exist in the namespace 'System.Windows.Forms' (are you missing an assembly reference?)` Here is my `using` section of the class: ``` using System; using System.Collections; using System.Collections.Generic; using System.Windows.Forms.DataVisualization.Charting; using System.Windows.Forms.DataVisualization.Charting.Borders3D; using System.Windows.Forms.DataVisualization.Charting.ChartTypes; using System.Windows.Forms.DataVisualization.Charting.Data; using System.Windows.Forms.DataVisualization.Charting.Formulas; using System.Windows.Forms.DataVisualization.Charting.Utilities; namespace myNamespace { public class myClass { // Usual class stuff } } ``` The thing is that I am using the same DataVisualization includes in another class. The only thing that I can think that is different is that the classes that are giving this missing namespace error are Solution Items rather than specific to a project. The projects reference them by link. Anyone have thoughts on what the problem is? I've installed the chart component, .Net 3.5 SP1, and the Chart Add-in for Visual Studio 2008. UPDATE: I moved the items from Solution Items to be regular members of my project and I'm still seeing the same behavior. UPDATE 2: Removing the items from the Solution Items and placing them under my project worked. Another project was still referencing the files which is why I didn't think it worked previously. I'm still curious, though, why I couldn't use the namespace when the classes were Solution Items but moving them underneath a project (with no modifications, mind you) instantly made them recognizable. :\
Solution items aren't used by compiled assemblies. <http://msdn.microsoft.com/en-us/library/1ee8zw5t.aspx> "They can be referenced by projects, but are never included in solution or project builds" As far as I know, solution folders/items are really just meant for organizing things.
You are very likely missing a reference to the DataVisualization DLL. Note that although they share the namespace of System.Windows.Forms.dll, they aren't actually contained within it.
System.Windows.Forms.DataVisualization Namespace Fine in One Class but Not in Another
[ "", "c#", ".net", "winforms", "namespaces", "" ]
This is not the first time I'm using this method to send a POST request, and I never had any problems: ``` public static Stream SendPostRequest(Uri uri, byte[] postData) { var request = WebRequest.Create(uri); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postData, 0, postData.Length); requestStream.Close(); return request.GetResponse().GetResponseStream(); } ``` On request.GetRequestStream() I'm getting a System.Net.WebException: The underlying connection was closed: An unexpected error occured on a send. Even more interesting, it works perfectly well on some machines, but doesn't work on my machine (Windows 7 Beta) and production server (Windows Server 2008). More information: Works - Windows Xp - .NET 2.0 Works - Windows Xp - .NET 3.5 Works - Windows Server 2003 - .NET 3.0 Doesn't work - Windows Vista - .NET 3.5 Doesn't work - Windows Server 2008 - .NET 3.5 Doesn't work - Windows 7 Beta - .NET 3.5 SP1 Tried: * Bunch of stuff from [here](http://blogs.msdn.com/engelsr/articles/497902.aspx), nothing helped. * Using [WebClient](https://stackoverflow.com/questions/625513/sending-a-post-request-system-net-webexception/625558#625558), nothing changed. * Tweaking these [options](https://stackoverflow.com/questions/625513/sending-a-post-request-system-net-webexception/626030#626030), but didn't notice any notable difference. * Tried [WireShark](http://www.wireshark.org/). A very good tool. **[Solved. Kinda]** I forgot to mention, but Uri was https... I tried http and it worked. Can't believe, I didn't try that sooner... Still, I would appreciate, if someone would shine a light on this whole situation.
My first plan of attack would be to use [WireShark](http://wireshark.org) to see what's happening at the network level in each case. See what each machine is sending. Also, you've noted differences between operating systems, but do they all have the exact same version of .NET (down to SP) installed?
Do GETs work? Perhaps it is a proxy config issue (`proxycfg` etc). Also - to simplify things (reduce the number of unknowns), consider using `WebClient` to do the post: ``` using (WebClient client = new WebClient()) { client.Headers.Add("content-type","application/x-www-form-urlencoded"); client.UploadData(address, data); // or more simply client.UploadValues(address, nameValuePairs); } ```
Sending a POST request: System.Net.WebException
[ "", "c#", ".net", "post", "https", "httpwebrequest", "" ]
I recently had my first encounter with PHP (5) through a Drupal application for a client. There was certainly nothing difficult about the experience (documentation is good for instance), but I never had a moment where I thought, "that's really clever!", or "wow this is fun to use!" Moreover, I couldn't accurately predict how functions were going to be named, or ascertain a guiding principle to follow. This is in contrast to Ruby, for instance, where everything is an object, methods are predictable and pseudo-polymorphic, and blocks are a joy to use (to name a few examples). Other language highlights for contrast: Python's list comprehensions change the way you think about iteration, C brings you back to the hardware with it's pointers and bit operations, javascript is surprisingly wonderful with its nameless functions and advanced suppport for hashes, and even SQL in its crustiness forces you to appreciate your data and think about it relationally. So with that in mind, what are the highlights of php? And what is the overall design philosophy of the language? I know php doesn't enjoy a great reputation overall, but I've always heard that that was a perception problem due to the large amount of non-professional developers banging out copy and paste code. EDIT: Alright, so the consensus is that PHP is the monkey-wrench of web programmers. I can accept that. I was just looking for a insight, but I guess I already had it. I certainly do appreciate mod\_php/libphp for instance. And I was able to get my application out the door in two weeks with no prior php experience, so I guess that also speaks for itself. Thanks for the posts.
From the [php web site](http://us.php.net/manual/en/faq.general.php#faq.general.what): > PHP is an HTML-embedded scripting > language. Much of its syntax is > borrowed from C, Java and Perl with a > couple of unique PHP-specific features > thrown in. The goal of the language is > to allow web developers to write > dynamically generated pages quickly. In other words, there isn't really a design philosophy: It's a mix and mash of ideas to get a job done (obviously inherited from Perl, hehe).
The design philosophy of PHP: > **D'oh!**
What is the overall design philosophy of php?
[ "", "php", "language-design", "language-features", "language-comparisons", "" ]
I have the following code... ``` if (Price_Foreign != Double.NaN) { output.Append(spacer); output.Append(String.Format("{0,-10:C} USD",Price_Foreign)); } ``` Which outputs: ``` NaN USD ``` What gives? I'm using Double.NaN to indicate that the value doesn't exist, and shouldn't be output.
Perhaps you are looking for the `IsNaN` static function? Try something like this: ``` if (!Double.IsNaN(Price_Foreign)) { output.Append(spacer); output.Append(String.Format("{0,-10:C} USD",Price_Foreign)); } ```
The [IEEE 754 floating point standard](http://en.wikipedia.org/wiki/IEEE_754) states that comparing NaN with NaN will **always** return false. If you must do this, use `Double.IsNaN()`. But, this isn't the best way to do what you're trying to do. Doubles are NOT precise, and you're using them to represent prices here. I'm betting that at some point, you're going to want to compare prices for equality, too. That's not going to work, because [you can't rely on floating point equality](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/). You should really look into using some integer type for these values (that supports equality comparison) rather than trying to use doubles. Doubles are for scientific problems; not for finance.
Equality with Double.NaN
[ "", "c#", "equality", "nan", "" ]
How resizing and fitting different images in a fixed space as done in <http://www.ted.com/talks/browse> and search results jinni.com. Any leads how this can be done, like with jQuery or with php support something. Thanks
The way it's done on the TED website, they use Flash and only one aspect ratio for all the images, which makes the algorithm fairly trivial. For an even more stylish look (and for serious geek points), you could pick a couple of aspect ratios (one square, one portrait, one or two horizontal) and custom-build an algorithm to solve a subset of the 2D [bin packing problem](http://en.wikipedia.org/wiki/Bin_packing_problem) efficiently. Better yet, you could use some nifty algebra to automatically decide which sizes would fit into a rectangle of a specified width and have the algorithm do all the resizing for you automatically. That may sound like NP-hard black magic, but [A List Apart](http://www.alistapart.com/) actually had an excellent article about it some time ago. It even has a simple explanation of the math involved and PHP code you can download and modify to your needs: [Automatic Magazine Layout](http://www.alistapart.com/articles/magazinelayout) -- [Example 1](http://www.alistapart.com/d/magazinelayouts/example1.htm)
The correct term for this display is a [Treemap](http://en.wikipedia.org/wiki/Treemapping). It may help with your algorithm search. There are several solutions available, including [JavaScript](http://blog.thejit.org/javascript-information-visualization-toolkit-jit/) and [RoR](http://code.qnot.org/svn/projects/acts_as_treemap/). Even if those solutions don't work for you, the proper term should help you get on track!
Fitting different images as done in Ted.com
[ "", "javascript", "jquery", "web-applications", "" ]
I was reading about flag enums and bitwise operators, and came across this code: ``` enum file{ read = 1, write = 2, readandwrite = read | write } ``` I read somewhere about why there is a inclusive or statement and how there can't be an &, but can't find the article. Can someone please refresh my memory and explain the reasoning? Also, how can I say and/or? Eg. if dropdown1="hello" and/or dropdown2="hello".... Thanks
**First Question:** A `|` does a bitwise or; a bit will be set in the result if it is set in the first value or the second value. (You use it on `enums` to create values that are combinations of other values) If you were to use a bitwise and, it wouldn't make very much sense. It gets used as follows: ``` [Flags] enum FileAccess{ None = 0, // 00000000 Nothing is set Read = 1, // 00000001 The read bit (bit 0) is set Write = 2, // 00000010 The write bit (bit 1) is set Execute = 4, // 00000100 The exec bit (bit 2) is set // ... ReadWrite = Read | Write // 00000011 Both read and write (bits 0 and 1) are set // badValue = Read & Write // 00000000 Nothing is set, doesn't make sense ReadExecute = Read | Execute // 00000101 Both read and exec (bits 0 and 2) are set } // Note that the non-combined values are powers of two, \ // meaning each sets only a single bit // ... // Test to see if access includes Read privileges: if((access & FileAccess.Read) == FileAccess.Read) ``` Essentially, you can test if certain bits in an `enum` are set; in this case we are testing to see if the bits corresponding to a `Read` are set. Values `Read` and `ReadWrite` would both pass this test (the both have bit zero set); `Write` would not (it does not have bit zero set). ``` // if access is FileAccess.Read access & FileAccess.Read == FileAccess.Read // 00000001 & 00000001 => 00000001 // if access is FileAccess.ReadWrite access & FileAccess.Read == FileAccess.Read // 00000011 & 00000001 => 00000001 // uf access is FileAccess.Write access & FileAccess.Read != FileAccess.Read // 00000010 & 00000001 => 00000000 ``` **Second Question:** I think when you say "and/or", you mean "one, the other or both". This is exactly what the `||` (or operator) does. To say "one or the other, but not both", you'd use `^` ( the exclusive or opertor). Truth tables (true==1, false==0): ``` A B | A || B ------|------- OR 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 1 (result is true if any are true) A B | A ^ B ------|------- XOR 0 0 | 0 0 1 | 1 1 0 | 1 1 1 | 0 (if both are true, result is false) ```
The above or is a bitwise or, not a logical or. 1 | 2 is equivalent to 3 (while 1 & 2 = 0). See <http://en.wikipedia.org/wiki/Bitwise_operation> for a better explanation about bitwise operations.
What does the bitwise or | operator do?
[ "", "c#", ".net", "enums", "bit-manipulation", "" ]
When using Linq2Nibernate is better to make you Repository return a IQueryable? My understanding is that if you use Linq to Nibernate the the query will not "fire" until you call .First() or Single() ect ect. So would it not be best to return IQueryable from all you Interfaces so you can build up\manipulate the expression tree before it fires? My Repositories are called by a services and inherits from IServicie. **EDIT:** First I really appreciate all the answers. But I wan to add a little to the question. I am for this design. I don't fully understand the reservations around testing. As long as the process is tested at every point IE every filter point then I don't really see much of a difference. addition: Is there any point to Using Linq2Nibernate if your repository doesn't return IQuerrable?
Personally, I think not. The problem with exposing composable queries from your repository is that you can no longer fully unit test them - their behaviour (and success) is now at the mercy of the caller. For example, they might do `.Where(x=>SomeUnmappedMethod(x))` (with no translation). I added more on this [here](http://marcgravell.blogspot.com/2009/02/pragmatic-linq.html). If you have fixed methods that return (for example) `IList<T>` or `T[]`, then you can be sure that if it works in the unit test, it should work for real (barring any configuration errors). It also means that you can profile the DAL in isolation and have reasonable confidence what SQL (etc) is going to be executed. You can't profile/optimise a DAL that changes based on the caller. (based on my LINQ-to-SQL usage; not LINQ-to-NHibernate specifically)
It depends on what's consuming your "Repository" (quotes because of ambiguity). I would say if something like your last layer (UI) is consuming your repository classes to **NOT** return an IQueryable. However if you have another layer between your UI layer and your Data Access layer I'd say yes, return IQueryable and have your middle layer handle the execution of the query. **EDIT** As for testing your Data Access Layer (DAL)/Repository I would say for the most part unless you have actual logic (if statements etc) there should be little to no testing. At that point you're testing the framework. My suggestion would to be put another layer between your accessing layer (UI) and the DAL like a BLL or something that handles the execution of the IQueryable queries. That way your repository can return queries and your BLL can handle executing them and maybe doing some logic which can then be tested.
interface design with Linq2Nibernate and IQueryable
[ "", "c#", ".net", "linq", "iqueryable", "linq-to-nhibernate", "" ]
Consider the following two snippets, with braces: ``` switch (var) { case FOO: { x = x + 1; break; } case BAR: { y = y + 1; break; } } ``` Without braces: ``` switch (var) { case FOO: x = x + 1; break; case BAR: y = y + 1; break; } ``` I know that, in the snippet with braces, a new scope is created by enclosing each case in braces. However, if each case does not need the new scope (i.e. no variable names are being reused), is there any sort of performance penalty for using the braces with a case?
> is there any sort of performance penalty for using the braces with a case? None. The curly braces are there to help the compiler figure out the scope of a variable, condition, function declaration, etc. It doesn't affect the runtime performance once the code is compiled into an executable.
No performance penalty from an execution point of view. Slight performance penalty from a compiling point of view as there is more to parse, but if anyone were actually that concerned about it they would have to write their code all on one line :-) And now for the opinion part of our post... I always put in the { and } because there is a penalty for maintainability in that you will likely have to put them in at a later date, and it can be a pain putting them in later... but that is 103% personal preference.
Java switch cases: with or without braces?
[ "", "java", "performance", "switch-statement", "" ]
In C# how do I memoize a function with two arguments? Do I have to curry before memoization? [Wes Dyer wrote the Memoization code](http://blogs.msdn.com/wesdyer/archive/2007/01/26/function-memoization.aspx) I typically use, but now I need two arguments
You just make an overloaded version of the Memoize method that has three generic types and takes a function with two parameters, and the two arguments. It still returns a parameterless function: ``` public static Func<R> Memoize<A1,A2,R>(this Func<A1,A2,R> f, A1 a1, A2 a2) { R value = default(R); bool hasValue = false; return () => { if (!hasValue) { hasValue = true; value = f(a1,a2); } return value; }; } ``` Edit: Alternatively, you need to make a custom IEqualityComparer for a KeyValuePair that contains the two arguments, for the Memoize method to be able to return a function with two parameters: ``` public static Func<A1,A2,R> Memoize<A1,A2,R>(this Func<A1,A2,R> f, IEqualityComparer<KeyValuePair<A1,A2>> comparer) { var map = new Dictionary<KeyValuePair<A1,A2>,R>(comparer); return (a1,a2) => { R value; KeyValuePair<A1,A2> key = new KeyValuePair<A1,A2>(a1,a2); if (map.TryGetValue(key, out value)) { return value; } value = f(a1,a2); map.Add(key, value); return value; }; } ```
Wes has another post where he gives [a two (or more) argument version of Memoize](http://blogs.msdn.com/wesdyer/archive/2007/02/11/baby-names-nameless-keys-and-mumbling.aspx "Baby Names, Nameless Keys, and Mumbling"). It does not require a custom comparer.
Two argument Memoization
[ "", "c#", ".net", "functional-programming", "memoization", "" ]
I thought it was odd that C# let me call sort on my class and not specify a way to sort them nor write a compare overload. When i ran this code this error popped up ``` List<MyClass> myClassArray= new List<MyClass>(); //myClassArray.add(...); myClassArray.Sort(); An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Failed to compare two elements in the array. ``` Why does C# let me compile this code when it doesnt know how to sort this! -edit- Codex ask why it does this. I wrote a theory on why it does it in my comments. Here some example code. ``` class A : IComparable<A> { public int CompareTo(A a) { return 0; } } class C //: IComparable<A> { public int CompareTo(A a) { return 0; } } static void test() { A a = new A(); bool b; C c = new C(); object o = a; IComparable<A> ia = (IComparable<A>)o; b = ia == ia; o = c; IComparable<A> ic = (IComparable<A>)o; b = ic == ic; //uncomment this to get a compile time error //IComparable<A> ic2 = c; return; } ``` If you uncomment the line before return, you'll get a compile time error. When you uncomment IComparable in class c, it will compile and work.
There's no constraint on the generic parameter of List<T> requiring it to implement IComparable<T>. If there were, it would (sort of) guarantee that elements could be sorted, but you wouldn't be able to use List<T> to hold anything that didn't implement IComparable. And since you probably won't be sorting every list you create, this is the right decision.
Sort should be checking to see if your object implements [IComparable](http://msdn.microsoft.com/en-us/library/system.icomparable.aspx). This is a run time check, and since you presumably don't implement it the default comparer doesn't know what to do with your objects, so it throws the exception. It lets it compile because this isn't a language feature, its a framework feature.
Why does C# let me compile sort code when it doesnt know how to sort
[ "", "c#", "sorting", "" ]
I'm working on some JavaScript that requires a tag that can get focus. I'd like to be able to use a `<div />` tag, however `<div />` tags can't get focus. It looks like the only elements that can gain focus are `<input />` tags and `<a />` tags. Is there any other way to allow an element to gain focus that isn't an `<input />` or `<a />` tag? I can't use `<a />` or `<input />` tags because I need to be able to place content inside of the tag so neither of those tags will work, unless there's a way to allow nested `<a />` tags, although I doubt it since that [goes against the standard](http://www.w3.org/TR/html4/struct/links.html#h-12.2.2). I'm trying to figure out a way to allow a `<div />` tag (or any other container element) to get focus.
What do you mean by "can get focus"? Any DOM element can be setup to receive a multitude of javascript events including `click` events. Or do you mean "can be tabbed to with the keyboard"? If so, and if you cannot use an `a` tag as your container, then try the [`tabindex` property](http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex/) on your elements. I'm not sure how cross-browser it is, but at least try it before writing a tabbed ui in javascript yourself.
Bookmarks are the way to go. Begin your content with ``` <a href="#anchor"> ```
Focus on a non-input/anchor element?
[ "", "javascript", "html", "dom", "" ]
How to remove tkinter icon from title bar in it's window
### On Windows **Step One:** Create a transparent icon using either an icon editor, or a site like [rw-designer](http://www.rw-designer.com/online_icon_maker.php). Save it as `transparent.ico`. **Step Two:** ``` from tkinter import * tk = Tk() tk.iconbitmap(default='transparent.ico') lab = Label(tk, text='Window with transparent icon.') lab.pack() tk.mainloop() ``` ### On Unix Something similar, but using an `xbm` icon.
Similar to the accepted answer (with the con of being uglier): ``` import tkinter import tempfile ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00' b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00' b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64 _, ICON_PATH = tempfile.mkstemp() with open(ICON_PATH, 'wb') as icon_file: icon_file.write(ICON) tk = tkinter.Tk() tk.iconbitmap(default=ICON_PATH) label = tkinter.Label(tk, text="Window with transparent icon.") label.pack() tk.mainloop() ``` It just creates the file on the fly instead, so you don't have to carry an extra file around. Using the same method, you could also do an '.xbm' icon for Unix. Edit: The `ICON` can be shortened even further thanks to [@Magnus Hoff](https://stackoverflow.com/a/29509705/1546993): ``` import base64, zlib ICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy' 'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc=')) ```
Removing the TK icon on a Tkinter window
[ "", "python", "python-3.x", "tkinter", "tk-toolkit", "" ]
``` function has_thumbnail_image(&$post) { $content = $post->post_content; return preg_match('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results); } ``` I need a function that goes through a block of dynamically returned text and puts all of the images contained within into an array (or more specifically the image source of each image). The function above only gives me the first image and I cannot work out how to make this loop keep happening until all of the images are in the array. Any help on this would be much appreciated. Thanks
You may want to investigate [`preg_match_all`](http://uk.php.net/preg_match_all). If I recall correctly, `preg_match` only searches for the first match and then stops.
You are very close! You just need `preg_match_all` instead of `preg_match`.
How to put all the images in a block of text into an array, PHP?
[ "", "php", "wordpress", "" ]
I am trying to return Xml value from SQL Server 2005 using For Xml. Is there any limit in the size of xml returned from SQL Server? I will be using ExecuteXmlReader to get the value in my C# code. Also, is there any limit on the data that can hold in an XmlReader? Any thoughts...
There is no *practical* limit, but you are normally returning the equivalent of nvarchar(MAX), so you're likely to run into a ~2 billion character limit (and probably much less then that because of limited free address space). However there are no small limits, like the 32KB SQL statement limit, that you need to worry about.
Technically there is a 1 Gig limit as the XML datatype is based off of the NVARCHAR(MAX) data type. But if you have a 1 Gig XML document you need to look at making it smaller.
Is there any size limit for the values returned from a Stored Procedure in SQL 2005?
[ "", "c#", "sql-server", "sql-server-2005", "" ]
I need to manipulate data in fixed array involving mid insertion. Rather than using memcpy,etc. I want to use vector. I have problem when I want to copy the vector elements back to the c-style array. Here's the code: ``` void tryvector() { using namespace std; const int MAX_SIZE=16; BYTE myarr[MAX_SIZE]={0xb0,0x45,0x47,0xba,0x11,0x12, 0x4e}; vector<BYTE> myvec (myarr, myarr+MAX_SIZE); vector<BYTE>::iterator it; printf("myarr pre :"); for(int i=0;i<MAX_SIZE;++i){ printf("%02x ", myarr[i]) ; } printf("\nmyvec pre :") for(it=myvec.begin(); it<myvec.end();++it){ cout<<hex<<static_cast<int>(*it)<<" "; } it = myvec.begin()+ 3; myvec.insert(it,0x5f); printf("\nmyvec post:"); for(it=myvec.begin(); it<myvec.end();++it){ cout<<hex<<static_cast<int>(*it)<<" "; } copy(myvec.begin(), myvec.end(), myarr); //??? printf("\nmyarr post:"); for(int i=0;i<MAX_SIZE;++i){ printf("%02x ", myarr[i]) ; } } ``` I'm using vs 2005. Here's the warning: ``` warning C4996: 'std::_Copy_opt' was declared deprecated 1> c:\program files\microsoft visual studio 8\vc\include\xutility(2270) : see declaration of 'std::_Copy_opt' 1> Message: 'You have used a std:: construct that is not safe. See documentation on how to use the Safe Standard C++ Library' 1> c:\documents and settings\mhd\my documents\tesvector.cpp(50) : see reference to function template instantiation '_OutIt std::copy<std::_Vector_iterator<_Ty,_Alloc>,BYTE*>(_InIt,_InIt,_OutIt)' being compiled 1> with 1> [ 1> _OutIt=BYTE *, 1> _Ty=BYTE, 1> _Alloc=std::allocator<BYTE>, 1> _InIt=std::_Vector_iterator<BYTE,std::allocator<BYTE>> 1> ] ``` When I run it , I got the following run-time error: ``` Run-Time Check Failure #2 - Stack around the variable 'myarr' was corrupted. ``` Please note that I use vector instead list or deque because the 'middle insertion' like the code above is juat a particular problem. It will happen less than 'inserting at the end' and 'random access of element'. Any solution ? Any answer that resembles:"You use c++, drop the c style array implementation. Use only vector for all array implementation" is not really helpful. Thanks.
The problem is that you're adding things to the vector so it ends up with more elements than were in the `myarr` array that you initialized it with. If you want to copy the vector back into the array, you'll need to size it down: ``` myvec.resize( MAX_SIZE); ``` Or you could limit the number of elements you copy back: ``` copy( myvec.begin(), myvec.begin()+MAX_SIZE, myarr); ``` If you want the `myarr` array to contain all the elements, then it needs to be larger than `MAX_SIZE`, and you've found out why people suggest to use `vector` rather than raw arrays (`vector`s know how to grow, arrays do not). Note that while you don't want 'Any answer that resembles:"You use c++, drop the c style array implementation. Use only vector for all array implementation"', you can often get away with using a `vector` and passing `&myvec[0]` to routines that expect a raw array. `vector` is required to store its elements contiguously just like a raw array for just this reason. Since you're getting the 'unsafe operation' warning, you're using Microsoft's compiler. To fix the problem safely, you're supposed to use the `checked_copy` algorithm instead of `copy`. As [Evgeny Lazin indicates](https://stackoverflow.com/questions/633549/how-to-copy-the-contents-of-stdvector-to-c-style-static-array-safely/633575#633575), you can create a checked iterator for your array to pass to the `checked_copy` algorithm. Other options to make the copy safe that do not require Microsoft extensions would be to wrap the array in a class (possibly templated) that keeps track of the array size and provides methods to copy data into the array in a safe manner. Something like [STLSoft's `array_proxy` template](http://www.stlsoft.org/doc-1.9/classstlsoft_1_1array__proxy.html) or [Boost's `boost::array`](http://www.boost.org/doc/libs/1_38_0/doc/html/array.html) might help.
In general, I guess you could do something like this: ``` void *myarr; if((myarr = malloc(myvec.size() * sizeof myvec[0])) != NULL) { memcpy(myarr, &myvec[0], myvec.size() * sizeof myvec[0]); /* Do stuff with the C-style array for a while . . . */ free(myarr); /* Don't forget handing back the memory when done. */ } ``` This allocates a new C-style array to hold the vector's elements, and copies the data in place. This way the there is no need to match the sizes statically. Of course, this is general so it just gives you a `void *` to access your C array with, so you need to either cast or just change the type to the actual type (`BYTE` in this case).
How to copy the contents of std::vector to c-style static array,safely?
[ "", "c++", "arrays", "vector", "" ]
Are there any advantages of using SQL Passthrough facility along with SAS?
Although this question is overly broad, I can provide an overly broad answer. The pass-through SQL in SAS allows you to communicate directly with a database. This becomes very advantageous when you are using database specific functions. An example would be Oracle's stats functions. You do not have to worry about how SAS will handle your coding or translate your SQL. Additionally, it has also been a benefit to us that Pass-through SQL requires very little processing on the SAS side. If you have an extremely busy SAS box, you can opt to send the processing logic directly to the database. This is possible without using Pass-through SQL, but you have a higher degree of control when utilizing it. This is by no means an exhaustive list of benefits, simply a few high level perks to using pass-through SQL. If you have a more concrete use case, we can discuss the specific differences in coding techniques.
PROC SQL will try and pass as much of the logic as it can to the database, but there are various times that it cannot. Using SAS functions that do not have equivalent in the database (or in the SAS/ACCESS engine for the database), will prevent passing the whole query to the database. When the query is not fully passed to the database, then the data is pulled into SAS and processed there. The more complicated your SQL is the more likely it will end up being processed in SAS. Here is a case that makes a larger difference than you might realize. ``` libname db <database> path=dbserver user=... password=...; proc sql; create table db.new as select * from db.largedata where flag=1; quit; ``` This will actually (at least thru SAS 9.1.3) pull all the data that matches flag=1 down to SAS and then load it back into the database. It this is millions of rows it really slows down. You would find explicit pass through much faster in this case. ``` proc sql; connect dbase (server=dbserver user=... password=...); execute (create table db.new as select * from db.largedata where flag=1) as dbase; disconnect dbase; quit; ``` I recently did an example using Oracle and a table with about 250,000 rows. The first way took 20 seconds and the second way to 2 seconds.
SQL Passthrough in SAS
[ "", "sql", "sas", "proc-sql", "" ]
I have a table which contains a book and then multiple prices about the book (this is a highly simplified sample): ``` ID BOOK PRICE 1 BOOK1 10 2 BOOK1 15 3 BOOK1 12 4 BOOK2 8 5 BOOK2 2 ``` I am easily calculating the average, but there must be a nice way to calculate the median? Current SQL: ``` SELECT DISTINCTROW Books.BOOK, Avg(Books.PRICE) AS [Avg Of PRICE] FROM Books GROUP BY Books.BOOK; ``` Results: ``` BOOK Avg Of PRICE BOOK1 12.3333333333333 BOOK2 5 ```
There is no Median in Jet SQL, unless it has been added for 2007, but here is an idea of how to get one. You will need ... Some SQL ... ``` SELECT Statistics.Month, Sum(([SentTo])) AS [Sum Sent], fMedian("Statistics","Month",[Month],"SentTo") AS [Median Sent] FROM Statistics GROUP BY Statistics.Month; ``` And a User Defined Function (UDF). ``` Function fMedian(SQLOrTable, GroupFieldName, GroupFieldValue, MedianFieldName) Dim rs As DAO.Recordset Set db = CurrentDb Set rs1 = db.OpenRecordset(SQLOrTable, dbOpenDynaset) If IsDate(GroupFieldValue) Then GroupFieldValue = "#" & GroupFieldValue & "#" ElseIf Not IsNumeric(GroupFieldValue) Then GroupFieldValue = "'" & Replace(GroupFieldValue, "'", "''") & "'" End If rs1.Filter = GroupFieldName & "=" & GroupFieldValue rs1.Sort = MedianFieldName Set rs = rs1.OpenRecordset() rs.Move (rs.RecordCount / 2) If rs.RecordCount Mod 2 = 0 Then varMedian1 = rs.Fields(MedianFieldName) rs.MoveNext fMedian = (varMedian1 + rs.Fields(MedianFieldName)) / 2 Else fMedian = rs.Fields(MedianFieldName) End If End Function ``` From: [LessThanDot Wiki](http://wiki.lessthandot.com/index.php/Aggregate_Median_(UDF))
Median can be be calculated in MS Access using just regular queries and without VBA. Median is the 50th percentile. So, create select queries normally; then go into SQL view and include "Top 50 Percent" after select keyword. Sort ascending for bottom 50 percent; sort descending for top 50 percent. Then find maximum of bottom percent result set and minimum of top percent result set. The average of these two is the median. When using "Top 50 Percent", make sure criteria in the query is specific for that result set from which median will be calculated.
Best Way To Calculate A Median In Access 2007 When Using Group By
[ "", "sql", "ms-access", "ms-access-2007", "median", "" ]
What would be the best practice for the following scenario: There´s a grid that will be filled and must be changed according to each row. For instance, there´s a grid filled with products, then according to each product one of the columns will be dynamically populated. Is it better to return from the service all the productdetail table and query it on the client side or have a method on the service that will return only the data needed? The latter would mean that if there are n number of products on the grid, there will be n requests to that service method. My dilemma is that for some of the users the table will be relatively small and sending it to the client might not be a big deal, but other users do have a considerable amount of rows that would be returned (more than 15k). Thanks for any insight you may bring.
I'd suggest creating some sort of ViewModel on the server to tailor the data for the client. This is similar to your second option; however, it's not done on row by row. It's a batch operation on the server side which preps the columns so the view doesn't need any special logic. I feel manipulating data on the client side can be tricky because there's so many variables- browser, os, computing power. You control the server, so leverage what you control as much as possible. Good luck.
You could make your service implement some sort of paging, and allow the client to request the number of records they want (usually a starting index and a count, or something like that). You could cap the page-size at a certain limit so that you don't end up having to serve a huge request. Using something like this, you should be able to find a nice balance between the number of calls being made vs. the size of the data being served in each request.
Best practice for queries and WCF Service
[ "", "sql", "wcf", "" ]
I'm creating a server control that basically binds two dropdown lists, one for country and one for state, and updates the state dropdown on the country's selectedindexchanged event. However, it's not posting back. Any ideas why? Bonus points for wrapping them in an UpdatePanel (having rendering issues; maybe because I don't have a Page to reference?) Here's what I have (with some extra data access stuff stripped out): ``` public class StateProv : WebControl { public string SelectedCountry; public string SelectedState; private DropDownList ddlCountries = new DropDownList(); private DropDownList ddlStates = new DropDownList(); protected override void OnLoad(EventArgs e) { base.OnLoad(e); IList<Country> countries = GetCountryList(); IList<State> states = new List<State>(); if (SelectedCountry != null && SelectedCountry != "") { states = GetStateList(GetCountryByShortName(SelectedCountry).CountryShortName); } else { states.Add(new State { CountryId = 0, Id = 0, StateLabelName = "No states available", StateLongName = "No states available", StateShortName = "" }); } ddlCountries.DataSource = countries; ddlCountries.DataTextField = "CountryLongName"; ddlCountries.DataValueField = "CountryShortName"; ddlCountries.SelectedIndexChanged += new EventHandler(ddlCountry_SelectedIndexChanged); ddlCountries.AutoPostBack = true; ddlStates.DataSource = states; ddlStates.DataTextField = "StateLongName"; ddlStates.DataTextField = "StateShortName"; ddlCountries.DataBind(); ddlStates.DataBind(); if (!string.IsNullOrEmpty(SelectedCountry)) { ddlCountries.SelectedValue = SelectedCountry; if (!string.IsNullOrEmpty(SelectedState)) { ddlStates.SelectedValue = SelectedState; } } } protected override void RenderContents(HtmlTextWriter output) { ddlCountries.RenderControl(output); ddlStates.RenderControl(output); } private IList<Country> GetCountryList() { //return stuff } private IList<State> GetStateList(Country country) { //return stuff } private IList<State> GetStateList(string countryAbbrev) { Country country = GetCountryByShortName(countryAbbrev); return GetStateList(country); } private Country GetCountryByShortName(string countryAbbrev) { IList<Country> list = dataAccess.RetrieveQuery<Country>(); //return stuff } private IList<State> GetAllStates() { //return stuff } protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { IList<State> states = GetStateList(GetCountryList()[((DropDownList)sender).SelectedIndex]); ddlStates.DataSource = states; ddlStates.DataBind(); } } ``` **Edit:** Viewstate is on the page, and other controls on the page perform postbacks correctly, just not this.
Is Viewstate turned on? **Edit:** Perhaps you should reconsider overriding the rendering function ``` protected override void RenderContents(HtmlTextWriter output) { ddlCountries.RenderControl(output); ddlStates.RenderControl(output); } ``` and instead add the dropdownlists to the control and render the control using the default RenderContents. **Edit:** See the answer from Dennis which I alluded to in my previous comment: ``` Controls.Add ( ddlCountries ); Controls.Add ( ddlStates ); ```
I can't see that you're adding these controls to the control hierarchy. Try: ``` Controls.Add ( ddlCountries ); Controls.Add ( ddlStates ); ``` Events won't be invoked unless the control is part of the control hierarchy.
ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing
[ "", "c#", "asp.net", "drop-down-menu", "custom-server-controls", "selectedindexchanged", "" ]
Is anyone aware of a such a thing as a SQL writing library for .Net? I'm thinking it would be wrapper for generating queries in an object oriented style. Maybe something like the following: ``` class SelectQuery : BaseQuery { List<Column> SelectedColumns { get; set; } Table MainTable { get; set; } List<Join> Joins { get; set; } List<Condition> Conditions { get; set; } List<Column> Order { get; set; } string Write() { } } ``` Nevermind why I'm looking for something to do this. And, there's no specific problem which this would address for me, I'm just interested in seeing such a thing. Please note, I am not looking for an O/RM, but a means of writing SQL, and representing queries with objects.
I've started a project specifically for this. It's called [SeaQuail](http://seaquail.codeplex.com/).
nHibernate has a new project underway called Antlr which is an Abstract Syntax Tree for SQL Queries. I've not looked at it but it might have you want.
SQL Writing Library
[ "", ".net", "sql", "oop", "" ]
Let's say I have a javascript method that takes a little to long to finish to go without any user feedback at all. In my case it's sorting the rows in a table element (all in the DOM; only takes too long if there are a *lot* of rows), but it might do anything. I want to show the "progress" cursor while it runs. Here is what I have currently, but I've tried several other things as well: ``` // SORT document.body.style.cursor = "progress"; MyLongRunningMethod(); //blocks for 10-15 seconds before returning document.body.style.cursor = "auto"; ``` Unfortunately, nothing happens. MyLongRunningMethod() does it's thing correctly, but the cursor never changes. My thought is that the browser needs to wait for the method to return to be able to handle the cursor change message generated by the windowing environment, but that may be way off and even if it's true I don't know how to fix it. Any other ideas? --- [edit]: I decided all the back-story I had up wasn't really necessary. If you really want to read it check the revision history. --- **Final Results** I ended up using RoBorg's solution. It doesn't mess up the code as much as I was originally thinking, because I can keep the function declared right there- it's just like adding an inline scope block. Interestingly, on Firefox I discovered that this means I don't need to change the cursor at all. I found that after I added the setTimeout call I was sometimes seeing a wait cursor show up before the progress cursor was set, so I commented out my cursor code. It turns out that something in using setTimeout to push this out of the click event handler itself allows FireFox to figure out on it's own that the cursor should change. Unfortunately, IE is not that smart so I did put the cursor code back. This lends credence to my belief that a cursor change is the appropriate action here — given the opportunity it's what the browser will do anyway. I really don't want to have to add and remove new items (like a busy image of some type) into the DOM for a page that I know very little about. The script should match no matter what visual design the page uses. Finally, Chrome makes the whole thing irrelevant. Using the same data, Chrome does in less than 5 seconds what took IE and Firefox 10 to 15 seconds to accomplish. So their javascript engine really is faster. I can't wait for the Firefox 3.1 engine. Unfortunately people here are still mostly using IE6.
Is using a timer out of the question? ``` document.body.style.cursor = "progress"; setTimeout(function() { SortTable(cell.cellIndex, dir, sortType); document.body.style.cursor = "auto"; }, 10); ```
In web, changing mouse cursor is not conventional and not nice. It’s much better (and easier) to use some small animations on the page itself, check <http://www.ajaxload.info/> for such images (it’s an online generator).
Change cursor type for an html document from javascript
[ "", "javascript", "html", "mouse-cursor", "" ]
I have a command line EXE written in C#. It's log parser that grinds through several GB worth of log files every night. It pegs the processor at 100% for quite a while. Not ideal. How could I "throttle" the app? It can take as long as it wants, but I'd rather have it use less of the total CPU. Is there some coding method or theory to make an EXE slow down and take less CPU? I can't do anything in the environment it runs (like change the process priority), so any changes have to be within the code of the app itself.
You can set the priority of the threads using the [`Thread.Priority`](http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx) property. Of course, if there's nothing else trying to run that will still use 100% CPU - but I guess in that case you don't mind so much. Does your application create any other threads or use the thread pool? If it does, you'll probably want to make sure those threads have a reduced priority too. EDIT: Setting the process's overall priority is probably a better solution in general, but I'll leave this one up as an alternative.
Try this: ``` using System.Diagnostics; Process myProc = Process.GetCurrentProcess(); myProc.PriorityClass = ProcessPriorityClass.BelowNormal; ``` If that isn't low enough, there is a `ProcessPriorityClass.Idle` [MSDN Link 1](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.priorityclass.aspx) [MSDN Link 2](http://msdn.microsoft.com/en-us/library/system.diagnostics.processpriorityclass.aspx)
How can you throttle a long-running command-line EXE to avoid pegging the CPU?
[ "", "c#", "" ]
I'd like to do this in JavaScript. To clarify, I mean a page. Sorry about that.
Try this: ``` top != self ``` `top` refers to the top window and `self` to the own window.
Do you mean a form element, or a page? If form, i've never considered having an element inside a separate frame before, but I don't think this is possible in the way you are thinking. Elements have to be inside forms, and forms have to be inside pages. You can have an element, or a form, inside a page, inside a frame on another page, but the two pages will still be separate pages, and the forms will be separate forms. You can't have a single form that spans multiple pages. You can, however, have multiple forms that act as a single process across pages, or you can use AJAX to include content (including form elements) from outside the page, but they become part of the page once they are included. Perhaps one of these options is what you need? You can also have, I suppose an element on another page, in a frame, which you then access via JavaScript, but that element will still be in a separate form, in a separate page.
How do I determine if an HTML element is inside of a frame?
[ "", "javascript", "html", "" ]
I'm trying to create a small app that takes a base text template with specially tagged word arrays, parses the template contents and outputs a randomly generated text document. Essentially, what I'm trying to do is take this: <{Hello|Hi|Howdy}> world. and turn it into this: ``` Hello world. OR Hi world. OR Howdy world. ``` So far, so good. Googling got me enough to be able to successfully extract the inner text between the <{ and }> into an array, from which I then randomly select a word to replace the full <{Hello|Hi|Howdy}>. The problem I'm having is parsing a nested set of words wrapped in the same tags. For example, if I start with this: <{Hello|Hi|Howdy}> world. <{How's <{life|it going}>?|How are you?}> I'd like to turn it into this: ``` Hello world. How's life? OR Hello world. How's it going? OR Hello world. How are you? ``` and so on... Could someone suggest a way to do this fairly simply using c# and regex? I've looked at <http://www.vsj.co.uk/articles/display.asp?id=789> and <http://www.m-8.dk/resources/RegEx-balancing-group.aspx>, and to be honest, a lot of that goes way over my head, so something simple would be nice. ;-) Thank you.
If you have currently have a regex that can correctly parse the values inside your tag into an array (call it A'), then for each value in A', reapply that regex. You should be able to do this recursively.
There is lex and yacc in the Visual Studio SDK: These links might help: <http://msdn.microsoft.com/en-us/library/bb165963(VS.80).aspx> <http://devhawk.net/2006/09/17/Managed+Lex+And+Yacc.aspx> Depending on how complex your parsing is going to be (considering possible future changes and additions) however you may just want to stick with Regex.
C# and regex for word substitutions with nested tags
[ "", "c#", "regex", "" ]
I am using SVN to develop some software in a team of four people. Whenever I update my working copy, it creates far more conflicts than I would expect to be created, a large number of these conflicts are like so: If the initial was ``` import Class1 ``` and I change it to ``` import Class1 import Class2 ``` while another team member changes the code to ``` import Class1 import Class3 ``` Subversion will not merge all three lines. I suppose this is because subversion isn't aware of the semantic content of the code, so couldn't decide when it would/wouldn't be appropriate to do this. Another conflict I get is if I replace ``` processA(); processB(); ``` with : ``` if(x){ processA(); processB(); } ``` the whole thing is marked as a change, is there no way to get it to highlight the fact that only if(x) was added above/below. In cases like this i have to analyse the entire lines inside the new block, and worry about missing small changes in the lines inside. The question is, is there a more effective way for my team to use SVN in these cases, a large portion of my time is spent merging. Sorry for being so long winded in my expression, thanks for reading.
Since SVN doesn't know about programming languages it would be very dangerous if it would try to deduce semantic meaning from change sets. Therefore it can only do relatively simple merges (i.e. if a file changed in two completely different areas). The common solution is to use small commits. Don't keep big changes piling up. Commit often. Update often.
If you check in frequently, you'll still see the big changes (e.g. in the "if" case) but you won't have much *merging* to do.
How can I run updates in SVN without causing many conflicts
[ "", "java", "svn", "" ]
While setting up Hudson for continous integration testing (on a JeOS server), I've come across some strange behaviour I'm hoping the fine people at SO can explain to me. Our unit tests depend heavily on the use of domain objects, with lots of properties that must be set (due to null constraints in the database). In order to keep our tests readable, we have created a class InstantiationUtils that can instantiate an object and set a series of properties through reflection: ``` public static <T> T newInstance(final Class<T> type, final KeyValuePair<?>... propertyValues) { return ReflectionUtils.reflectionOperation(new ReflectionOperation<T>() { @Override public T perform() throws Exception { T object = type.newInstance(); for (KeyValuePair<?> propertyValue : propertyValues) { String propertyName = propertyValue.getKey(); Object value = propertyValue.getValue(); String setterName = "set" + StringUtils.capitalize(propertyName); ReflectionUtils.invoke(object, setterName, value); } return object; } }); } public static void invoke(final Object target, final String methodName, final Object... params) { List<Class<?>> parameterTypes = ListUtils.map(asList(params), "class"); Class<?> targetClass = target.getClass(); Method method = MethodUtils.getMatchingAccessibleMethod(targetClass, methodName, parameterTypes.toArray(new Class<?>[] {})); invoke(target, method, params); } public class Foo { private String foo; public void setFoo(final String foo) { this.foo = foo; } } public class Bar extends Foo { private String bar; public void setBar(final String bar) { this.bar = bar; } } ``` The person who wrote this code unfortunately no longer works for us, but as far as I can see, there is nothing wrong with it. Which is also true for Windows - we use InstantiationUtils throughout our unit tests without any problems. Linux, however, is different. It turns out that in Linux, the newInstance() method only works for direct (i.e. not inherited) members of the class we want to instantiate. InstantiationUtils.newInstance(Bar.class, "bar", "12345"); will work, while InstantiationUtils.newInstance(Bar.class, "foo", "98765"); will fail on Linux, with the following exception: > xxx.xxx.xxx.ReflectionUtils$ReflectionException: java.lang.NoSuchMethodException: Property 'foo' has no setter method On Windows, both calls will work (I know the newInstance signature doesn't match; we have several overloaded newInstance() methods that convert the parameters to KeyValuePairs). I had a hard time accepting that inherited public methods are treated differently, so I have tested this in all ways I can think of. And it always ends up with the conclusion that under Linux, at least with the above usage of Reflection, we can't access public inherited methods. On Windows, I use Sun's JRE 1.6.0.11, in Linux it's also Sun, but version 1.6.0.7. Can anyone confirm if this is correct? Or is the Reflection usage somehow flawed?
Mystery partially solved: MethodUtils.getMatchingAccessibleMethod() apparently works differently on Linux and Windows. By using MethodUtils.getAccessibleMethod() instead, it works. Why, I don't know, but I'm guessing that MethodUtils somehow misinterprets the parameter list when figuring out what signature the Method should have. I'd like to spend more time investigating this, but as always there are things to do and projects to deliver, so I just have to accept that getAccessibleMethod works, and move on :-) Thanks to everyone for their input!
You are using MethodUtils, and it has some [limitations](http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/MethodUtils.html) : > Known Limitations > > Accessing Public Methods In A Default Access Superclass > > There is an issue when invoking public methods contained in a default access superclass. Reflection locates these methods fine and correctly assigns them as public. However, an IllegalAccessException is thrown if the method is invoked. Another thing to check is if the setFoo() method is overloaded, this may also cause the problem...
Is Java Reflection on Inherited Methods Different in Windows and Linux?
[ "", "java", "windows", "linux", "reflection", "" ]
I have an ASP.Net page with a C# code behind. However, I've been asked to not use a code behind - so that it will be easier to deploy in SharePoint. Is there a way to include the C# code in the ASP.Net page, without using a separate code behind file?
By default Sharepoint does not allow server-side code to be executed in ASPX files. [See this](http://mysharepointblog.com/post/2008/01/Running-Code-Blocks-In-Your-SharePoint-ASPX-Pages.aspx) for how to resolve that. However, I would raise that having a code-behind is not necessarily difficult to deploy in Sharepoint (we do it extensively) - just compile your code-behind classes into an assembly and deploy it using a [solution](http://msdn.microsoft.com/en-us/library/aa543214.aspx). If still no, you can include all the code you'd normally place in a codebehind like so: ``` <script language="c#" runat="server"> public void Page_Load(object sender, EventArgs e) { //hello, world! } </script> ```
You can actually have all the code in the aspx page. As explained [here](https://blog.codinghorror.com/code-behind-vs-inline-code/). Sample from [here](http://support.microsoft.com/kb/303247): ``` <%@ Language=C# %> <HTML> <script runat="server" language="C#"> void MyButton_OnClick(Object sender, EventArgs e) { MyLabel.Text = MyTextbox.Text.ToString(); } </script> <body> <form id="MyForm" runat="server"> <asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox> <asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button> <asp:label id="MyLabel" runat="server"></asp:label> </form> </body> </HTML> ```
ASP.net page without a code behind
[ "", "c#", ".net", "asp.net", "sharepoint", "code-behind", "" ]
I have a file open for writing, and a process running for days -- something is written into the file in relatively random moments. My understanding is -- until I do file.close() -- there is a chance nothing is really saved to disk. Is that true? What if the system crashes when the main process is not finished yet? Is there a way to do kind of commit once every... say -- 10 minutes (and I call this commit myself -- no need to run timer)? Is file.close() and open(file,'a') the only way, or there are better alternatives?
You should be able to use `file.flush()` to do this.
If you don't want to kill the current process to add `f.flush()` (it sounds like it's been running for days already?), you should be OK. If you see the file you are writing to getting bigger, you will not lose that data... From Python docs: > **write(str)** > Write a string to the file. There is no return value. Due to buffering, > the string may not actually show up in > the file until the flush() or close() > method is called. It sounds like Python's buffering system will automatically flush file objects, but it is not guaranteed when that happens.
is there COMMIT analog in python for writing into a file?
[ "", "python", "file-io", "commit", "buffering", "" ]
I didn't imagine that I would encounter radically new syntax in Java anymore at this stage, but lo and behold, I just encountered something: *The exact context and what the code below should do is pretty irrelevant - it's there just to give some kind of context.* I'm trying to synthetically create an event in IT Mill Toolkit, so I wrote this kind of line: ``` buttonClick(new Button.ClickEvent(button)); ``` But, Eclipse gives me the following error message: > No enclosing instance of type Button is accessible. Must qualify the allocation with an enclosing instance of type Button (e.g. x.new A() where x is an instance of Button). When I rewrite the line above as follows, it doesn't complain anymore: ``` buttonClick(button.new ClickEvent(button)); // button instanceof Button ``` So, my question is: **What does the latter syntax mean, exactly, and why doesn't the first snippet work?** What is Java complaining about, and what's it doing in the second version? *Background info: Both `Button` and `Button.ClickEvent` are non-abstract public classes.*
Inner classes (like `Button.ClickEvent`) need a reference to an instance of the outer class (`Button`). That syntax creates a new instance of `Button.ClickEvent` with its outer class reference set to the value of `button`. Here's an example - ignore the lack of encapsulation etc, it's just for the purposes of demonstration: ``` class Outer { String name; class Inner { void sayHi() { System.out.println("Outer name = " + name); } } } public class Test { public static void main(String[] args) { Outer outer = new Outer(); outer.name = "Fred"; Outer.Inner inner = outer.new Inner(); inner.sayHi(); } } ``` See [section 8.1.3 of the spec](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.1.3) for more about inner classes and enclosing instances.
Button.ClickEvent is a non-static inner class so an instance of this class can only exist enclosed in a instance of Button. In your second code example you have an instance of Button and you create an instance of ClickEvent enclosed in this Button instance...
Strange syntax for instantiating an inner class
[ "", "java", "constructor", "inner-classes", "" ]
I have a FlowDocumentScrollViewer I want to automatically scroll to the bottom when text is added. ``` <FlowDocumentScrollViewer Name="Scroller"> <FlowDocument Foreground="White" Name="docDebug" FontFamily="Terminal"> <Paragraph Name="paragraphDebug"/> </FlowDocument> </FlowDocumentScrollViewer> ``` In code I add Inlines to the Paragraph, but when there is to much text I would like to be able to simply scroll down using code instead of having the user doing so. Any suggestions?
The other answers given here are a bit puzzling, since I don't see any public "ScrollViewer" property on the FlowDocumentScrollViewer. I hacked around the problem like this. Beware that this method can return null during initialization: ``` public static ScrollViewer FindScrollViewer(this FlowDocumentScrollViewer flowDocumentScrollViewer) { if (VisualTreeHelper.GetChildrenCount(flowDocumentScrollViewer) == 0) { return null; } // Border is the first child of first child of a ScrolldocumentViewer DependencyObject firstChild = VisualTreeHelper.GetChild(flowDocumentScrollViewer, 0); if (firstChild == null) { return null; } Decorator border = VisualTreeHelper.GetChild(firstChild, 0) as Decorator; if (border == null) { return null; } return border.Child as ScrollViewer; } ```
try: ``` Scroller.ScrollViewer.ScrollToEnd(); ``` Where "Scroller" is the name of your FlowDocumentScrollViewer. **EDIT**: I wrote this answer a little too quickly. FlowDocumentScrollViewer does not expose a ScrollViewer property. I had actually extended the FlowDocumentScrollViewer class and implemented the ScrollViewer property myself. Here is the implementation: ``` /// <summary> /// Backing store for the <see cref="ScrollViewer"/> property. /// </summary> private ScrollViewer scrollViewer; /// <summary> /// Gets the scroll viewer contained within the FlowDocumentScrollViewer control /// </summary> public ScrollViewer ScrollViewer { get { if (this.scrollViewer == null) { DependencyObject obj = this; do { if (VisualTreeHelper.GetChildrenCount(obj) > 0) obj = VisualTreeHelper.GetChild(obj as Visual, 0); else return null; } while (!(obj is ScrollViewer)); this.scrollViewer = obj as ScrollViewer; } return this.scrollViewer; } } ```
Scroll a WPF FlowDocumentScrollViewer from code?
[ "", "c#", ".net", "wpf", "flowdocument", "" ]
This is mostly a rhetorical question, as far as I've checked the answer is 'don't even bother', but I wanted to be really sure. We have an email app, where you can send email to lists of subscribers. This is not spam: it's used, for example, by an university to send communications to its students, by a museum to send emails to subscribers, etc. Recently, I was asked by a prospective client if it was possible to send html messages containing javascript without being marked as spam. Not knowing, I did a short trip of the webs and what I've got is (percentages out of my posterior) 'half the clients won't display properly', 'half the clients will flag you as spam' and 'half the clients will have blocked javascript altogether' (There's clearly some superposition). So the best solution seems to be adding a link to a proper page if really necessary. Have you got a different experience? Do you know of any email-merge solution that provides this feature? Do you know if specific clients accept it or refuse to display html with javascript?
You have listed the right arguments against javascript usage in emails. These show you that it is a bad idea. Linking to a page where you can use javascript freely is a good option and lets the user decide if and when he wants to access this "enhanced" content.
The problem of JavaScript is that it poses a security threat. If there is any email client that accepts it, then it's most likely a security vulnerability and should be fixed. So, really, "don't even bother", because even if it works, it'll soon stop working. EDIT: Some people don't seem to understand *why* it is a security risk, so I'll explain. Consider the following code(one of the multiple ways to steal passwords using Javascript and unsafe email clients). Using JavaScript: 1. Create a form with "username" and "password" input fields. 2. Let the browser automatically remember the content of these fields(several users store username and password in the browser's memory to avoid having to type and remember it every time. 3. Once both fields are (automatically) filled, send their content to your website using something like `<img src="badsite.com/senddata?username=user&password=pass">`. 4. Congratulations! You've stolen a password! Usually, just creating a form using JavaScript in your own unsafe website isn't harmful by itself because the browser is smart enough to tell gmail data only to gmail(and you usually don't try to steal passwords from your own website, and in that case there'd be easier ways to steal them anyway). However, if you allowed JavaScript in emails, then the browser wouldn't be capable of separating legitimate JavaScript from insecure code. Cookie theft is also possible if an email client can't filter JavaScript.
Is it possible / recommendable sending HTML emails containing Javascript?
[ "", "javascript", "email", "web-applications", "dhtml", "" ]
I want to open a file which is periodically written to by another application. This application cannot be modified. I'd therefore like to only open the file when I know it is not been written to by an other application. Is there a pythonic way to do this? Otherwise, how do I achieve this in Unix and Windows? **edit**: I'll try and clarify. *Is there a way to check if the current file has been opened by another application?* I'd like to start with this question. Whether those other application read/write is irrelevant for now. I realize it is probably OS dependent, so this may not really be python related right now.
Will your python script desire to open the file for writing or for reading? Is the legacy application opening and closing the file between writes, or does it keep it open? It is extremely important that we understand what the legacy application is doing, and what your python script is attempting to achieve. This area of functionality is highly OS-dependent, and the fact that you have no control over the legacy application only makes things harder unfortunately. Whether there is a pythonic or non-pythonic way of doing this will probably be the least of your concerns - the hard question will be whether what you are trying to achieve will be possible at all. --- **UPDATE** OK, so knowing (from your comment) that: > the legacy application is opening and > closing the file every X minutes, but > I do not want to assume that at t = > t\_0 + n\*X + eps it already closed > the file. then the problem's parameters are changed. It can actually be done in an OS-independent way given a few assumptions, or as a combination of OS-dependent and OS-independent techniques. :) 1. **OS-independent way**: if it is safe to assume that the legacy application keeps the file open for at most some known quantity of time, say `T` seconds (e.g. opens the file, performs one write, then closes the file), and re-opens it more or less every `X` seconds, where `X` is larger than 2\*`T`. * `stat` the file * subtract file's modification time from `now()`, yielding `D` * if `T` <= `D` < `X` then open the file and do what you need with it * *This may be safe enough for your application*. Safety increases as `T`/`X` decreases. On \*nix you may have to double check `/etc/ntpd.conf` for proper time-stepping vs. slew configuration (see tinker). For Windows see [MSDN](http://support.microsoft.com/kb/223184) 2. **Windows**: in addition (or in-lieu) of the OS-independent method above, you may attempt to use either: * sharing (locking): this assumes that the legacy program also opens the file in shared mode (usually the default in Windows apps); moreover, if your application acquires the lock just as the legacy application is attempting the same (race condition), the legacy application will fail. + this is extremely intrusive and error prone. Unless both the new application and the legacy application need synchronized access for writing to the same file and you are willing to handle the possibility of the legacy application being denied opening of the file, do not use this method. * attempting to find out what files are open in the legacy application, using the same techniques as [ProcessExplorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) (the equivalent of \*nix's `lsof`) + you are even more vulnerable to race conditions than the OS-independent technique 3. **Linux/etc.**: in addition (or in-lieu) of the OS-independent method above, you may attempt to use the same technique as `lsof` or, on some systems, simply check which file the symbolic link `/proc/<pid>/fd/<fdes>` points to * you are even more vulnerable to race conditions than the OS-independent technique * it is highly unlikely that the legacy application uses locking, but if it is, locking is not a real option unless the legacy application can handle a locked file gracefully (by blocking, not by failing - and if your own application can guarantee that the file will not remain locked, blocking the legacy application for extender periods of time.) --- **UPDATE 2** If favouring the "check whether the legacy application has the file open" (intrusive approach prone to race conditions) then you can solve the said race condition by: 1. checking whether the legacy application has the file open (a la `lsof` or `ProcessExplorer`) 2. suspending the legacy application process 3. repeating the check in step 1 to confirm that the legacy application did not open the file between steps 1 and 2; delay and restart at step 1 if so, otherwise proceed to step 4 4. doing your business on the file -- ideally simply renaming it for subsequent, independent processing in order to keep the legacy application suspended for a minimal amount of time 5. resuming the legacy application process
One thing I've done is have python very temporarily rename the file. If we're able to rename it, then no other process is using it. I only tested this on Windows.
Python - How to check if a file is used by another application?
[ "", "python", "windows", "unix", "logging", "file-io", "" ]
I have a Java program, in which, I'm using a JTextField, but if i don't specify a default size, it'll have the width 0. I'm inserting it in a BorderLayout, so how do I make it expand to fill the whole container?
In the above example, the text field will work fine. However, if you insert into EAST or WEST, it will not work. ``` import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JTextField; public class TextFieldTest { public static void main(String[] args) { JFrame f = new JFrame(); f.setLayout(new BorderLayout()); JTextField tf = new JTextField(); f.getContentPane().add(BorderLayout.EAST, tf); f.pack(); f.setVisible(true); } } ``` My question back to you is: Does this need to be a BorderLayout or can you use other Layout Managers? If you can, you should check out GridBagLayout that you can have an element auto expand (using a weight) to fit the entire container.
Fill the whole container? With BorderLayout? ``` container.add( jTextField, BorderLayout.CENTER ); ``` Simple as that.
How to make JTextField expand with a BorderLayout (Java)
[ "", "java", "swing", "" ]
How can you tell whether python has been started with the -i flag? According to [the docs](http://www.wingware.com/psupport/python-manual/2.6/using/cmdline.html), you can check the PYTHONINSPECT variable in os.environ, which is the *equivalent* of -i. But apparently it doesn't work the same way. Works: ``` $ PYTHONINSPECT=1 python -c 'import os; print os.environ["PYTHONINSPECT"]' ``` Doesn't work: ``` $ python -i -c 'import os; print os.environ["PYTHONINSPECT"]' ``` The reason I ask is because I have a script that calls sys.exit(-1) if certain conditions fail. This is good, but sometimes I want to manually debug it using -i. I suppose I can just learn to use "PYTHONINSPECT=1 python" instead of "python -i", but it would be nice if there were a universal way of doing this.
### How to set inspect mode programmatically The answer from [the link](http://mail.python.org/pipermail/python-list/2005-April/319756.html) [@Jweede provided](https://stackoverflow.com/questions/640389/tell-whether-python-is-in-i-mode/640405#640405) is imprecise. It should be: ``` import os os.environ['PYTHONINSPECT'] = '1' ``` ### How to retrieve whether interactive/inspect flags are set Just another variant of [@Brian's answer](https://stackoverflow.com/questions/640389/tell-whether-python-is-in-i-mode/640534#640534): ``` import os from ctypes import POINTER, c_int, cast, pythonapi def in_interactive_inspect_mode(): """Whether '-i' option is present or PYTHONINSPECT is not empty.""" if os.environ.get('PYTHONINSPECT'): return True iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int)) #NOTE: in Python 2.6+ ctypes.pythonapi.Py_InspectFlag > 0 # when PYTHONINSPECT set or '-i' is present return iflag_ptr.contents.value != 0 ``` See the Python's [main.c](http://svn.python.org/view/python/trunk/Modules/main.c?view=markup).
I took a look at the source, and although the variable set when -i is provided is stored in Py\_InteractiveFlag, it doesn't look like it gets exposed to python. However, if you don't mind getting your hands a bit dirty with some low-level ctypes inspecting, I think you can get at the value by: ``` import ctypes, os def interactive_inspect_mode(): flagPtr = ctypes.cast(ctypes.pythonapi.Py_InteractiveFlag, ctypes.POINTER(ctypes.c_int)) return flagPtr.contents.value > 0 or bool(os.environ.get("PYTHONINSPECT",False)) ``` [Edit] fix typo and also check PYTHONINSPECT (which doesn't set the variable), as pointed out in comments.
tell whether python is in -i mode
[ "", "python", "" ]
I want to do a case on the result of 2 columns. How do I do this? e.g.: ``` SELECT CASE amount=100 AND DATE IS NOT NULL WHEN 0 THEN 'Something' ELSE '' ``` Something like that?
``` select case when amount = 100 and date is not null then 'something' else 'something else' end ``` This is a "searched case expression" ([see MSDN](http://msdn.microsoft.com/en-us/library/ms181765.aspx)): ``` CASE WHEN Boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END ```
``` select someColumnName, case when amount = 100 AND someothercondition then 'XXX' when amount = 1000 AND anothercondition then 'YYY' else 'WWW' end as "MyColumnName" from myTable ```
TSQL - How to use a case statement for 2 columns?
[ "", "sql", "t-sql", "" ]
I've noticed that Magento stores MySQL connection details in an XML file which isn't secured above the docroot. This seems.... well dangerous. XML seems like a handy way to store config data, except for one thing, typing in <http://www.domain.com.au/library/config.xml> will show the world your private details! I went ahead and used an XMl file and added this to my .htaccess file. ``` <Files ~ "\.xml$"> // regex files that end with xml extension Order allow,deny Deny from all // don't show them </Files> ``` Now I *was* happy with this, now I'm not too sure. What if the .htaccess file is accidentally deleted/corrupted (does that happen besides human error) and what if one day I want to place the app on a non apache server... does every server have the equivalent to block XML files, and if they do, can they be altered on a folder level like the .htaccess can (and not just a httpd.conf file). My question is... does the convenience of XML (easy to update, designers who need to tinker won't feel so intimidated) outweigh the potential problems (exposing private data)?
I'd personally only store config file information in a format thats not in a directly accessible format or location. So I'd either use the XML format above the docroot or use the PHP $config['varname'] = 'value' format. The later method would just render a blank white page if called directly (so long as it's all PHP and contains no HTML and doesn't echo out). Gallery, vBulletin, and Joomla all use the second method I mentioned. I know I've mentioned those projects before in other PHP related questions, but it seems to be a method that's widely used and accepted between projects.
Short answer, no it is not. But a better question would be. If it is not stored in a config file where would you keep it?
Is storing config variables in an XML file on a PHP site under the site root too risky?
[ "", "php", "xml", "apache", ".htaccess", "" ]
I'm looking for a cross-platform file monitoring python package? I know it is possible to monitor files on windows using pywin32, and there are packages working on Linux/Unix but does anyone know about a cross-platform one?
For Unix/Linux based systems, you should use [File Alteration Monitor Python bindings](http://sourceforge.net/projects/python-fam/) to [libfam](http://oss.sgi.com/projects/fam/). For Windows based systems, you should tie into the Win32 API [`FindFirstChangeNotification`](http://msdn.microsoft.com/en-us/library/aa364417%28VS.85%29.aspx) and related functions. As for a cross platform way, I don't know about a good cross platform way. I think it would be best to build a module yourself that works on either OS that uses one of the 2 above methods after detecting what OS it is.
I'm working on an MIT-licensed library that helps Python programs monitor file system events as portably as possible. There are differences that I'm trying to iron out. Highly alpha version at the moment: Check it out here: <http://github.com/gorakhargosh/watchdog/> Patches and contributions are welcome.
Monitoring contents of files/directories?
[ "", "python", "file", "cross-platform", "filesystems", "monitoring", "" ]
I have a quick question - is there a best practice in SQL Table design for storing "either/or" data? I have the following problem - I need to store template data (defining folder structure) in a SQL table. Any given folder might have a static name (for example "Emails") or it might be dynamically generated for each instance, depending on the objects associated with it (eg. Company Name). When a business object is instantiated the template data will be used to create the actual folder structure. I am thinking of storing the data like this: ``` CREATE TABLE folder ( ID INT IDENTITY PRIMARY KEY, FolderName NVARCHAR(50), IsDynamic BIT NOT NULL DEFAULT 0, DynamicFieldID INT FOREIGN KEY REFERENCES dynamicField, ParentID INT FOREIGN KEY REFERENCES folder ) ``` So if the IsDynamic field is set to true I know that there will be a rule (defined on the foreign key), but if not I will use the value stored in the folder name. However this seems a little messy for me - is there a "best-practice" pattern for this kind of scenario?
This doesn't look too bad to me. You may want to consider not bothering with the "IsDynamic" field as this can be derived from the fact that the DynamicFieldID is null. Then in your SQL you could LEFT JOIN and COALESCE the fields from the Dynamic tables. But I don't think the above model is all that messy.
``` CREATE TABLE folder ( ID INT IDENTITY PRIMARY KEY, ParentID INT FOREIGN KEY REFERENCES folder ) CREATE TABLE dynamic_folder ( ID INT FOREIGN KEY REFERENCES folder (id), DynamicFieldID INT FOREIGN KEY REFERENCES dynamicField ) CREATE TABLE static_folder ( ID INT FOREIGN KEY REFERENCES folder (id), FolderName NVARCHAR(50) ) ```
SQL Tables - Pattern for either/or data
[ "", "sql", "t-sql", "database-design", "" ]
When writing a Javascript a function that I had gotten help from [earlier](https://stackoverflow.com/questions/632709/javascript-clientheight-and-alternatives), which gets the height of an element that is hidden, someone reffered me to the Prototype function [getDimensions()](http://prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js). In the example, they set "visibility: hidden; position: absolute; display: block;", which effectively lets us measure what the clientHeight *would* be if it were being displayed. Then they set it all back and you can go about your business. I haven't used prototype, but I would assume that works fine. However, when I tried to mimic the same function in my own code, the use of "position: absolute;" threw off the measurement. It works fine without it, but its use is what allows us to do this for a split second without skewing the design. My version is below, any idea why it isn't working? ``` var objStyle = obj[objName].style; // Record original style values var visibility = objStyle.visibility; //var position = objStyle.position; var display = objStyle.display; // Modify object for measuring objStyle.visibility = "hidden"; //objStyle.position = "absolute"; objStyle.display = "block"; // Measure height height = obj[objName].clientHeight; // Fix object objStyle.visibility = visibility; //objStyle.position = position; objStyle.display = display; // Return height return parseInt(height); ``` Thanks in advance for your help.
I don't know if it works while invisible, but jQuery has some options here - in particular the [height function](http://docs.jquery.com/CSS/height); worth a look? Based on your example, something like: ``` height = $(obj[objName]).height(); ```
Are you seeing this only on a cetain browser, or on all browsers? Prototype's getDimensions() does a check for Safari (and possibly other buggy browsers), you should try putting that in your code as well and see if it fixes the issue. It could also be due to the fact that you're using obj[objName] as opposed to document.getElementById() - AFAIK these will return slightly different objects, which could cause the inconsistency you're seeing.
Javascript clientHeight inconsistency
[ "", "javascript", "html", "css", "dom", "" ]
I can flatten the results of a child collection within a collection with SelectMany: ``` // a list of Foos, a Foo contains a List of Bars var source = new List<Foo>() { ... }; var q = source.SelectMany(foo => foo.Bar) .Select(bar => bar.barId) .ToList(); ``` this gives me the list of all Bar Ids in the Foo List. When I attempt to go three levels deep the incorrect result is returned. ``` var q = source.SelectMany(foo => foo.Bar) .SelectMany(bar => bar.Widget) .Select(widget => widget.WidgetId) .ToList(); ``` How should I be using SelectMany to get the list of all Widgets in all Bars in my list of Foos? **Edit** I miss-worded the above sentence, but the code reflects the goal. I am looking for a list of all Widget Ids, not widgets. An "incorrect" result is not all of the widget ids are returned.
Your query is returning all the widget IDs, instead of all the widgets. If you just want widgets, just use: ``` var q = source.SelectMany(foo => foo.Bar) .SelectMany(bar => bar.Widget) .ToList(); ``` If that's still giving "the incorrect result" please explain in what *way* it's the incorrect result. Sample code would be very helpful :) EDIT: Okay, if you want the widget IDs, your original code should be fine: ``` var q = source.SelectMany(foo => foo.Bar) .SelectMany(bar => bar.Widget) .Select(widget => widget.WidgetId) .ToList(); ``` That could also be written as ``` var q = (from foo in source from bar in foo.Bar from widget in bar.Widget select widgetId).ToList(); ``` if you like query expression format. This really should work - if it's *not* working, that suggests there's something wrong with your data. We should have checked before - is this just LINQ to Objects, or a fancier provider (e.g. LINQ to SQL)?
``` var q = ( from f in foo from b in f.Bars from w in b.Widgets select w.WidgetId ).ToList(); ``` Also note that if you want the unique list, you can do .Distinct().ToList() instead.
SelectMany Three Levels Deep
[ "", "c#", "generics", "list", "lambda", "" ]
I need to understand the following sentence: "Charles Simonyi introduced the idea of organizing really big software teams by creating one super duper uber programmer writing the **top-level functions**, while handing off the implementation of the **lower-level functions** to a team of grunt junior-programmers as needed. They called this position program manager." 1. I want to know what are the **Top-level functions** 2. What are the **lower-level** functions? 3. How can a program manager easily **spot Top-level and Lower-level functions**? 4. Can you provide **Javascript examples** of Top-level and Lower-level functions? BTW, the quote above is taken from Joel Spolsky, extracted from his blog about How to be a program manager.
The closer it is to human language, the higher-level the function is. The closer it is to machine language, the lower-level the function is. I'm simplyfying but here are some examples: High level functions: ``` Car.Start() Car.MoveTo(Home) ``` Low level functions: ``` Car.Insert(Key); if (Car.IsKeyInserted() == False) return False; Car.StartEngine(); Car.ApplyAccelerator(0.1f); Car.ChangeGear(); Car.RotateWheel(-25); ```
**Top level function** is a term that describes writing program code outside of sub or function. There are various levels from declaring stuff to actually running program code like vbs/jscript. It normally discouraged or not allowed on languages that are expected to be complex. VB for instance only allows const and declares and dim. C# allows nothing top level. We normally use **higher level** to describe the abstraction of a language. In some languages the term will be top level method. I remember reading this a long time ago. <http://blogs.msdn.com/b/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx> which links back to this site [Why C# is not allowing non-member functions like C++](https://stackoverflow.com/questions/1024171/why-c-is-not-allowing-non-member-functions-like-c/1027853#1027853)
What's the difference between Low-level functions & Top-level functions?
[ "", "javascript", "project-management", "function", "" ]
I know JavaScript can open a link in a new window but is it possible to open a webpage without opening it in a window or displaying it to the user? What I want to do is parse that webpage for some text and use it as variables. Is this possible **without** any help from server side languages? If so, please send me in a direction I can achieve this. Thanks all
You can use an [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) object to do this. Here's a simple example ``` var req = new XMLHttpRequest(); req.open('GET', 'http://www.mydomain.com/', false); req.send(null); if(req.status == 200) dump(req.responseText); ``` Once loaded, you can perform your parsing/scraping by using [javascript regular expressions](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/RegExp) on the req.responseText member. ## More detail... In practice you need to do a little more to get the XMLHttpRequest object in a cross platform manner, e.g.: ``` var ua = navigator.userAgent.toLowerCase(); if (!window.ActiveXObject) req = new XMLHttpRequest(); else if (ua.indexOf('msie 5') == -1) req = new ActiveXObject("Msxml2.XMLHTTP"); else req = new ActiveXObject("Microsoft.XMLHTTP"); ``` ## Or use a library... Alternatively, you can save yourself all the bother and just use a library like [jQuery](http://docs.jquery.com/Ajax) or [Prototype](http://www.prototypejs.org/api/ajax) to take care of this for you. ## Same-origin policy may bite you though... Note that due to the [same-origin policy](http://www.w3.org/TR/XMLHttpRequest/#same-origin), the page you request must be from the same domain as the page making the request. If you want to request a remote page, you will have to proxy that via a server side script. Another possible workaround is to use Flash to make the request, which does allow cross-domain requests if the target site grants permission with a suitably configured crossdomain.xml file. Here's a nice article on the subject of the same-origin policy: * [Same-Origin Policy Part 1: Why we’re stuck with things like XSS and XSRF/CSRF](http://taossa.com/index.php/2007/02/08/same-origin-policy/)
Whatever Origin is an open source library that allows you to use purely Javascript to do scraping. It also solves the "same-domain-origin" problem. <http://www.whateverorigin.org/> ``` $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){ alert(data.contents); }); ```
Open webpage and parse it using JavaScript
[ "", "javascript", "regex", "parsing", "html", "" ]
I have seen it written in multiple threads/comments on stackoverflow that using `switch` is just bad OOP style. Personally I disagree with this. There will be many cases where you cannot add code (i.e. methods) to `enum` classes you want to switch on because you don't control them, perhaps they are in a 3rd-party jar file. There will be other cases where putting the functionality *on the enum itself* is a bad idea because it violates some separation-of-concerns considerations, or it is actually a function of something else *as well as the enumeration*. Last of all, switches are concise and clear: ``` boolean investable; switch (customer.getCategory()) { case SUB_PRIME: case MID_PRIME: investible = customer.getSavingsAccount().getBalance() > 1e6; break; case PRIME: investible = customer.isCeo(); break; } ``` I'm not defending every use of `switch` and I'm not saying it's always the way to go. But statements like "Switch is a code smell" are just wrong, in my opinion. Does anyone else agree?
Taking your followup: > *What if this is just the "investibility" logic for a customer wishing for a business loan. Perhaps the innvestibility decision of a customer for another product is really quite different ... Also, what if there are new products coming out all the time, each with different investibility decisions and I don't want to be updating my core Customer class every time this happens?* and one of your comments: > *I'm not entirely sure about holding logic close to the data on which it operates. The real world doesn't work like this. When I ask for a loan, the bank decides whether I qualify. They don't ask me to decide for myself.* you are right, as far as this goes. ``` boolean investable = customer.isInvestable(); ``` is not the optimal solution for the flexibility you're talking about. However, the original question didn't mention the existence of a separate Product base class. Given the additional information now available, the best solution would appear to be ``` boolean investable = product.isInvestable(customer); ``` The investability decision is made (polymorphically!) by the Product, in accordance with your "real world" argument and it also avoids having to make new customer subclasses each time you add a product. The Product can use whatever methods it wants to make that determination based on the Customer's public interface. I'd still question whether there are appropriate additions which could be made to Customer's interface to eliminate the need for switch, but it may still be the least of all evils. In the particular example provided, though, I'd be tempted to do something like: ``` if (customer.getCategory() < PRIME) { investable = customer.getSavingsAccount().getBalance() > 1e6; } else { investable = customer.isCeo(); } ``` I find this cleaner and clearer than listing off every possible category in a switch, I suspect it's more likely to reflect the "real world" thought processes ("are they below prime?" vs. "are they sub-prime or mid-prime?"), and it avoids having to revisit this code if a SUPER\_PRIME designation is added at some point.
I think statements like > Using a switch statement is bad OOP style. and > Case statements can almost always be replaced with polymorphism. are oversimplifying. The truth is that case statements that are switching on **type** are bad OOP style. These are the ones you want to replace with polymorphism. Switching on a **value** is fine.
Does anyone disagree with the statement: "using switch is bad OOP style"?
[ "", "java", "oop", "switch-statement", "" ]
I'm working on a roguelike style cellphone game that operates on a grid. Attacks/Items in this game operate by targeting tiles in a pattern relative to the user. The paturn is usually relative to the direction the user is aiming in as well, For instance in this [screenshot](http://arlenphillips.googlepages.com/Shotgun.PNG) the pattern ``` Point2d[] damageTiles = new Point2d[4]; damageTiles[0] = new Point2d(0, -1); damageTiles[1] = new Point2d(0, -2); damageTiles[2] = new Point2d(1, -2); damageTiles[3] = new Point2d(-1, -2); ``` is show relative to a temporary enemy(the yellow box) aiming "up". I currently have simple code to rotate a pattern array by 90 degree increments, as seen [here](http://arlenphillips.googlepages.com/screenshot.2.png). My question is, Is there an easy way to rotate an array of 2d points by 45 degree increments, allowing my Attacks/Items to fire on the diagonal, preferably without using floating point math, as it tends to run slowly on many phones(or so i hear). This is probably a trivial question to anyone familiar with graphics programming, but I've been hit with a case of coder's-block. My current rotation code is shown below. I now realize that a better way to do it would be to take an angle instead of a "direction" and rotate the points by that angle (rejecting angles that are not multiples of 45 of course). ``` private Point2d[] rotateList(Point2d[] points, int direction) { for (int i = 0; i < points.length; i++) { if (direction == ROTATE_LEFT) { int temp = points[i].x; points[i].x = points[i].y; points[i].y = -1 * temp; } else if (direction == ROTATE_RIGHT) { int temp = points[i].x; points[i].x = -1 * points[i].y; points[i].y = temp; } } return points; } ```
The T-shaped attack you show would be difficult to rotate at 45 degrees--things don't really translate from 90 to 45. ``` original: ..... .###. ..#.. ..o.. alternative A: ..... .##.. .##.. ...o. alternative B: ..#.. .#... #.#.. ...o. ``` There could easily be others for that pattern. I recommend you create a 45 degree "Pattern" to match you 90 degree pattern, then rotate the 45degree pattern exactly the same way you rotate your 90 degree patterns.
You can use a simple rotation matrix to rotate each point: <http://www.siggraph.org/education/materials/HyperGraph/modeling/mod_tran/2drota.htm>
j2me - Rotate array of 2d points in 45 degree increments
[ "", "java", "graphics", "java-me", "" ]
in my code I'm using ``` Thread.currentThread().sleep(sleepTime); ``` in the main (non Thread object) portion of the code. It appears to be working fine, but I'm worried that there might be some hidden pitfall that will bite me in the ass later. Is there a better way to make your main process sit around for a while? or is this the prescribed methodology? EDIT: In answer to why I'm doing it this way... I have a process that connects via HTTP or FTP to remote hosts and does stuff. In other words... stuff... connect to remote... do stuff with remote connection... close connection... more stuff... repeat as necessary. I've found that in very very rare instances, the connection just goes off into la la land. It doesn't fail, it doesn't throw any exception, it just goes away. And it's blocking, so there's no in-line way to set a timer. So, my solution is to do this... stuff... start new thread with connection in it... go into an infinite loop with a timer in the MAIN process (not in the spawned thread) and wait for either a) the connection thread to complete its task and set some flag to "done" or b) wait some preset amount of time and if the connection thread has not reported that it's finished, kill it and move on. It is in the main process that I intend to sleep for some time, wake up, and see if the MAX\_WAIT\_TIME has expired. If not, go back to sleep and wait some more. It seems much more efficient (on the processor) than sitting in standard while loop, since that would really interfere with the connection thread's business of doing what it needs to do. I guess my question really is... is there anything unsafe about this approach. I see from the answers that, given what I'm doing, it looks like there isn't. Perhaps I should have asked if there is a more standardized approach?
There's no pitfall. It will sleep for as long as you tell it to. There may or may not be a pitfall in the idea of your application falling asleep for a prolonged period of time.
What kind of application are you writing? It's rarely a good idea, and it's a *particularly* bad idea if you're writing a client GUI - while the thread is sleeping, it won't be responsive. If you could give more of an indication why you need to pause and the kind of application you're writing, that would help. One other thing - your call should really be: ``` Thread.sleep(sleepTime); ``` Calling it via `currentThread()` makes it *look* like it's an instance method, but it's not - it's just a normal static method. You can't make any *other* thread sleep. You should see if your IDE has an option to make calling static methods via a reference into a warning or error - it leads to misleading code (like this).
Is there anything dangerous about using Thread.currentThread.sleep() in my main code?
[ "", "java", "multithreading", "sleep", "" ]
I use Zend IDE and quite often use Analyze code to quickly find undeclared or unused variables. As all PHP developers I also use regular expressions. So main question is where to set a checkbox or tune config file to disable these warnings: Bad escape sequence: \s (line NN) Thanks for answers!
Why don’t you just correct the mistyped string declarations. If you have the regular expression `foo\sbar`, write it as: ``` 'foo\\sbar' "foo\\sbar" ```
window->preferences->php->code analyzer->bug->bas escape sequence
How to make Zend IDE 5.5.1 to not bother about backslashes?
[ "", "php", "regex", "ide", "zend-studio", "" ]
I seem to be snagging on a fundamental but I can't find the solution anywhere. Anywho, will go ahead and explain. I have a program consisting of three files; main.ccp, add.h, add.cpp. I declare the class 'SA' in add.h and have all my functions defined in add.cpp. additional.h ``` class SA { ... public int x; } Obj1, Obj2; ``` main.ccp ``` #include "additional.h" int main() { Obj1.x = 5; ... } ``` This gives me a link error on compiling: error LNK2005: "class SA Obj1" (?Obj1@@3VSA@@A) already defined in main.obj The only deffinition of the object occurs in add.h, and nowhere else. The program compiles just fine if I declare the objects in the main and not the header: main.ccp ``` #include "additional.h" int main() { SA Obj1; Obj1.x = 5; ... } ``` The issue is that I want to use the objects primarily within add.cpp, but still need to initialise several public values through main.cpp. Any words of wisdom?
Define Obj1 and Obj2 in your .cpp instead of at .h add.h ``` class SA { ... public int x; }; ``` main.cpp ``` #include "additional.h" SA Obj1, Obj2; int main() { Obj1.x = 5; ... } ``` If you want to declare Obj1 and Obj2 in your .h file, add extern in the .h file like so: ``` extern SA Obj1, Obj2; ``` but you should declare the objects in a .cpp file in your project: main.cpp ``` SA Obj1, Obj2; ``` The reason for this is that everytime you include the .h file, you are declaring Obj1 and Obj2. So if you include the .h file two times, you will create two instance of Obj1 and Obj2. By adding the keyword extern, you are telling the compiler that you have already decalred the two variables somewhere in your project (preferably, in a .cpp file).
Use *extern* keyword. Declare these public objects as extern in header, then define instances in one of the cpps. Like this: ``` extern SA Obj1; // in header SA Obj1;// in any one (no more than one) cpp ```
Declaring class objects in a header file
[ "", "c++", "object", "header", "linker", "" ]
The following code ``` import types class A: class D: pass class C: pass for d in dir(A): if type(eval('A.'+d)) is types.ClassType: print d ``` outputs ``` C D ``` How do I get it to output in the order in which these classes were defined in the code? I.e. ``` D C ``` Is there any way other than using inspect.getsource(A) and parsing that?
The `inspect` module also has the `findsource` function. It returns a tuple of source lines and line number where the object is defined. ``` >>> import inspect >>> import StringIO >>> inspect.findsource(StringIO.StringIO)[1] 41 >>> ``` The `findsource` function actually searches trough the source file and looks for likely candidates if it is given a class-object. Given a method-, function-, traceback-, frame-, or code-object, it simply looks at the `co_firstlineno` attribute of the (contained) code-object.
Note that that parsing is already done for you in inspect - take a look at `inspect.findsource`, which searches the module for the class definition and returns the source and line number. Sorting on that line number (you may also need to split out classes defined in separate modules) should give the right order. However, this function doesn't seem to be documented, and is just using a regular expression to find the line, so it may not be too reliable. Another option is to use metaclasses, or some other way to either implicitly or explicitly ordering information to the object. For example: ``` import itertools, operator next_id = itertools.count().next class OrderedMeta(type): def __init__(cls, name, bases, dct): super(OrderedMeta, cls).__init__(name, bases, dct) cls._order = next_id() # Set the default metaclass __metaclass__ = OrderedMeta class A: class D: pass class C: pass print sorted([cls for cls in [getattr(A, name) for name in dir(A)] if isinstance(cls, OrderedMeta)], key=operator.attrgetter("_order")) ``` However this is a fairly intrusive change (requires setting the metaclass of any classes you're interested in to OrderedMeta)
Python introspection: How to get an 'unsorted' list of object attributes?
[ "", "python", "introspection", "python-datamodel", "" ]
So lets say that in my entry point class (i.e the class which runs when the program starts (which has the `public static void main(String args[])` function). In that class I have this variable: ``` private ArrayList<String> myData=new ArrayList<String>(); ``` This class instantiates another class, which needs to have access to the `myData` member of the entry point class. How can it retrieve this arraylist? Edit: To clarify, in the `main()` method I could do this: ``` SomeOtherClass myClass=new SomeOtherClass(); ``` and then I could do: ``` myClass.someMethod(); ``` however, in the `myClass` object, how could I perform a method/retrieve something from the entry class, which instantiated the `myClass` object?
It sounds like your entry point is still static when it calls some other class, but your ArrayList is a member of an *instance* of it. You need to move out of the static world and into instances. I'd refactor your main method into a private construtor, and put in a new main() which launches it as a new instance. Note that this code is very rough, but it should serve to illustrate what you need to do. ``` public class EntryPoint { private ArrayList<String> myData=new ArrayList<String>(); public static void main( String[] args ) { EntryPoint ep = new EntryPoint(); ep.init(); } private void init() { // Populate myData perhaps? SomeOtherClass myClass=new SomeOtherClass(); myClass.someMethod( this ); } public List<String> getMyData() { return myData; } } public class SomeOtherClass { public void someMethod( EntryPoint entry ) { List<String> data = entry.getMyData(); // do stuff with data..! } } ```
The best way to give the class you instantiate access to `myData` would be to pass it into the constructor when it is created. Then, in your constructor, you can save the `ArrayList` into a member variable of the class. For example, your object constructor will look like: ``` private ArrayList<String> myData; public YourObjConstructor(ArrayList<String> data){ myData = data; } ```
How do Java classes get information from the Entry class?
[ "", "java", "oop", "" ]
How can I determine the list of files in a directory from inside my C or C++ code? I'm not allowed to execute the `ls` command and parse the results from within my program.
**UPDATE 2017**: In C++17 there is now an official way to list files of your file system: `std::filesystem`. There is an excellent answer from [**Shreevardhan**](https://stackoverflow.com/a/37494654/23264) below with this source code: > ``` > #include <string> > #include <iostream> > #include <filesystem> > namespace fs = std::filesystem; > > int main() > { > std::string path = "/path/to/directory"; > for (const auto & entry : fs::directory_iterator(path)) > std::cout << entry.path() << std::endl; > } > ``` **Old Answer:** In small and simple tasks I do not use boost, I use `dirent.h`. It is available as a standard header in UNIX, and also available for Windows via a [compatibility layer created by Toni Rönkkö](https://github.com/tronkko/dirent). ``` DIR *dir; struct dirent *ent; if ((dir = opendir ("c:\\src\\")) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { printf ("%s\n", ent->d_name); } closedir (dir); } else { /* could not open directory */ perror (""); return EXIT_FAILURE; } ``` It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost (no offence, I like boost!).
C++17 now has a [`std::filesystem::directory_iterator`](https://en.cppreference.com/w/cpp/filesystem/directory_iterator), which can be used as ``` #include <string> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::string path = "/path/to/directory"; for (const auto & entry : fs::directory_iterator(path)) { std::cout << entry.path() << std::endl; } } ``` Also, [`std::filesystem::recursive_directory_iterator`](https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator) can iterate the subdirectories as well.
How can I get the list of files in a directory using C or C++?
[ "", "c++", "c", "file", "directory", "" ]
What does `where T : somevalue` mean? I just saw some code that said `where T : Attribute`. I think this has something to do with generics but I am not sure what this means or what it is doing. Does anyone know?
It is a [**constraint on a type parameter**](http://msdn.microsoft.com/en-us/library/d5x73970.aspx), meaning that the type `T` given to a generic class or method must inherit from the class `Attribute` For example: ``` public class Foo<T> : where T : Attribute { public string GetTypeId(T attr) { return attr.TypeId.ToString(); } // .. } Foo<DescriptionAttribute> bar; // OK, DescriptionAttribute inherits Attribute Foo<int> baz; // Compiler error, int does not inherit Attribute ``` This is useful, because it allows the generic class to do things with objects of type `T` with the knowledge that anything that is a `T` must also be an `Attribute`. In the example above, it's okay for `GetTypeId` to query the `TypeId` of `attr` because `TypeId` is a property of an `Attribute`, and because `attr` is a `T` it must be a type that inherits from `Attribute`. Constraints can also be used on generic methods, with the same effect: ``` public static void GetTypeId<T>(T attr) where T : Attribute { return attr.TypeId.ToString(); } ``` There are other constraints you can place on a type; from [MSDN](http://msdn.microsoft.com/en-us/library/d5x73970.aspx): > `where T: struct` > > The type argument must be a value > type. Any value type except Nullable > can be specified. > > `where T : class` > > The type argument must be a reference > type; this applies also to any class, > interface, delegate, or array type. > > `where T : new()` > > The type argument must have a public > parameterless constructor. When used > together with other constraints, the > new() constraint must be specified > last. > > `where T : <base class name>` > > The type argument must be or derive > from the specified base class. > > `where T : <interface name>` > > The type argument must be or implement > the specified interface. Multiple > interface constraints can be > specified. The constraining interface > can also be generic. > > `where T : U` > > The type argument supplied for T must > be or derive from the argument > supplied for U. This is called a naked > type constraint.
Additionally what the others said, you have the following too: * new() - T must have default constructor * class - T must be a reference type * struct - T must be a value type
What does "where T : somevalue" mean?
[ "", "c#", "generics", "constraints", "" ]
Given (in C++) ``` char * byte_sequence; size_t byte_sequence_length; char * buffer; size_t N; ``` Assuming `byte_sequence` and `byte_sequence_length` are initialized to some arbitrary length sequence of bytes (and its length), and `buffer` is initialized to point to `N * byte_sequence_length` bytes, what would be the easiest way to replicate the `byte_sequence` into `buffer` `N` times? Is there anything in STL/BOOST that already does something like this? For example, if the sequence were "abcd", and `N` was 3, then `buffer` would end up containing "abcdabcdabcd".
I would probably just go with this: ``` for (int i=0; i < N; ++i) memcpy(buffer + i * byte_sequence_length, byte_sequence, byte_sequence_length); ``` This assumes you are dealing with binary data and are keeping track of the length, not using `'\0'` termination. If you want these to be c-strings you'll have to allocate an extra byte and add in the `'\0'` a the end. Given a c-string and an integer, you'd want to do it like this: ``` char *RepeatN(char *source, size_t n) { assert(n >= 0 && source != NULL); size_t length = strlen(source) - 1; char *buffer = new char[length*n + 1]; for (int i=0; i < n; ++i) memcpy(buffer + i * length, source, length); buffer[n * length] = '\0'; } ```
**Repeating the buffer while avoiding pointer arithmetic:** You can use std::vector < char > or std::string to make things easier for you. Both of these containers can hold binary data too. This solution has the nice properties that: * You don't need to worry about memory access violations * You don't need to worry about getting the size of your *buffer* correct * You can append sequences at any time to your buffer without manual re-allocations . ``` //Note this works even for binary data. void appendSequenceToMyBuffer(std::string &sBuffer , const char *byte_sequence , int byte_sequence_length , int N) { for(int i = 0; i < N; ++i) sBuffer.append(byte_sequence, byte_sequence_length); } //Note: buffer == sBuffer.c_str() ``` --- **Alternate: For binary data using memcpy:** ``` buffer = new char[byte_sequence_length*N]; for (int i=0; i < N; ++i) memcpy(buffer+i*byte_sequence_length, byte_sequence, byte_sequence_length); //... delete[] buffer; ``` --- **Alternate: For null terminated string data using strcpy:** ``` buffer = new char[byte_sequence_length*N+1]; int byte_sequence_length = strlen(byte_sequence); for (int i=0; i < N; ++i) strcpy(buffer+i*byte_sequence_length, byte_sequence, byte_sequence_length); //... delete[] buffer; ``` --- **Alternate: If you are filling the buffer with a single value:** ``` buffer = new char[N]; memset(buffer, byte_value, N); //... delete[] buffer; ```
Easiest way to repeat a sequence of bytes into a larger buffer in C++
[ "", "c++", "stl", "boost", "" ]
I want to code a function in javascript that every time I call it in the webform it fires up an specific validator in that same webform.
``` if (Page_ClientValidate('Validation Group')) { //Your valid } ```
``` <asp:RequiredFieldValidator ID="passwordRequiredFieldValidator" runat="server" ErrorMessage="* Password Required!" EnableClientScript="true" CssClass="errorText" ControlToValidate="passwordTextBox"> </asp:RequiredFieldValidator> ``` To fire this validator use: ``` window.ValidatorValidate(window.passwordRequiredFieldValidator); ``` Further example: ``` function ValidatePassword() { window.ValidatorValidate(window.passwordRequiredFieldValidator); var valid = window.passwordRequiredFieldValidator.isvalid; alert(valid); } ```
How do I fire an ASP.NET custom validator from JavaScript?
[ "", "asp.net", "javascript", "" ]
Look at the code snippet: This is what I normally do when coding against an enum. I have a default escape with an InvalidOperationException (I do not use ArgumentException or one of its derivals because the coding is against a private instance field an not an incoming parameter). I was wondering if you fellow developers are coding also with this escape in mind.... ``` public enum DrivingState {Neutral, Drive, Parking, Reverse}; public class MyHelper { private DrivingState drivingState = DrivingState.Neutral; public void Run() { switch (this.drivingState) { case DrivingState.Neutral: DoNeutral(); break; case DrivingState.Drive: DoDrive(); break; case DrivingState.Parking: DoPark(); break; case DrivingState.Reverse: DoReverse(); break; default: throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, "Drivestate {0} is an unknown state", this.drivingState)); } } } ``` In code reviews I encounter many implementations with only a break statement in the default escape. It could be an issue over time....
I don't like this approach because the default case is untestable. This leads to reduced coverage in your unit tests, which while isn't necessarily the end of the world, annoys obsessive-compulsive me. I would prefer to simply unit test each case and have an additional assertion that there are only four possible cases. If anyone ever added new enum values, a unit test would break. Something like ``` [Test] public void ShouldOnlyHaveFourStates() { Assert.That(Enum.GetValues( typeof( DrivingState) ).Length == 4, "Update unit tests for your new DrivingState!!!"); } ```
Your question was kinda vague, but as I understand it, you are asking us if your coding style is good. I usually judge coding style by how readable it is. I read the code **once** and I understood it. So, in my humble opinion, your code is an example of good coding style.
Programming against an enum in a switch statement, is this your way to do?
[ "", "c#", ".net", "" ]
I'm not sure how to best word this, so I'll give it a shot and hopefully revise it as it comes to me. Using javascript/jQuery, let's say I want to get some data from a clicked element to a function for processing. A couple of options: OPTION 1: ``` $('.classOfInterest').click(function() { // How can I get 'a' and 'b'? var c = $(this).hasClass('cExists'); }); <a class="cExists classOfInterest" /> ``` OPTION 2: ``` function processClick(string a, string b) { // How can I get a reference to the calling element, similar to $(this) in the event handler? var c; // here I want to determine whether the calling element has class 'cExists' } <a class="cExists" href="javascript:processClick('a', 'b')" /> ```
Option 1 is the more jQuery-ish way to accomplish what you're trying to do. You can get a and b by making them attributes of the link: ``` $('.classOfInterest').click(function() { // How can I get 'a' and 'b'? var c = $(this).hasClass('cExists'); alert(this.attr('a') + ' ' + this. attr('b')); }); <a class="cExists classOfInterest" a="hi" b="mom" /> ```
JS: ``` function processClick(id, a, b) { $(id).click(function() { var c = $(this).hasClass('cExists'); alert(a + ' ' + b); }); } ``` HTML: ``` <script type="text/javascript">processClick("foo123", "a", "b")</script> <a class="cExists" id="foo123" href="#"> ``` Another option if you want to avoid the inline js inside the html is to do something like the following. JS: ``` $(function() { $('cExists').click(function() { var c = $(this).hasClass('cExists'); var a = $(this).attr('title').split(":")[0]; var b = $(this).attr('title').split(":")[1]; alert(a + ' ' + b); }); }); ``` HTML: ``` <a class="cExists" href="#" title="foo:bar"> ``` But this way you'll be exposing the **a** and **b** variables on the element's title.
What are my options to get all the necessary data using javascript and/or jQuery for the following scenario?
[ "", "javascript", "jquery", "" ]
Is there a printf()-like formatting in MySQL? I couldn't find a straightforward way in the documentation. For example, how can I make something like: ``` SELECT STRFORMATFUNCTIONIMLOOKINGFOR("%03d", 17) ``` to get 017 ?
You can implement this kind of function by creating a new UDF (user defined function).E.g. see <http://dev.mysql.com/doc/refman/5.1/en/adding-functions.html>
for your example, you could use SELECT [LPAD](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_lpad)(17, 3, '0'); there is also SELECT [FORMAT](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_format)(17, 3); -- 17.000 otherwise, UDF as mentioned above.
String formatting in MySQL
[ "", "mysql", "sql", "formatting", "format", "" ]
I'm looking for a way to add or remove files to/from an existing ZIP archive, or any other archive format for that matter as long as there are cross platform APIs, without having to rewrite a new zip file with new files added to it, or sans items deleted from it. With ZIP files, the catalog is placed at the end of the file so that, and some parts of the zip file will likely have to be rewritten each time. I'm just trying to avoid having to rewrite the whole thing every time. The archive files I'm looking at dealing with will be large, and speed is important. Is there any C++ library out there that does what I'm looking for?
[Zipios++](http://zipios.sourceforge.net/) provides direct access to files inside ZIP archives.
[miniz](https://github.com/richgel999/miniz) library allows you to append a file to an existing archive without rewriting it with one function call: ``` mz_zip_error error = MZ_ZIP_NO_ERROR; mz_bool status = mz_zip_add_mem_to_archive_file_in_place_v2("foo.zip", "bar.txt", "Test", 4, "Comment", 7, MZ_BEST_COMPRESSION, &error); ```
C++ Library for modifying a ZIP file in place
[ "", "c++", "zip", "archive", "" ]
I recently had my mind expanded by a new concept: [Web Services for Remote Portlets](http://en.wikipedia.org/wiki/Web_Services_for_Remote_Portlets), or WSRP. I learned of it during a presentation on a Java-based web portal we are considering purchasing at work; we are a .NET shop and WSRP would be the means by which we would extend this portal. Although I cannot control the end decision as to whether or not we purchase the product, I can provide input as to how difficult it would be to build WSRP-compliant portlets. Unfortunately, my recent queries into the subject have turned up almost nill. So I ask you, the SO community, the following: what libraries or frameworks are out there for building WSRP-compliant portlets in C#/.NET? What are some of the pros and cons of using WSRP in general? Because there is no correct answer here, I will make this a community wiki post. So far, I have only found the following: * [WSRP Toolkit for Sharepoint](http://blogs.msdn.com/sharepoint/archive/2008/12/05/announcing-the-wsrp-toolkit-for-sharepoint.aspx) by Microsoft (but requiring Sharepoint). * [WSRP Portal and WSRP .NET Framework](http://www.netunitysoftware.com/) By NetUnity. Given that WSRP is on top of SOAP, this seems like a perfect candidate for a WCF binding and channel, and yet I see nothing on the subject, anywhere.
If you read the WSRP spec carefully, you'll find it is a remote version of the Java Portlet Specification (if I'm spelling that right). That means that it's useful for integrating Java Portlets. Anything else will have to look like a Java Portlet, which is not very generic.
WSRP is very contrarian. By now the world has seen that tight coupling between the data model and the presentation model is suboptimal. The success of RSS, REST, MVC, and web services in general shows this. Despite the WS in the name, WSRP stands against the core principles of Web services. The WSRP spec ignores the sound advice to keep data and presentation separate, and couples them tightly. WSRP promises integration, at the UI level. This seems like the wrong problem to be solving. It baffles me that this thing has lived as long as it has. The problem it attempts to solve is often not the problem that *should be* solved.
Web Services for Remote Portlets in C# / .NET -- Options?
[ "", "c#", ".net", "asp.net", "wcf", "wsrp", "" ]
I have a list of words and I want to filter it down so that I only have the nouns from that list of words (Using Java). To do this I am looking for an easy way to query a database of words for their type. My question is does anybody know of a free, easy word lookup API that would enable me to find the *class* of a word, not necessarily its semantic definition. Thanks! Ben. EDIT: By class of the word I meant 'part-of-speech' thanks for clearing this up
Word type? Such as verb, noun, adjective, etc? If so, you might run into the issue that some words can be used in more than one way. For example: "Can you trade me that card?", "That was a bad trade." See [this thread](https://stackoverflow.com/questions/216612/dictionary-api-or-library) for some suggestions. Have a look at [this](http://wordnetweb.princeton.edu/perl/webwn) as well, seems like it might do exactly what you're looking for.
I think what you are looking for is the part-of-speech (POS) of a word. In general that will not be possible to determine except in the context of a sentence. There are many words that have can several different potential parts of speech (e.g. 'bank' can be used as a verb or noun). You could use a POS tagger to get the information you want. However, the following part-of-speech taggers assume assume that you are tagging words within a well-structured English sentence... * The [OpenNLP](http://opennlp.sourceforge.net/) Java libraries are generally very good and released under the LGPL. There is a part-of-speech tagger for English and a few other languages included in the distribution. Just go to the project page to get the jar (and don't forget to download the models too). * There is also the [Stanford part-of-speech tagger](http://nlp.stanford.edu/software/tagger.shtml), written in Java under the GPL. I haven't had any direct experience with this library, but the Stanford NLP lab is generally pretty awesome.
Online (preferably) lookup API of a word's class
[ "", "java", "web-services", "nlp", "" ]
Is it possible to "self inject" an EJB in order to call local methods as bean methods? There are some cases where this could be favorable, for example if container managed transactions are used and something should be accomplished in a new transaction. An example how this could work: Foo.java: ``` @Local public interface FoO { public void doSomething(); public void processWithNewTransaction(); // this should actually be private } ``` FooBean.java: ``` @Stateless public class FooBean implements Foo { @EJB private Foo foo; public void doSomething() { ... foo.processWithNewTransaction(); ... } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void processWithNewTransaction() { ... } } ``` If I extract `processWithNewTransaction()` to another bean, it would need to be exposed as a public method in the interface, even though it should be called only by `FooBean`. (The same issue is with my code above, that's why there is a comment in the interface definition.) One solution would be to switch to bean managed transactions. However this would require changing the whole bean to manage its own transactions, and would add a lot of boiler plate to all methods.
**Update**: As noted by other answers, this is indeed technically possible. Please see the answers of [Csaba](https://stackoverflow.com/a/12255700/57601) and [Michael](https://stackoverflow.com/a/14172017/57601) on how and why it works despite the apparend endless recursion. --- I cannot give a 100% accurate answer but I'm pretty sure that this is not possible. I think so because for injecting the Foo bean into the Foo bean itself the container would initially have to create a Foo instance which he can inject afterwards. But to create this he has to inject an already existing instance of Foo into the Foo to be created... which leads to an infinite recursion. If you need separate transactions I'd suggest to keep things easy and create two independend beans/interfaces.
It is possible to do a `self injection`. You need to use `SessionContext`. ``` SessionContext sc = ... sc.getBusinessObject(FooBean.class).processWithNewTransaction() ```
Can an EJB3 bean "self inject" and call its own methods via EJB container?
[ "", "java", "ejb-3.0", "" ]
I want to connect a `BindingSource` to a list of class objects and then objects value to a ComboBox. Can anyone suggest how to do it? ``` public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country() { Cities = new List<City>(); } } ``` is my class and I want to bind its `name` field to a BindingSource which could be then associated with a ComboBox
As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a `BindingList`) ``` public class Country { public string Name { get; set; } public IList<City> Cities { get; set; } public Country(string _name) { Cities = new List<City>(); Name = _name; } } ``` ``` List<Country> countries = new List<Country> { new Country("UK"), new Country("Australia"), new Country("France") }; var bindingSource1 = new BindingSource(); bindingSource1.DataSource = countries; comboBox1.DataSource = bindingSource1.DataSource; comboBox1.DisplayMember = "Name"; comboBox1.ValueMember = "Name"; ``` To find the country selected in the bound combobox, you would do something like: `Country country = (Country)comboBox1.SelectedItem;`. If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the `DataSource` implements `IBindingList`; one such structure is `BindingList<T>`. --- Tip: make sure that you are binding the `DisplayMember` to a Property on the class and not a public field. If you class uses `public string Name { get; set; }` it will work but if it uses `public string Name;` it will not be able to access the value and instead will display the object type for each line in the combo box.
For a backgrounder, there are 2 ways to use a ComboBox/ListBox 1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country. 2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue For 2) you will need a list of countries first ``` // not tested, schematic: List<Country> countries = ...; ...; // fill comboBox1.DataSource = countries; comboBox1.DisplayMember="Name"; comboBox1.ValueMember="Cities"; ``` And then in the SelectionChanged, ``` if (comboBox1.Selecteditem != null) { comboBox2.DataSource=comboBox1.SelectedValue; } ```
How to bind a List to a ComboBox?
[ "", "c#", "winforms", "data-binding", "combobox", "" ]
I like using structs a lot. So after reading this [article](http://dotnetperls.com/Content/Struct-Examples.aspx), are there any other concerns I should have against using them all the time? ### See Also: > * [When should I use a struct instead of a class?](https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class) > * [When to use struct in C#?](https://stackoverflow.com/questions/521298/when-to-use-struct-in-c)
You should make the following considerations about structs: * structs should be immutable (mutable structs are not intuitive and unpredictable) * structs *always* have a default (public parameterless) constructor that cannot be changed * struct size should not exceed 16 bytes * the `Equals` and `GetHashCode` methods should be overriden for better performance * implementing the `IEquatable<T>` interface is recommended * redefining and `==` and the `!=` operators is also recommended
I almost *never* define custom structs. There just aren't that many natural value types around, IMO. In particular, I would think very, *very* carefully before defining a mutable struct, especially if it mutates via an interface implementation. Mutable structs behave in ways which people don't expect at all, leading to code which is hard to understand. I think it's worth reading ["Choosing Between Classes and Structures"](http://msdn.microsoft.com/en-us/library/ms229017.aspx) from ["Design Guidelines For Developing Class Libraries"](http://msdn.microsoft.com/en-us/library/ms229042.aspx). In particular: > Do not define a structure unless the > type has all of the following > characteristics: > > * It logically represents a single > value, similar to primitive types > (integer, double, and so on). > * It has an instance size smaller than > 16 bytes. > * It is immutable. > * It will not have to be boxed frequently. Do you really develop types with all of those characteristics frequently?
C# Struct usage tips?
[ "", "c#", "data-structures", "" ]
I'm doing a home project that started off really easy (doesn't that always happen?) and then took a nasty permissions turn. Basically, I have a home intranet and my PC is doing double-duty as the home web server. I'm running Vista, so we're talking IIS 7. In Visual Studio, this works perfectly. I have my homepage query Outlook (2007) and display the next couple appointments. I do this as so, ``` using Microsoft.Office.Interop.Outlook; //Be kind -- this is a work in progress public static string nextAppointment() { System.Text.StringBuilder returnString = new System.Text.StringBuilder(); try { Application outlookApp = new ApplicationClass(); NameSpace outlookNamespace = outlookApp.GetNamespace("MAPI"); MAPIFolder theAppts = outlookNamespace.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); List<AppointmentItem> todaysAppointments = new List<AppointmentItem>(); TimeSpan oneday = new TimeSpan(24, 0, 0); DateTime today = DateTime.Today; DateTime yesterday = today.Subtract(oneday); DateTime tomorrow = today.Add(oneday); foreach (AppointmentItem someAppt in theAppts.Items) { if (someAppt.Start > yesterday && someAppt.Start < tomorrow) { todaysAppointments.Add(someAppt); } } foreach (AppointmentItem todayAppts in todaysAppointments) { returnString.Append(todayAppts.Start.ToShortTimeString() + " -- " + todayAppts.Subject + "<br />"); } } catch (System.Exception ex) { //TO-DO: Add some real handling returnString.Append("Cannot access calendar"); } return returnString.ToString(); } ``` This code snippet is just a work in progress, but you get the idea. It looks to see what kind of calendar events I have within a 24 hr period and then adds them to a string that I eventually write-out on the webpage. When I debug this in Visual Studio, it runs great through the ASP.NET Development Studio. Feeling confident, I take the same code and run it on IIS for all at home to enjoy, and I get the error (when I don't catch my exception), > Retrieving the COM class factory for > component with CLSID > {0006F03A-0000-0000-C000-000000000046} > failed due to the following error: > 80070005. > > Description: An unhandled exception > occurred during the execution of the > current web request. Please review the > stack trace for more information about > the error and where it originated in > the code. > > Exception Details: > System.UnauthorizedAccessException: > Retrieving the COM class factory for > component with CLSID > {0006F03A-0000-0000-C000-000000000046} > failed due to the following error: > 80070005. > > ASP.NET is not authorized to access > the requested resource. Consider > granting access rights to the resource > to the ASP.NET request identity. > ASP.NET has a base process identity > (typically {MACHINE}\ASPNET on IIS 5 > or Network Service on IIS 6) that is > used if the application is not > impersonating. If the application is > impersonating via , the identity > will be the anonymous user (typically > IUSR\_MACHINENAME) or the authenticated > request user. > > To grant ASP.NET access to a file, > right-click the file in Explorer, > choose "Properties" and select the > Security tab. Click "Add" to add the > appropriate user or group. Highlight > the ASP.NET account, and check the > boxes for the desired access. I've tried altering permissions through Explorer on the site but no luck. Any ideas?
Ended up being something else entirely: 2 fold step -- (1) Enter identity credentials to impersonate either in web.config or through iis and (2) give write access to that same user in Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files Editing pool settings has no effect as it turns out. I can go back and put the pool under NetworkService and it doesn't matter. Thanks for your help! Much appreciated!! It definitely put me on the right track
Try running the web app's application pool under a user that has access (such as a domain user).
Cannot connect ASP.NET to Outlook in IIS, but can through Visual Studio
[ "", "c#", "iis", "permissions", "outlook", "" ]
For a brand new application, is it better to use WPF over Windows Forms? I used Windows Forms before but not much WPF. As far as I know, WPF is the successor to Windows Forms, right? The application is going to host DirectX Windows (not WPF 3D, but [Managed DirectX](http://en.wikipedia.org/wiki/Managed_DirectX) and [SlimDX](http://en.wikipedia.org/wiki/SlimDX)) with lots of custom controls. EDIT: The application is a 3D related application, editor, such as [modo](http://en.wikipedia.org/wiki/Modo_%28software%29): ![Image created using the 3D painting program modo.](https://i.stack.imgur.com/l6Gk3.jpg)
----EDIT 2 ----- Given that you're trying to make an editor like the one you showed, I'd recommend going WPF even more. My current project has many features along those lines, as well, and we've decided that the ability to composite WPF with Direct3D content is extremely powerful. It's nice to be able to render your scene into anything - not just a rectangular window. In WinForms, you pretty much were limited to one rectangle, and you had issues with airspace there, too (subtle, but things like flickering issues when menus pull over your hwnd, etc). The WPF compositor with D3DImage gets rid of all of those issues, and lets you use your imagination to construct a very flexible UI. Things like rendering your scene in realtime on the side of a WPF3D object are possible, or using WPF controls directly on top of your d3d scene instead of trying to do the GUI in D3D, etc. -----Original--------- If you're going to be hosting DX, you might want to consider it - especially since it gives you the ability to do scene composition with your UI and no airspace issues if you use [D3DImage](http://msdn.microsoft.com/en-us/library/system.windows.interop.d3dimage.aspx). This does work with SlimDX and WPF. ----EDIT----- For more information on the disadvantages of using Direct3D with Winforms, and the advantages of WPF/DX integration, see: [MSDN Article on Airspace](http://msdn.microsoft.com/en-us/library/aa970688.aspx) [Codeproject arcticle on intro to D3DImage](http://www.codeproject.com/KB/WPF/D3DImage.aspx)
We dealt with this question about 9 months ago. We decided to go with WPF and so far we're happy with the decision. Yes, there is a learning curve. It's fairly considerable especially coming from WinForms where you have so much to unlearn. I also recommend you have access to a designer otherwise your application will probably look a bit shabby. Also be prepared for some WPF gotchas that will have you spending hours scratching your head saying 'why was this so hard'. But WPF is a step ahead. The data binding, templating and complete control of how you want your windows to look makes you think that this how WinForms should've been originally. Oh yes, and be prepared to shell out a couple of dollars for some missing controls. There are a couple of things missing like a Date picker and having checkboxes on tree controls (you can actually template this out, but it's not as simple as winforms in that regard). 3.5 SP1 includes a grid control now, thankfully. I'm sure I'm missing a bunch more, but that's what I can come up with off the top of my head. Good luck!
Is it better to use WPF over Windows Forms?
[ "", "c#", ".net", "wpf", "winforms", "user-interface", "" ]
I've got a table in a mysql database that contains monetary transactions. Let's say the tabled is called *transactions*: ``` id int, to_user int, from_user int, created datetime, amount double ``` I'm trying to create a query that returns the average amount of a transaction grouped by the number of transactions that appear per day. The applicable columns are amount and created. So I'm trying to answer the question: what is the average amount of transactions that occur on days where there are between 0 and 2 transactions, between 2 and 4 transactions, between 4 and 6 transactions, etc. Any ideas?
``` SELECT AVG(`num`), ((`num` - 1) DIV 2) * 2 AS `tier` FROM ( SELECT DATE_FORMAT(`created`, '%Y-%m-%d') AS `day`, COUNT(*) AS `num` FROM `yourtable` GROUP BY 1 ) AS `src` GROUP BY `tier` ```
After several misunderstandings I finally seem to get what you need :) ``` SELECT cnt_range * 2 AS days_range, CASE WHEN SUM(trans_cnt) > 0 THEN SUM(trans_sum) / SUM(trans_cnt) ELSE 0 END AS average_amount FROM ( SELECT SUM(amount) AS trans_sum, COUNT(*) AS trans_cnt, FLOOR(COUNT(*) / 2) AS cnt_range FROM transactions GROUP BY TO_DATE(created) ) ao GROUP BY cnt_range ```
SQL Query for Summary By Instances Per Day
[ "", "sql", "mysql", "" ]
I know that C++ has the concept of objects but C doesn't. I also know that pretty much all there is to know about C fits into [K & R](https://rads.stackoverflow.com/amzn/click/com/0131103628) but the C++ library is vastly more complex. There have got to be other big differences though. What are the major differences between C and C++?
Check out Stroustrup's FAQ [here](http://www.research.att.com/~bs/bs_faq.html#difference), specifically: **What is the difference between C and C++?** > C++ is a direct descendant of C that > retains almost all of C as a subset. > C++ provides stronger type checking > than C and directly supports a wider > range of programming styles than C. > C++ is "a better C" in the sense that > it supports the styles of programming > done using C with better type checking > and more notational support (without > loss of efficiency). In the same > sense, ANSI C is a better C than K&R > C. In addition, C++ supports data > abstraction, object-oriented > programming, and generic programming > (see The C++ Programming Language (3rd > Edition)"; Appendix B discussing > compatibility issues is available for > downloading).
The C++ language says they are the same: ``` int C = 0; assert(C++ == C); ```
What's the difference between C and C++
[ "", "c++", "c", "" ]
I am trying to find a way to know about garbage collection. Either, when it has started, finished or is in process. I really just need some event connected to the collection itself (I think). My issue is that I have a WeakEventManager (written from scratch) and I have cleanup methods that delete and WeakReferences that are no longer alive (WeakReferences are in a Dictionary). The issue is that I have to know when it is time to "clean up". It would be nice to cleanup when the collector is doing its thing. Even if it is after the garbage collection, at least the next collection will remove these old objects.
Here's the class I used to log to SmartInspect that GC has occured. You should easily be able to change what this class does. To get it started, simply call `GCLog.Register();`. ``` #region File Header // This file Copyright © 2007 Lasse Vågsæther Karlsen, All rights reserved. // // $Id: GCLog.cs 135 2008-05-28 11:28:37Z lassevk $ #endregion #region Using using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Gurock.SmartInspect; #endregion namespace PresentationMode { /// <summary> /// This class is used to get a running log of the number of garbage collections that occur, /// when running with logging. /// </summary> public sealed class GCLog { #region Construction & Destruction /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="GCLog"/> is reclaimed by garbage collection. /// </summary> ~GCLog() { SiAuto.Main.LogMessage("GARBAGE COLLECTED"); if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && !Environment.HasShutdownStarted) new GCLog(); } #endregion #region Public Static Methods /// <summary> /// Registers this instance. /// </summary> public static void Register() { #if DEBUG if (SiAuto.Si.Enabled) new GCLog(); #endif } #endregion } } ```
The System.GC class offers a RegisterForFullGCNotification method which will allow notifications to be raised when garbage collection is about to be done, and when it's been completed. It's not ideal, as there are a few caveats to using this method, such as concurrent garbage collection must be disabled for this method to work. Please see the following links for full info: [Garbage Collection Notifications](http://msdn.microsoft.com/en-us/library/cc713687.aspx) [GC.RegisterForFullGCNotification Method](http://msdn.microsoft.com/en-us/library/system.gc.registerforfullgcnotification.aspx)
Are there any events that tell an application when garbage collection has occurred?
[ "", "c#", "events", "garbage-collection", "" ]
i would like to insert custom javascript to the head of the page all i have is this HTMLDocumentClass object, does anyone know how to do that? are there any security restrictions??? can i change ids of elemnts that came with the page??
There is no way directly in .NET to set a script element in the document head. As a workaround you could reference the mshtml.dll and use the IHTMLDocument2 interface. Also, you could also just use a wrapper class to expose the functionality you require. (i.e. the Text or src properties of the script element so you can set you script code). Then you just need a method that implements the custom wrapper interface. Something as shown below... ``` using System.Runtime.CompilerServices; using System.Runtime.InteropServices; /// <summary> /// A COM interface is needed because .NET does not provide a way /// to set the properties of a HTML script element. /// This class negates the need to refrence mshtml in its entirety /// </summary> [ComImport, Guid("3050F536-98B5-11CF-BB82-00AA00BDCE0B"), InterfaceType((short)2), TypeLibType((short)0x4112)] public interface IHTMLScriptElement { /// <summary> /// Sets the text property /// </summary> [DispId(1006)] string Text { [param: MarshalAs(UnmanagedType.BStr)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-2147417085)] set; } /// <summary> /// Sets the src property /// </summary> [DispId(1001)] string Src { [param: MarshalAs(UnmanagedType.BStr)] [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(-1001)] set; } } // Inject script element public static void InjectJavascript(string javascript, HTMLDocument doc) { if (doc != null) { try { // find the opening head tag HtmlElement head = doc.GetElementsByTagName("head")[0]; // create the script element HtmlElement script = doc.CreateElement("script"); // set it to javascirpt script.SetAttribute("type", "text/javascript"); // cast the element to our custom interface IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement; // add the script code to the element element.Text = "/* <![CDATA[ */ " + javascript + " /* ]]> */"; // add the element to the document head.AppendChild(script); } catch (Exception e) { MessageBox.show(e.message); } } } ``` You would use it like this, where myDoc is your html document... ``` InjectJavascript("function foo(bar) { alert(bar); }", myDoc); // inject the 'foo' function ``` and test it like this... ``` myDoc.InvokeScript("foo", new object[] { "Hello!" }); // alerts 'hello!' ```
Use the HTMLDocument::Window property to get the HTMLWindow class, the use the HTMLWindow::DomWindow property to get the native IE interface. Then call IHTMLWindow2::execScript. <http://msdn.microsoft.com/en-us/library/aa741364(VS.85).aspx>
Insert some java script using HTMLDocumentClass
[ "", "c#", "html", "xml", "" ]
Here is my scenario, I have query that returns a lot of fields. One of the fields is called ID and I want to group by ID and show a count in descending order. However, since I am bringing back more fields, it becomes harder to show a true count because I have to group by those other fields. Here is an example of what I am trying to do. If I just have 2 fields (ID, color) and I group by color, I may end up with something like this: ID COLOR COUNT == ===== ===== 2    red     10 3    blue     5 4    green   24 Lets say I add another field which is actually the same person, but they have a different spelling of their name which throws the count off, so I might have something like this: ID COLOR NAME COUNT == ===== ====== ===== 2    Red    Jim      5 2    Red    Jimmy      5 3    Red    Bob      3 3    Red    Robert      2 4    Red    Johnny      12 4    Red    John      12 I want to be able to bring back ID, Color, Name, and Count, but display the counts like in the first table. Is there a way to do this using the ID?
If you want a single result set, you would have to omit the name, as in your first post ``` SELECT Id, Color, COUNT(*) FROM YourTable GROUP By Id, Color ``` Now, you could get your desired functionality with a subquery, although not elegant ``` SELECT Id, Color Name, (SELECT COUNT(*) FROM YourTable Where Id = O.Id AND Color = O.Color ) AS "Count" FROM YourTable O GROUP BY Id, Color, Name ``` This should work as you desire
Try this:- ``` SELECT DISTINCT a.ID, a.Color, a.Name, b.Count FROM yourTable INNER JOIN ( SELECT ID, Color, Count(1) [Count] FROM yourTable GROUP BY ID, Color ) b ON a.ID = b.ID, a.Color = b.Color ORDER BY [Count] DESC ```
How to get a proper count in sql server when retrieving a lot of fields?
[ "", "sql", "sql-server", "t-sql", "" ]
Can anyone explain `IEnumerable` and `IEnumerator` to me? For example, when to use it over foreach? what's the difference between `IEnumerable` and `IEnumerator`? Why do we need to use it?
> for example, when to use it over foreach? You don't use `IEnumerable` "over" `foreach`. Implementing `IEnumerable` makes using `foreach` *possible*. When you write code like: ``` foreach (Foo bar in baz) { ... } ``` it's functionally equivalent to writing: ``` IEnumerator bat = baz.GetEnumerator(); while (bat.MoveNext()) { Foo bar = (Foo)bat.Current; ... } ``` By "functionally equivalent," I mean that's actually what the compiler turns the code into. You can't use `foreach` on `baz` in this example *unless* `baz` implements `IEnumerable`. `IEnumerable` means that `baz` implements the method ``` IEnumerator GetEnumerator() ``` The `IEnumerator` object that this method returns must implement the methods ``` bool MoveNext() ``` and ``` Object Current() ``` The first method advances to the next object in the `IEnumerable` object that created the enumerator, returning `false` if it's done, and the second returns the current object. Anything in .NET that you can iterate over implements `IEnumerable`. If you're building your own class, and it doesn't already inherit from a class that implements `IEnumerable`, you can make your class usable in `foreach` statements by implementing `IEnumerable` (and by creating an enumerator class that its new `GetEnumerator` method will return).
**The IEnumerable and IEnumerator Interfaces** To begin examining the process of implementing existing .NET interfaces, let’s first look at the role of IEnumerable and IEnumerator. Recall that C# supports a keyword named foreach that allows you to iterate over the contents of any array type: ``` // Iterate over an array of items. int[] myArrayOfInts = {10, 20, 30, 40}; foreach(int i in myArrayOfInts) { Console.WriteLine(i); } ``` While it might seem that only array types can make use of this construct, the truth of the matter is any type supporting a method named GetEnumerator() can be evaluated by the foreach construct.To illustrate, follow me! Suppose we have a Garage class: ``` // Garage contains a set of Car objects. public class Garage { private Car[] carArray = new Car[4]; // Fill with some Car objects upon startup. public Garage() { carArray[0] = new Car("Rusty", 30); carArray[1] = new Car("Clunker", 55); carArray[2] = new Car("Zippy", 30); carArray[3] = new Car("Fred", 30); } } ``` Ideally, it would be convenient to iterate over the Garage object’s subitems using the foreach construct, just like an array of data values: ``` // This seems reasonable ... public class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with IEnumerable / IEnumerator *****\n"); Garage carLot = new Garage(); // Hand over each car in the collection? foreach (Car c in carLot) { Console.WriteLine("{0} is going {1} MPH", c.PetName, c.CurrentSpeed); } Console.ReadLine(); } } ``` Sadly, the compiler informs you that the Garage class does not implement a method named GetEnumerator(). This method is formalized by the IEnumerable interface, which is found lurking within the System.Collections namespace. Classes or structures that support this behavior advertise that they are able to expose contained subitems to the caller (in this example, the foreach keyword itself). Here is the definition of this standard .NET interface: ``` // This interface informs the caller // that the object's subitems can be enumerated. public interface IEnumerable { IEnumerator GetEnumerator(); } ``` As you can see, the GetEnumerator() method returns a reference to yet another interface named System.Collections.IEnumerator. This interface provides the infrastructure to allow the caller to traverse the internal objects contained by the IEnumerable-compatible container: ``` // This interface allows the caller to // obtain a container's subitems. public interface IEnumerator { bool MoveNext (); // Advance the internal position of the cursor. object Current { get;} // Get the current item (read-only property). void Reset (); // Reset the cursor before the first member. } ``` If you want to update the Garage type to support these interfaces, you could take the long road and implement each method manually. While you are certainly free to provide customized versions of GetEnumerator(), MoveNext(), Current, and Reset(), there is a simpler way. As the System.Array type (as well as many other collection classes) already implements IEnumerable and IEnumerator, you can simply delegate the request to the System.Array as follows: ``` using System.Collections; ... public class Garage : IEnumerable { // System.Array already implements IEnumerator! private Car[] carArray = new Car[4]; public Garage() { carArray[0] = new Car("FeeFee", 200); carArray[1] = new Car("Clunker", 90); carArray[2] = new Car("Zippy", 30); carArray[3] = new Car("Fred", 30); } public IEnumerator GetEnumerator() { // Return the array object's IEnumerator. return carArray.GetEnumerator(); } } ``` After you have updated your Garage type, you can safely use the type within the C# foreach construct. Furthermore, given that the GetEnumerator() method has been defined publicly, the object user could also interact with the IEnumerator type: ``` // Manually work with IEnumerator. IEnumerator i = carLot.GetEnumerator(); i.MoveNext(); Car myCar = (Car)i.Current; Console.WriteLine("{0} is going {1} MPH", myCar.PetName, myCar.CurrentSpeed); ``` However, if you prefer to hide the functionality of IEnumerable from the object level, simply make use of explicit interface implementation: ``` IEnumerator IEnumerable.GetEnumerator() { // Return the array object's IEnumerator. return carArray.GetEnumerator(); } ``` By doing so, the casual object user will not find the Garage’s GetEnumerator() method, while the foreach construct will obtain the interface in the background when necessary. Adapted from the [Pro C# 5.0 and the .NET 4.5 Framework](http://www.apress.com/9781430242338)
Can anyone explain IEnumerable and IEnumerator to me?
[ "", "c#", "ienumerable", "ienumerator", "" ]
I have a legacy Oracle (10.2g) database that I'm connecting to and I'd like to use NHibernate (2.0.1) to give me back objects from a stored procedure. The stored procedure in question uses a SYS\_REFCURSOR to return results. According to the [documentation](http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/querysql.html#querysql-limits-storedprocedures) this should be doable but I've found a [few](http://forum.hibernate.org/viewtopic.php?p=2398761) [posts](http://groups.google.com/group/nhusers/browse_thread/thread/1e5c71502dd547f0/a7908ea36bed6a5e) on the internet that suggest otherwise. Here's my paraphrased code: Mapping file: ``` <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="OracleStoredProcedures" namespace="OracleStoredProcedures"> <class name="Person" mutable="false"> <id name="PersonCode" type="AnsiString" column="PERSONCODE"> <generator class="assigned" /> </id> <property name="Name" type="String" column="PERSON_NAME" /> <property name="Surname" type="String" column="PERSON_SURNAME" /> </class> <sql-query name="getpeople"> <return class="Person" /> EXEC RS_DB.GETPERSONTEST </sql-query> </hibernate-mapping> ``` Stored procedure: ``` CREATE OR REPLACE PROCEDURE RS_DB.GETPERSONTEST ( io_cursor IN OUT sys_refcursor ) IS BEGIN OPEN io_cursor FOR SELECT PERSONCODE, PERSON_NAME, PERSON_SURNAME FROM PEOPLE END GETPERSONTEST; ```
As far as I remember this was a bug I also found a couple of years ago when working with oracle, I've tracked back the issue in NH tracker and is fixed but on version 2.1.1GA; Can you verify that this is the same problem you have? <https://nhibernate.jira.com/browse/NH-847>
What a royal pain this was. This finally worked. I turned the store procedure into a function. Function returned sys\_refcursor. Used similar mapping as the OP and name query as below. ``` <sql-query name="getpeople"> <return class="Person" /> { ? = call RS_DB.GETPERSONTEST } </sql-query> ``` [Link](http://nhibernate.svn.sourceforge.net/viewvc/nhibernate/trunk/nhibernate/src/NHibernate.Test/SqlTest/Custom/Oracle/StoredProcedures.hbm.xml?view=markup)
Oracle stored procedures, SYS_REFCURSOR and NHibernate
[ "", "c#", "oracle", "nhibernate", "stored-procedures", "" ]