Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a user control that I'm building. It's purpose is to display the status of a class to the user. Obviously, this does not matter, and will slow things down when the control runs in the IDE, as it does as soon as you add it to a form. One way to work around this would be to have the control created and added to the controls collection of the form at run-time. But this seems less than perfect. Is there a way to set a flag in the control so that it can skip certain sections of code based on how it is running? p.s. I'm using C# and VS 2008
``` public static bool IsInRuntimeMode( IComponent component ) { bool ret = IsInDesignMode( component ); return !ret; } public static bool IsInDesignMode( IComponent component ) { bool ret = false; if ( null != component ) { ISite site = component.Site; if ( null != site ) { ret = site.DesignMode; } else if ( component is System.Windows.Forms.Control ) { IComponent parent = ( (System.Windows.Forms.Control)component ).Parent; ret = IsInDesignMode( parent ); } } return ret; } ```
I found this answer on another post and it seems to be easier and working better for my situation. [Detecting design mode from a Control's constructor](https://stackoverflow.com/questions/1166226/detecting-design-mode-from-a-controls-constructor) ``` using System.ComponentModel; if (LicenseManager.UsageMode == LicenseUsageMode.Runtime) { } ```
How can I detect whether a user control is running in the IDE, in debug mode, or in the released EXE?
[ "", "c#", "ide", "user-controls", "" ]
I have put together a script which is very much like the flickr photostream feature. Two thumbnails next to each other, and when you click the next or prev links the next (or previous) two images slide in. Cool! Currently when the page loads it loads the two images. The first time nxt / prv is used then the next two images or previous two are loaded via ajax, with the id of the first image being passed in the url and the HTML for the two new images returned and displayed via ajax. simple enough, but it got me to thinking, on a slow connection, or heavy server load then the two images, although relatively small thumbnails could still take a while to load, and the nice things with sliding panes is the fact that the hidden data slides in quickly and smoothly preferbly without a loading delay. So I was wondering from a performance and good practice point of view which option is best, this is what I can think of for now, open to suggestions. 1, call each set of images via JSON (its supposed to be fast?) 2,load all the possible images into a json file and pull in the details that way - although browser will still have to load image. Plus sometimes there might be 4 images, other times there could be upto 1000! 3, Load 10 images via php into a Json or other file, and load all 10 images into the browser hiding the 8 which are not on show, and always showing the middle two. Problem here is that each time someone clicks, the file has to reload the first and last images, which still takes up time, although i suppose the middle images will have all been cached via the browser by now though. But still there is a loading time. 4, Is it possible to have a json image with all the image details (regardless of numbers) and use no 3 above to load 10 of those images, is it possible to use ajax to only read 10 lines and keep a pointer of the last one it read, so the json file can be loaded fast, short refresh and images either side are cached via the browser!! Hope thats clear, any suggestions on how you would handle this?
To preload an image from Javascript, you don't need to do anything that sounds like AJAX or JSON. All you need is this: ``` var img = new Image(); img.src = "http://example.com/new/image.jpg"; ``` The browser will quite happily load the image in the background, even though it's not displayed anywhere. Then, when you update the `src` field of another (displayed) image tag, the browser will immediately show the part of the image it's already loaded (hopefully all of it).
Fetching JSON Via Ajax will just slow you down. You're better off using inline JSON and generated Javascript. ``` <?php $images = array( "foo.jpg","bar.jpg" ); ?> <script type="text/javascript"> jQuery(function($){ var images = ( <?php echo json_encode($images); ?> ); /* Creating A Hidden box to preload the images into */ var imgbox = document.createElement("div"); $(imgbox).css({display: 'none'}); /* Possible Alternative trick */ /* $(imgbox).css({height:1px; width: 1px; overflow: hidden;}); */ $('body').append(imgbox); $.each( images , function( ind, item ) { #Injecting images into the bottom hidden div. var img = document.createElement("img"); $(img).src("/some/prefix/" + item ); $(imgbox).append(img); }); }); </script> ```
php/Ajax - Best practice for pre-loading images
[ "", "php", "ajax", "json", "performance", "loading", "" ]
Is it possible to create a multithreading application in VC6 with boost library? If it is possible, what are some relevant tutorials.
Yes, I have done this successfully, but with Boost v1.30.0. So if you have trouble with the latest versions of the Boost libraries, you might want to go back a year or five. I recall I started getting all sorts of internal compiler errors, *et al.*, when trying to upgrade Boost -- so I didn't, but rather went on using v1.30.0 until I was able to upgrade Visual C++ as well. Even the old versions of Boost are very stable and useful, they just have less features.
<http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html>
Creating a multithreading application in vc6 with boost library?
[ "", "c++", "visual-c++-6", "boost-thread", "" ]
Is it possible, or does anyone know the best way to capture MSN chats? I was thinking about attaching to the MSN process, and messing about searching for static addresses for conversations, to capture them. (This is all on the windows platform using c++)
It would probably be easiest to sniff packets on the ports known to be used by MSN. That has the added benefit of working with clients other than the Microsoft one (such as Pidgin).
Assuming the protocol is unencrypted, it would probably be easier to attach to the process and intercept the network traffic than to search all of the application memory for chats. But that's no small task, either.
Capturing MSN Chat via Memory
[ "", "c++", "chat", "capture", "msn", "" ]
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? **UPDATE** This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido van Rossum an email cause I really wanted to know the differences in these methods. ### My email: > There are at least 3 ways to do a square root in Python: math.sqrt, the > '\*\*' operator and pow(x,.5). I'm just curious as to the differences in > the implementation of each of these. When it comes to efficiency which > is better? ### His response: > pow and \*\* are equivalent; math.sqrt doesn't work for complex numbers, > and links to the C sqrt() function. As to which one is > faster, I have no idea...
**`math.sqrt(x)` is significantly faster than `x**0.5`.** ``` import math N = 1000000 ``` ``` %%timeit for i in range(N): z=i**.5 ``` > 10 loops, best of 3: 156 ms per loop ``` %%timeit for i in range(N): z=math.sqrt(i) ``` > 10 loops, best of 3: 91.1 ms per loop Using Python 3.6.9 ([notebook](https://colab.research.google.com/drive/1HWHl3g5erXogBu68mVB00IEYdE7NU09r?usp=sharing)).
* first rule of optimization: *don't do it* * second rule: *don't do it*, yet Here's some timings (Python 2.5.2, Windows): ``` $ python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 1000000 loops, best of 3: 0.445 usec per loop $ python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 1000000 loops, best of 3: 0.574 usec per loop $ python -mtimeit -s"import math; x = 123" "math.sqrt(x)" 1000000 loops, best of 3: 0.727 usec per loop ``` This test shows that `x**.5` is slightly faster than `sqrt(x)`. For the Python 3.0 the result is the opposite: ``` $ \Python30\python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 1000000 loops, best of 3: 0.803 usec per loop $ \Python30\python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 1000000 loops, best of 3: 0.695 usec per loop $ \Python30\python -mtimeit -s"import math; x = 123" "math.sqrt(x)" 1000000 loops, best of 3: 0.761 usec per loop ``` `math.sqrt(x)` is always faster than `x**.5` on another machine (Ubuntu, Python 2.6 and 3.1): ``` $ python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 10000000 loops, best of 3: 0.173 usec per loop $ python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 10000000 loops, best of 3: 0.115 usec per loop $ python -mtimeit -s"import math; x = 123" "math.sqrt(x)" 10000000 loops, best of 3: 0.158 usec per loop $ python3.1 -mtimeit -s"from math import sqrt; x = 123" "x**.5" 10000000 loops, best of 3: 0.194 usec per loop $ python3.1 -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 10000000 loops, best of 3: 0.123 usec per loop $ python3.1 -mtimeit -s"import math; x = 123" "math.sqrt(x)" 10000000 loops, best of 3: 0.157 usec per loop ```
Which is faster in Python: x**.5 or math.sqrt(x)?
[ "", "python", "performance", "" ]
What would be the best way to display & program simple game board (say chess, checkers and such) in C#? In terms of controls and underlying game logic. An idea that came to my mind was to use **Picture Box** (or class inheriting from it) with Board & Field classes. * Is that a decent solution after all? * How would I separate graphics from game logic using this solution (I believe Board & Field classes may not be enough)? * Is PictureBox efficient enough for such purpose? Googling some also brought me to solutions using button/label for each game field. But back to Board, Field and PictureBox. Extendability - designing it properly would easily allow to implement any other board game (or even card game) as it's all about board with modifiable fields after all.
In an object-oriented approach, think about the objects involved in your game (e.g. the board, the pieces) … let them each provide a drawing method that takes a `Graphics` object and draws itself on it. The drawing itself could be done on a `PictureBox` – this is the ideal control for such purpose – but this isn't really all that important because once your drawing logic is in place, it won't depend on the kind of control. In general, *don't* use workarounds with different controls. These might be nice for a conventional GUI. Not so much for games (or any kind of graphics-heavy application).
From data structure perspective take a look at the bitboard datastructure. <http://en.wikipedia.org/wiki/Bitboard>
Best way to display & program game board?
[ "", "c#", "" ]
I'm trying to figure out if there's a reasonably efficient way to perform a lookup in a dictionary (or a hash, or a map, or whatever your favorite language calls it) where the keys are regular expressions and strings are looked up against the set of keys. For example (in Python syntax): ``` >>> regex_dict = { re.compile(r'foo.') : 12, re.compile(r'^FileN.*$') : 35 } >>> regex_dict['food'] 12 >>> regex_dict['foot in my mouth'] 12 >>> regex_dict['FileNotFoundException: file.x does not exist'] 35 ``` (Obviously the above example won't work as written in Python, but that's the sort of thing I'd like to be able to do.) I can think of a naive way to implement this, in which I iterate over all of the keys in the dictionary and try to match the passed in string against them, but then I lose the O(1) lookup time of a hash map and instead have O(n), where n is the number of keys in my dictionary. This is potentially a big deal, as I expect this dictionary to grow very large, and I will need to search it over and over again (actually I'll need to iterate over it for every line I read in a text file, and the files can be hundreds of megabytes in size). Is there a way to accomplish this, without resorting to O(n) efficiency? Alternatively, if you know of a way to accomplish this sort of a lookup in a database, that would be great, too. (Any programming language is fine -- I'm using Python, but I'm more interested in the data structures and algorithms here.) Someone pointed out that more than one match is possible, and that's absolutely correct. Ideally in this situation I'd like to return a list or tuple containing all of the matches. I'd settle for the first match, though. I can't see O(1) being possible in that scenario; I'd settle for anything less than O(n), though. Also, the underlying data structure could be anything, but the basic behavior I'd like is what I've written above: lookup a string, and return the value(s) that match the regular expression keys.
What you want to do is very similar to what is supported by xrdb. They only support a fairly minimal notion of globbing however. Internally you can implement a larger family of regular languages than theirs by storing your regular expressions as a character trie. * single characters just become trie nodes. * .'s become wildcard insertions covering all children of the current trie node. * \*'s become back links in the trie to node at the start of the previous item. * [a-z] ranges insert the same subsequent child nodes repeatedly under each of the characters in the range. With care, while inserts/updates may be somewhat expensive the search can be linear in the size of the string. With some placeholder stuff the common combinatorial explosion cases can be kept under control. * (foo)|(bar) nodes become multiple insertions This doesn't handle regexes that occur at arbitrary points in the string, but that can be modeled by wrapping your regex with .\* on either side. Perl has a couple of Text::Trie -like modules you can raid for ideas. (Heck I think I even wrote one of them way back when)
This is definitely possible, as long as you're using 'real' regular expressions. A textbook regular expression is something that can be recognized by a [deterministic finite state machine](http://en.wikipedia.org/wiki/Deterministic_finite_state_machine), which primarily means you can't have back-references in there. There's a property of regular languages that "the union of two regular languages is regular", meaning that you can recognize an arbitrary number of regular expressions at once with a single state machine. The state machine runs in O(1) time with respect to the number of expressions (it runs in O(n) time with respect to the length of the input string, but hash tables do too). Once the state machine completes you'll know which expressions matched, and from there it's easy to look up values in O(1) time.
Hashtable/dictionary/map lookup with regular expressions
[ "", "python", "regex", "dictionary", "hash", "" ]
I'd like to create a popup dialog box in silverlight in which i can manipulate controls, enter data, and return a value. I want it to be modal, so that when it is open, the page "Below" is inaccessible. I havent found an easy way to do this yet. Any suggestions?
I know the question asked for a Silverlight 2 solution but in Silverlight 3 (Beta now, RTW in July 2009) there is a built-in ChildWindow that can do everything you're looking for.
I haven't found a perfect solution either. The closest I have seen is this: [Using Popup to create a Dialog class](http://blogs.msdn.com/devdave/archive/2008/06/08/using-popup-to-create-a-dialog-class.aspx) If it is ok to be non-modal, you can try this tip using HtmlPage.PopupWindow(). [How to Popup a Browser Window](http://silverlight.net/blogs/msnow/archive/2008/09/30/silverlight-tip-of-the-day-52-how-to-popup-a-browser-window.aspx)
How do I create a Popup Dialog box in Silverlight?
[ "", "c#", ".net", "silverlight", "silverlight-2.0", "" ]
Published Date returned from Twitter Search API Atom Feed as 2008-11-03T21:30:06Z which needs to be converted to "X seconds/minutes/hours/days ago" for showing how long ago twitter messages were posted. Think this can be done with php date() function using DATE\_ATOM value?
``` function time_since($your_timestamp) { $unix_timestamp = strtotime($your_timestamp); $seconds = time() - $unix_timestamp; $minutes = 0; $hours = 0; $days = 0; $weeks = 0; $months = 0; $years = 0; if ( $seconds == 0 ) $seconds = 1; if ( $seconds> 60 ) { $minutes = $seconds/60; } else { return add_s($seconds,'second'); } if ( $minutes >= 60 ) { $hours = $minutes/60; } else { return add_s($minutes,'minute'); } if ( $hours >= 24) { $days = $hours/24; } else { return add_s($hours,'hour'); } if ( $days >= 7 ) { $weeks = $days/7; } else { return add_s($days,'day'); } if ( $weeks >= 4 ) { $months = $weeks/4; } else { return add_s($weeks,'week'); } if ( $months>= 12 ) { $years = $months/12; return add_s($years,'year'); } else { return add_s($months,'month'); } } function add_s($num,$word) { $num = floor($num); if ( $num == 1 ) { return $num.' '.$word.' ago'; } else { return $num.' '.$word.'s ago'; } } echo time_since('2008-11-03T21:30:06Z'); ```
[strtotime](https://www.php.net/strtotime) will handle that date format, giving you a unix timestamp. You can then follow the algorithms on [How do I calculate relative time?](https://stackoverflow.com/questions/11/how-do-i-calculate-relative-time) to get your result.
PHP Convert HTML Formatted Date
[ "", "php", "date", "atom-feed", "" ]
How can I create a regex for a string such as this: ``` <SERVER> <SERVERKEY> <COMMAND> <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH> <LOGTO> <OPTIONAL-MAXSIZE> <OPTIONAL-OFFSET> ``` Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended. Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file. The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset. Heres some examples: ``` loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 ``` Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath. Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't. Heres my regex: ``` ^(\s+)?(?P<SRCHOST>.+)(\s+)(?P<SRCKEY>.+)(\s+)(?P<COMMAND>COPY)(\s+)(?P<SRCDIR>.+)(\s+)(?P<RETENTION>\d+)(\s+)(?P<TRANSFER_MODE>BIN|ASC|BINARY|ASCII)(\s+)(?P<DSTDIR>.+)(\s+)(?P<LOGFILE>.+)(\s+)?(?P<SIZE>\d+)?(\s+)?(?P<OFFSET>\d+)?$ ```
Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work. Some assumptions I had in mind: * `SERVER`, `SERVERKEY` and `COMMAND` not containing any spaces: `\S+` * `FOLDERPATH` beginning with a slash: `/.*?` * `RETENTION` being a number: `\d+` * `TRANSFERMODE` not containing any spaces: `\S+` * `OUTPUTPATH` beginning with a drive and ending with a slash: `[A-Z]:\\.*?\\` * `LOGTO` either being the word "`NO`", or a path beginning with a drive: `[A-Z]:\\.*?` * `MAXSIZE` and `OFFSET` being a number: `\d+` Putting it all together: ``` ^\s* (?P<SERVER>\S+)\s+ (?P<SERVERKEY>\S+)\s+ (?P<COMMAND>\S+)\s+ (?P<FOLDERPATH>/.*?)\s+ # Slash not that important, but should start with non-whitespace (?P<RETENTION>\d+)\s+ (?P<TRANSFERMODE>\S+)\s+ (?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+ # Could also support network paths (?P<LOGTO>NO|[A-Z]:\\.*?) (?: \s+(?P<MAXSIZE>\d+) (?: \s+(?P<OFFSET>\d+) )? )? \s*$ ``` In one line: ``` ^\s*(?P<SERVER>\S+)\s+(?P<SERVERKEY>\S+)\s+(?P<COMMAND>\S+)\s+(?P<FOLDERPATH>/.*?)\s+(?P<RETENTION>\d+)\s+(?P<TRANSFERMODE>\S+)\s+(?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+(?P<LOGTO>NO|[A-Z]:\\.*?)(?:\s+(?P<MAXSIZE>\d+)(?:\s+(?P<OFFSET>\d+))?)?\s*$ ``` Testing: ``` >>> import re >>> p = re.compile(r'^(?P<SERVER>\S+)\s+(?P<SERVERKEY>\S+)\s+(?P<COMMAND>\S+)\s+(?P<FOLDERPATH>/.*?)\s+(?P<RETENTION>\d+)\s+(?P<TRANSFERMODE>\S+)\s+(?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+(?P<LOGTO>NO|[A-Z]:\\.*?)(?:\s+(?P<MAXSIZE>\d+)(?:\s+(?P<OFFSET>\d+))?)?\s*$',re.M) >>> data = r"""loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 ... loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 ... loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256""" >>> import pprint >>> for match in p.finditer(data): ... print pprint.pprint(match.groupdict()) ... {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': '300', 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/hats*', 'LOGTO': 'C:\\log\\love.log', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\no\\', 'RETENTION': '300', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'ascii'} >>> ```
The problem is that because you're allowing spaces in filenames and using spaces to separate fields, the solution is ambiguous. You either need to use a different field separator character that can't appear in filenames, or use some other method of representing filenames with spaces in them, e.g. putting them in quotation marks.
How do I process a string such as this using regular expressions?
[ "", "python", "regex", "" ]
I've got to write few words about C#, generally piece of cake? No! I've searched through various internet resources and books and what i got is kind of headache. For example **Garbage Collector** some sources says that this is C# feature, other that CLR got this feature and C# along with all other .NET languages got it by default. Ofcourse, my vote on CLR but there are lot other things that bring confusion, like **avoiding explicit code conversions**. Maybe i've got bad books and resources... so maybe someone would suggest some place where in clear way is said about C# Second thing are origins of C# syntax, again few choices and nothing clear, other language combo by each other author. C, c++, Java, that's ok but VB6 and Delphi, i have doubts. And again features origin from these languages is mixed up with c# but in fact it is not clear if it is C# or CLR feature MTH
GC is provided by the CLR C# is everything that the language spec states, and no more. Some of the more-interesting things that are actually C# features: * iterator blocks [yield return] * anonymous methods / closures / lambdas [the syntax, not to be confused with expression trees] But anything that relates to the code you type, but which isn't directly provided by either the CLR or the framework is a language feature. Other languages may implement them too, of course... * using [try/finally/Dispose] * lock [Monitor.Enter/try/finally/Monitor.Exit] * foreach [GetEnumerator()/while/[Dispose]] * extension method resolution * query syntax ["where pred" to .Where(x=>pred) etc] (these are just a few examples of course; and again - other languages are at liberty to also provide these features!)
The GC itself is a CLR feature, but the C# language assumes that it's running on a platform with garbage collection - without defining the exact semantics. It's a tough thing to pin down precisely, but a rough rule of thumb is "if it's well defined in the language specification, it's a C# feature." If you could give some more examples of *features* to categorise ("avoiding explicit code conversions" isn't a language feature, unless you want to give some more detail) it would help.
C# and CLR features confusion, what feature deserves to be described strictly as C# feature?
[ "", "c#", ".net", "clr", "" ]
I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map. ``` <img src="pic.jpg" usemap="#picmap" /> <map id="picmap" name="picmap"><area shape="rect" coords ="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" /> </map> <p id="desc"></p> ``` Where in the header I defined these functions: ``` <script type="text/javascript"> function mouse_off(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic.jpg"; } function mouse_on_write(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic2.jpg"; </script> ``` It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). **How can I make the image switching more seamless without reduction in picture quality?** On second thought I realize that I could also just have both images displayed, at a small and a large scale, and **on mouse over they would switch places; How would I do this?** Would this reduce lag?
You don't need to create any page elements, it can all be preloaded using JavaScript: ``` tempImg = new Image() tempImg.src="pic2.jpg" ``` EDIT: If you have a lot of images, you can use the poor-man's multi-preloader: ``` preloads = "red.gif,green.gif,blue.gif".split(",") var tempImg = [] for(var x=0;x<preloads.length;x++) { tempImg[x] = new Image() tempImg[x].src = preloads[x] } ```
Doing this with sprites is a good solution, because you don't have to wait to load the new image. Sprites work by combining the two images into one, and changing the background offset on mouseover. You can even do with with CSS instead, for much faster results. There's a good tutorial on this [here](http://www.alistapart.com/articles/sprites/).
How do I pre-cache images for quick viewing with javascript?
[ "", "javascript", "html", "" ]
I need to get a file from sourcesafe database programmatically. Any idea of how to do it? ps: I'll do that by using C#.
``` using System; using System.Collections.Generic; using SourceSafeTypeLib; namespace YourNamespace { public class SourceSafeDatabase { private readonly string dbPath; private readonly string password; private readonly string rootProject; private readonly string username; private readonly VSSDatabaseClass vssDatabase; public SourceSafeDatabase(string dbPath, string username, string password, string rootProject) { this.dbPath = dbPath; this.username = username; this.password = password; this.rootProject = rootProject; vssDatabase = new VSSDatabaseClass(); } public List<string> GetAllLabels() { List<string> allLabels = new List<string>(); VSSItem item = vssDatabase.get_VSSItem(rootProject, false); IVSSVersions versions = item.get_Versions(0); foreach (IVSSVersion version in versions) { if (version.Label.Length > 0) { allLabels.Add(version.Label); } } return allLabels; } public void GetLabelledVersion(string label, string project, string directory) { string outDir = directory; vssDatabase.get_VSSItem(rootProject, false).get_Version(label).Get(ref outDir, (int)VSSFlags.VSSFLAG_RECURSYES + (int)VSSFlags.VSSFLAG_USERRONO); } public void Open() { vssDatabase.Open(dbPath, username, password); } public void Close() { vssDatabase.Close(); } } // some other code that uses it SourceSafeDatabase sourceControlDatabase = new sourceControlDatabase(...); sourceControlDatabase.Open(); sourceControlDatabase.GetLabelledVersion(label, rootProject, projectDirectory); sourceControlDatabase.Close(); ```
There is a command-line SS.EXE program that you can call to do source control operations. However, it relies on global SourceSafe configuration and so it sometimes is hard to make it do what you want.
How to get a file from sourcesafe programmatically?
[ "", "c#", "visual-sourcesafe", "" ]
We are considering switching from MS Visual Studio 2003 to MS Visual Studio 2005 for our C++ development. I think jumping to 2008 might be better. In what ways are VS2008 better than VS2005 for C++ development? Are there any disadvantages of VS2008 over VS2005?
There are very little difference between 2005 and 2008 from native C++ developer point of view. However, if coming from 2003, it makes sense to upgrade directly to 2008 - the conversion process should be almost the same, and you will end up with a slightly better platform. Some new features which are available for 2008 only: * /MP option for multicore compilation (a huge timesaver if you have a mutlicore computer) * some improved debugging options for multithreaded applications There are also some additional downloadable feature packs for 2008 only: * TR1 libraries * new MFC
To be honest, as far as pure C++ development goes, I don't think there is much between the two, other than VS2008 is the 'latest' release. I didn't notice any significant changes. However, the latest release of MFC has been given a new lease of life with the addition of the Feature Pack (giving you an MSOffice 2007 look and feel) which might be worth knowing.
What are the advantages of VS2008 over VS2005 for C++ development?
[ "", "c++", "visual-studio-2008", "visual-studio-2005", "" ]
I found this in the code I'm working on at the moment and thought it was the cause of some problems I'm having. In a header somewhere: ``` enum SpecificIndexes{ //snip INVALID_INDEX = -1 }; ``` Then later - initialization: ``` nextIndex = INVALID_INDEX; ``` and use ``` if(nextIndex != INVALID_INDEX) { //do stuff } ``` Debugging the code, the values in nextIndex didn't quite make sence (they were very large), and I found that it was declared: ``` unsigned int nextIndex; ``` So, the initial setting to INVALID\_INDEX was underflowing the unsigned int and setting it to a huge number. I assumed that was what was causing the problem, but looking more closely, the test ``` if(nextIndex != INVALID_INDEX) ``` Was behaving correctly, i.e, it never executed the body of the if when nextIndex was the "large +ve value". Is this correct? How is this happening? Is the enum value being implicitly cast to an unsigned int of the same type as the variable, and hence being wrapped in the same way?
Yes to everything. It is valid code, it is also commonly used library-side C++ code, more so in modern C++ (it is strange when you see it the first time but its a very common pattern in reality). Then enums are signed ints, but they get implicitly cast into unsigned ints, now this depending on your compiler might give a warning, but its still very commonly used, however you should explicitly cast to make it clear to maintainers.
enums may be represented by signed or unsigned integral types according to whether they contain any negative values and what the compiler feels like. The example here contains a negative value and hence must be represented by a signed integral type. Equality comparison between signed and unsigned types is safe and usually does what the author intended - the signed value will be converted to unsigned first, and the result of doing that is defined by the C++ standard and is intuitive (at least, it is once you know the destination type. Except maybe if integers aren't two's complement. So maybe not that intuitive, but it doesn't normally cause problems). Order comparison is more likely to result in errors. For example: ``` SpecificIndexes value = INVALID_VALUE; return (value >= 0); ``` returns false, but: ``` unsigned int value = INVALID_VALUE; return (value >= 0); ``` returns true. Sometimes the author will not appreciate the difference, especially if the type of "value" isn't quite so obvious at the point of use. The compiler may well warn about the second example, though, because (value >= 0) is a tautology.
C++ enum to unsigned int comparison
[ "", "c++", "enums", "comparison", "integer", "unsigned", "" ]
I've got a couple django models that look like this: ``` from django.contrib.sites.models import Site class Photo(models.Model): title = models.CharField(max_length=100) site = models.ForeignKey(Site) file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} ) def __unicode__(self): return self.name ``` I'm having all kinds of *fun* trying to get the `limit_choices_to` working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?
I would delete `site` field on my `Photo` model and add a `ForeignKey` to `Gallery`. I would remove `limit_choices_to` from `photos` fields on `Gallery` model. Because you are using `ForeignKey`s to `Site`s, that means sites don't share galleries and photos. Therefore having those I mentioned above is already useless. ``` class Photo(models.Model): title = models.CharField(max_length=100) gallery = models.ForeignKey(Gallery, related_name='photos') file = models.ImageField(upload_to=get_site_profile_path) def __unicode__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=40) site = models.ForeignKey(Site) def __unicode__(self): return self.name ``` Once you set the `site` on a gallery all its photos will inherit this property. And the site will be accessible as `photo_instance.gallery.site`: ``` @property def site(self): return self.gallery.site ``` This should work as if you had a `site` field. But I haven't tested it. Things change or course, if you decide that a gallery or a photo can appear in multiple sites.
Yes. You need to override the form that admin uses for the `Gallery` model, then limit the queryset of the `photos` field in that form: ``` class GalleryAdminForm(django.forms.ModelForm): class Meta: model = Gallery def __init__(self, *args, **kwargs): super(GalleryAdminForm, self).__init__(*args, **kwargs) self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site) class GalleryAdmin(django.contrib.admin.ModelAdmin): form = GalleryAdminForm django.contrib.admin.site.register(Gallery, GalleryAdmin) ```
Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?
[ "", "python", "django", "foreign-keys", "manytomanyfield", "limit-choices-to", "" ]
I have a particular PHP page that, for various reasons, needs to save ~200 fields to a database. These are 200 separate insert and/or update statements. Now the obvious thing to do is reduce this number but, like I said, for reasons I won't bother going into I can't do this. I wasn't expecting this problem. Selects seem reasonably performant in MySQL but inserts/updates aren't (it takes about 15-20 seconds to do this update, which is naturally unacceptable). I've written Java/Oracle systems that can happily do thousands of inserts/updates in the same time (in both cases running local databases; MySQL 5 vs OracleXE). Now in something like Java or .Net I could quite easily do one of the following: 1. Write the data to an in-memory write-behind cache (ie it would know how to persist to the database and could do so asynchronously); 2. Write the data to an in-memory cache and use the PaaS (Persistence as a Service) model ie a listener to the cache would persist the fields; or 3. Simply start a background process that could persist the data. The minimal solution is to have a cache that I can simply update, which will separately go and upate the database in its own time (ie it'll return immediately after update the in-memory cache). This can either be a global cache or a session cache (although a global shared cache does appeal in other ways). Any other solutions to this kind of problem?
You should be able to do 200 inserts relatively quickly, but it will depend on lots of factors. If you are using a transactional engine and doing each one in its own transaction, don't - that creates way too much I/O. If you are using a non-transactional engine, it's a bit trickier. Using a single multi-row insert is likely to be better as the flushing policy of MySQL means that it won't need to flush its changes after each row. You really want to be able to reproduce this on your production-spec development box and analyse exactly why it's happening. It should not be difficult to stop. Of course, another possibility is that your inserts are slow because of extreme sized tables or large numbers of indexes - in which case you should scale your database server appropriately. Inserting lots of rows into a table whose indexes don't fit into RAM (or doesn't have RAM correctly configured to be used for caching those indexes) generally gets pretty smelly. BUT don't try to look for a way of complicating your application when there is a way of easily turning it instead, keeping the current algorithm.
mysql\_query('INSERT INTO tableName VALUES(...),(...),(...),(...)') Above given query statement is better. But we have another solution to improve the performance of insert statement. Follow the following steps.. 1. You just create a csv(comma separated delimited file)or simple txt file and write all the data that you want to insert using file writing mechanism (like FileOutputStream class in Java). 2. use this command ``` LOAD DATA INFILE 'data.txt' INTO TABLE table2 FIELDS TERMINATED BY '\t'; ``` 3 if you are not clear about this command then follow the [link](http://dev.mysql.com/doc/refman/5.1/en/load-data.html)
How to implement background/asynchronous write-behind caching in PHP?
[ "", "php", "mysql", "caching", "" ]
I am trying to convert this test code to C# and having a problem with the Trim command. Has anyone done anything similiar like this in C# going to use this with a text box for searching the aspx page. ``` Dim q = From b In db.Blogs _ Where b.BlogContents.Contains(txtSearch.Text.Trim()) Or _ b.BlogTitle.Contains(txtSearch.Text.Trim()) _ Select b ```
What is the issue you are having? And what LINQ provider is this? An in-memory set (LINQ-to-Objects)? Or LINQ-to-SQL? Or LINQ-to-Entities? I *suspect* you are getting something about the db LINQ provider not knowing about Trim() - in which case, try doing the trim first: ``` string s = txtSearch.Text.Trim(); var q = from b in db.Blogs where b.BlogContents.Contains(s) || b.BlogTitle.Contains(s) select b; ``` This addresses ~~two~~ three separate issues: 1: captures: in the original, it is `txtSearch` that is captured into the query, which has complications; by evaluating the `Trim` first, it is `s` that is captured, which is a simple immutable string 2: expression complexity: with expression-based LINQ (i.e. to a database), the *entire* expression (including `.Text`, `.Trim`, etc) is part of the expression. If the LINQ provider doesn't recognise one or more of those, it will fail. By reducing it to a string first, all the LINQ provider needs to handle is a string, which every provider should be fine with. (added) 3: repeated computation: LINQ-to-Objects is very literal; if you ask it to use a complex operation in a Where (etc), it *will*, even if it is obvious that the answer is unchanged per row; i.e. `txtSearch.Text.Trim()` shouldn't change per row, so why evaluate it per row? Evaluate it before the query and it is only done once.
not sure what you are asking but the Trim function in c# is the same. <http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx>
Using Linq and the Trim.Text for Search
[ "", "c#", "linq", "" ]
I am working on a plugin system that loads .dll's contained in a specified folder. I am then using reflection to load the assemblies, iterate through the types they contain and identify any that implement my `IPlugin` interface. I am checking this with code similar to the following: ``` foreach(Type t in myTypes ) { if( typeof(IPlugin).IsAssignableFrom(t) ) { ... } } ``` For some reason IsAssignableFrom() keeps returning false when it should be returning true. I have tried replacing the `t` by explicitly giving it a type that should pass, and it works fine, but for some reason it isn't working with the types that are returned from the loaded assembly. To make things stranger, the code works fine on my co-worker's machine but not on mine. Does anyone know of anything that might cause this sort of behavior? Thanks
That typically happens when there's a mismatch between the assembly which contains the type IPlugin that the current assembly references, and the assembly which is referenced by the assembly containg the types you're iterating over. I suggest you print: ``` typeof (IPlugin).Module.FullyQualifiedName ``` and ``` foreach (var type in t.GetInterfaces ()) { Console.WriteLine (type.Module.FullyQualifiedName) } ``` To see where the mismatch is.
I had same issue when interface was defined in a separate assembly to implementing type. Iterating and loading assemblies from root folder that contained dlls with classes AND dll with interface resulted in type mismatch as mentioned above. One solution was to change `LoadFrom()` to `LoadFile()` The `LoadFrom` method has some disadvantages and that is one of them: > If an assembly with the same identity is already loaded, LoadFrom returns the loaded assembly even if a different path was specified. Another way to overcome this is to place all dlls with types implementing interface into separate folder and not to copy referenced assembly (`CopyLocal = False`) so `Assembly.LoadFrom` will not load dll containing interface in memory.
IsAssignableFrom() returns false when it should return true
[ "", "c#", ".net", "reflection", "" ]
I'm using Java 1.5 and I'd like to launch the associated application to open the file. I know that Java 1.6 introduced the [Desktop API](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/), but I need a solution for **Java 1.5**. So far I found a way to do it in Windows: ``` Runtime.getRuntime().exec(new String[]{ "rundll32", "url.dll,FileProtocolHandler", fileName }); ``` Is there a cross-platform way to do it? Or at least a similar solution for **Linux**?
+1 for [this answer](https://stackoverflow.com/questions/325299/#325517) Additionally I would suggest the following implementation using polymorphism: This way you can add new platform easier by reducing coupling among classes. *The Client code:* ``` Desktop desktop = Desktop.getDesktop(); desktop.open( aFile ); desktop.imaginaryAction( aFile ); ``` *The Desktop impl:* ``` package your.pack.name; import java.io.File; public class Desktop{ // hide the constructor. Desktop(){} // Created the appropriate instance public static Desktop getDesktop(){ String os = System.getProperty("os.name").toLowerCase(); Desktop desktop = new Desktop(); // This uf/elseif/else code is used only once: here if ( os.indexOf("windows") != -1 || os.indexOf("nt") != -1){ desktop = new WindowsDesktop(); } else if ( os.equals("windows 95") || os.equals("windows 98") ){ desktop = new Windows9xDesktop(); } else if ( os.indexOf("mac") != -1 ) { desktop = new OSXDesktop(); } else if ( os.indexOf("linux") != -1 && isGnome() ) { desktop = new GnomeDesktop(); } else if ( os.indexOf("linux") != -1 && isKde() ) { desktop = new KdeDesktop(); } else { throw new UnsupportedOperationException(String.format("The platform %s is not supported ",os) ); } return desktop; } // default implementation :( public void open( File file ){ throw new UnsupportedOperationException(); } // default implementation :( public void imaginaryAction( File file ){ throw new UnsupportedOperationException(); } } // One subclass per platform below: // Each one knows how to handle its own platform class GnomeDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: execute gnome-open <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec:gnome-something-else <file> } } class KdeDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: kfmclient exec <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec: kfm-imaginary.sh <file> } } class OSXDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: open <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec: wow!! <file> } } class WindowsDesktop extends Desktop{ public void open( File file ){ // Runtime.getRuntime().exec: cmd /c start <file> } public void imaginaryAction( File file ){ // Runtime.getRuntime().exec: ipconfig /relese /c/d/e } } class Windows9xDesktop extends Desktop{ public void open( File file ){ //Runtime.getRuntime().exec: command.com /C start <file> } public void imaginaryAction( File file){ //Runtime.getRuntime().exec: command.com /C otherCommandHere <file> } } ``` This is only an example, in real life is not worth to create a new class only to parametrize a value ( the command string %s ) But let's do imagine that each method performs another steps in platform specific way. Doing this kind of approach, may remove unneeded if/elseif/else constructs that with time may introduce bugs ( if there are 6 of these in the code and a change is neede, you may forget to update one of them, or by copy/pasting you may forget to change the command to execute)
``` public static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); return os.indexOf("windows") != -1 || os.indexOf("nt") != -1; } public static boolean isMac() { String os = System.getProperty("os.name").toLowerCase(); return os.indexOf("mac") != -1; } public static boolean isLinux() { String os = System.getProperty("os.name").toLowerCase(); return os.indexOf("linux") != -1; } public static boolean isWindows9X() { String os = System.getProperty("os.name").toLowerCase(); return os.equals("windows 95") || os.equals("windows 98"); } ``` and ``` if (isLinux()) { cmds.add(String.format("gnome-open %s", fileName)); String subCmd = (exec) ? "exec" : "openURL"; cmds.add(String.format("kfmclient "+subCmd+" %s", fileName)); } else if (isMac()) { cmds.add(String.format("open %s", fileName)); } else if (isWindows() && isWindows9X()) { cmds.add(String.format("command.com /C start %s", fileName)); } else if (isWindows()) { cmds.add(String.format("cmd /c start %s", fileName)); } ```
Cross-platform way to open a file using Java 1.5
[ "", "java", "linux", "file-association", "java-5", "" ]
Is there a way in MySQL to select rows which fall on a specific day, as in Mondays, using a date column?
MySQL [DAYOFWEEK](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_dayofweek) function. E.g. to select Mondays: ``` SELECT * FROM foo WHERE DAYOFWEEK(bar) = 2 ```
Look up the DAYOFWEEK() function [here](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_dayofweek) in the MySQL Online Docs
Way to select rows which fall on a specific day?
[ "", "sql", "mysql", "" ]
I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit **Select All** it doesn't select all. I can right click and click **Select All** but `CTRL` + `A` doesn't do anything. Why? ``` wnd = CreateWindow("EDIT", 0, WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL, x, y, w, h, parentWnd, NULL, NULL, NULL); ```
I tend to use MFC (forgive me) instead of Win32 so I cannot answer this definitively, but I noticed this comment added to a page on an MS site concerning talking with an Edit control (a simple editor within the Edit control): > The edit control uses `WM_CHAR` for > accepting characters, not `WM_KEYDOWN` > etc. You must `Translate()` your > messages or you ironically won't be > able to edit the text in the edit > control. I don't know if this applies to BoltBait's response, but I suspect it does. (I found this at <http://msdn.microsoft.com/en-us/library/bb775462(VS.85).aspx>)
`Ctrl`+`A` is not a built-in accelerator like `Ctrl`+`C` and `Ctrl`+`V`. This is why you see WM\_CUT, WM\_PASTE and WM\_COPY messages defined, but there is no WM\_SELECTALL. You have to implement this functionality yourself. I did in my MFC app like this: ``` static BOOL IsEdit( CWnd *pWnd ) { if ( ! pWnd ) return FALSE ; HWND hWnd = pWnd->GetSafeHwnd(); if (hWnd == NULL) return FALSE; TCHAR szClassName[6]; return ::GetClassName(hWnd, szClassName, 6) && _tcsicmp(szClassName, _T("Edit")) == 0; } BOOL LogWindowDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message==WM_KEYDOWN) { if ( pMsg->wParam=='A' && GetKeyState(VK_CONTROL)<0 ) { // User pressed Ctrl-A. Let's select-all CWnd * wnd = GetFocus() ; if ( wnd && IsEdit(wnd) ) ((CEdit *)wnd)->SetSel(0,-1) ; } } return CDialog::PreTranslateMessage(pMsg); } ``` Note, I stole IsEdit from this page: <http://support.microsoft.com/kb/145616> I point that out partly because I want to give credit, and partly because I think the IsEdit function (comparing classname strings) is dorky and I want to give blame.
win32 select all on edit ctrl (textbox)
[ "", "c++", "user-interface", "winapi", "textbox", "" ]
Suppose I have code like this: ``` template<class T, T initial_t> class Bar { // something } ``` And then try to use it like this: ``` Bar<Foo*, NULL> foo_and_bar_whatever_it_means_; ``` GCC bails out with error (on the above line): > could not convert template argument > '0' to 'Foo\*' I found this thread: <http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html>, but I have to use NULL in this case (ok, I could probably refactor - but it would not be trivial; any suggestions?). I tried to overcome the problem by creating a variable with value of NULL, but GCC still complains that I pass variable and not address of variable as a template argument. And reference to a variable initialized with default ctor would not be the same as NULL.
Rethinking your code is probably the best way to get around it. The thread you linked to includes a clear quote from the standard indicating that this isn't allowed.
To accept `Bar<Foo, NULL>`, you need ``` template <typename T, int dummy> class Bar; /* Declared but not defined */ template <typename T> class Bar <T,NULL> { /* Specialization */ }; ``` since typeof(NULL)==int.
How to overcome GCC restriction "could not convert template argument '0' to 'Foo*'"?
[ "", "c++", "templates", "gcc", "" ]
I'm trying to implement a `KeyListener` for my `JFrame`. On the constructor, I'm using this code: ``` System.out.println("test"); addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { System.out.println( "tester"); } public void keyReleased(KeyEvent e) { System.out.println("2test2"); } public void keyTyped(KeyEvent e) { System.out.println("3test3"); } }); ``` When I run it, the `test` message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the `KeyListener` was not even there. I was thinking that it could be because the focus is not on the `JFrame` and so they `KeyListener` doesn't receive any events. But, I'm pretty sure it is. Is there something that I am missing?
You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well. The process is the same: ``` myComponent.addKeyListener(new KeyListener ...); ``` Note: Some components aren't focusable like JLabel. For setting them to focusable you need to: ``` myComponent.setFocusable(true); ```
If you don't want to register a listener on every component, you could **add your own `KeyEventDispatcher`** to the `KeyboardFocusManager`: ``` public class MyFrame extends JFrame { private class MyDispatcher implements KeyEventDispatcher { @Override public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED) { System.out.println("tester"); } else if (e.getID() == KeyEvent.KEY_RELEASED) { System.out.println("2test2"); } else if (e.getID() == KeyEvent.KEY_TYPED) { System.out.println("3test3"); } return false; } } public MyFrame() { add(new JTextField()); System.out.println("test"); KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.addKeyEventDispatcher(new MyDispatcher()); } public static void main(String[] args) { MyFrame f = new MyFrame(); f.pack(); f.setVisible(true); } } ```
Unresponsive KeyListener for JFrame
[ "", "java", "swing", "jframe", "keylistener", "" ]
I have two tables with the same columns, and I need to copy one table's rows to the other table's rows to create one big table with all the values from both tables. Right now I am doing this query to return the same thing: ``` SELECT col1, col2, col3 from Table1 union SELECT col1, col2, col3 from Table2 ``` However, it seems horribly inefficient, and on my system is very slow (returns 1210189 records).
May it work to just do: ``` SELECT col1, col2, col3 INTO Table1 FROM Table2 ```
Start with union all: ``` select col1, col2, col3 from Table1 union all select col1, col2, col3 from Table2 ``` Your query is trying to deduplicate things, which would slow it down considerably.
join two tables into one big table
[ "", "sql", "database", "" ]
I have a [`JPanel`](http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JPanel.html) to which I'd like to add JPEG and PNG images that I generate on the fly. All the examples I've seen so far in the [Swing Tutorials](http://java.sun.com/docs/books/tutorial/uiswing/), specially in the [Swing examples](http://java.sun.com/docs/books/tutorial/uiswing/examples/components/) use `ImageIcon`s. I'm generating these images as byte arrays, and are usually larger than the common icons they use in the examples, at 640x480. 1. Is there any (performance or other) problem in using the `ImageIcon` class to display an image that size in a `JPanel`? 2. What's the *"usual"* way of doing it? 3. How to add an image to a `JPanel` without using the `ImageIcon` class? **Edit**: A more careful examination of the tutorials and the API shows that you cannot add an `ImageIcon` directly to a `JPanel`. Instead, they achieve the same effect by setting the image as an icon of a `JLabel`. This just doesn't feel right...
Here's how I do it (with a little more info on how to load an image): ``` import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JPanel; public class ImagePanel extends JPanel{ private BufferedImage image; public ImagePanel() { try { image = ImageIO.read(new File("image name and path")); } catch (IOException ex) { // handle exception... } } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters } } ```
If you are using JPanels, then are probably working with Swing. Try this: ``` BufferedImage myPicture = ImageIO.read(new File("path-to-file")); JLabel picLabel = new JLabel(new ImageIcon(myPicture)); add(picLabel); ``` The image is now a swing component. It becomes subject to layout conditions like any other component.
How to add an image to a JPanel?
[ "", "java", "image", "swing", "jpanel", "" ]
I have input consisting of a list of nested lists like this: ``` l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] ``` I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this: ``` [39, 6, 13, 50] ``` Then I want to sort based on these. So the output should be: ``` [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] ``` What's a nice pythonic way of doing this?
A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax: ``` >>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] >>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t ... >>> sorted(l, key=asum) [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] ```
A little recursive function would do it: ``` def asum(a): if isinstance(a, list): return sum(asum(x) for x in a) else: return a l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] l.sort(key=asum) print l ```
Python - sort a list of nested lists
[ "", "python", "list", "sorting", "nested-lists", "" ]
I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this. ``` //Fill the years (counting 100 from the first) function fillvarYear() { var dt = $('#txtBDate').val(); dt = dt.toString().substring(6); var ye = parseInt(dt); //Loop and add the next 100 years from the birth year to the combo for (var j = 1; j <= 100; j++) { ye += 1; //Add one year to the year count var opt = document.createElement("OPTION"); opt.text = ye; opt.value = ye; document.form1.ddlYear.add(opt); } } ```
To see the value on postback: ``` string selectedValue = Request.Params[combobox.UniqueId] ``` Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation. I'd recommend placing the combobox in an update panel, so you can read txtBirthDate on the server and generate the appropriate data. You then won't have to manually preserve state either.
Always remember, ASP.NET controls are nothing "fancy" - they always end up at some point becoming standard HTML elements. Try checking out [this site](http://www.mredkj.com/tutorials/tutorial005.html). It has a pretty nice demo and overview. Take note however that you are **altering the data at the client side - this means you will need to do it on each and every request because the ViewState will not be updated.** TBH, you are probably better off just using a HTML control rather than ASP ComboBox.. Can I ask why you are changing items via Javascript? (out of curiosity) :)
I want to add items to an ASP.Net combobox using Javascript
[ "", "asp.net", "javascript", "" ]
I have a single string that contains the command-line parameters to be passed to another executable and I need to extract the string[] containing the individual parameters in the same way that C# would if the commands had been specified on the command-line. The string[] will be used when executing another assemblies entry-point via reflection. Is there a standard function for this? Or is there a preferred method (regex?) for splitting the parameters correctly? It must handle '"' delimited strings that may contain spaces correctly, so I can't just split on ' '. Example string: ``` string parameterString = @"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam foo"; ``` Example result: ``` string[] parameterArray = new string[] { @"/src:C:\tmp\Some Folder\Sub Folder", @"/users:abcdefg@hijkl.com", @"tasks:SomeTask,Some Other Task", @"-someParam", @"foo" }; ``` I do not need a command-line parsing library, just a way to get the String[] that should be generated. **Update**: I had to change the expected result to match what is actually generated by C# (removed the extra "'s in the split strings)
In addition to the [good and pure managed solution](https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c/298990#298990) by [Earwicker](https://stackoverflow.com/users/27423/earwicker), it may be worth mentioning, for sake of completeness, that Windows also provides the [`CommandLineToArgvW`](http://msdn.microsoft.com/en-us/library/bb776391.aspx) function for breaking up a string into an array of strings: > ``` > LPWSTR *CommandLineToArgvW( > LPCWSTR lpCmdLine, int *pNumArgs); > ``` > > Parses a Unicode command line string > and returns an array of pointers to > the command line arguments, along with > a count of such arguments, in a way > that is similar to the standard C > run-time argv and argc values. An example of calling this API from C# and unpacking the resulting string array in managed code can be found at, “[Converting Command Line String to Args[] using CommandLineToArgvW() API](http://intellitect.com/converting-command-line-string-to-args-using-commandlinetoargvw-api/).” Below is a slightly simpler version of the same code: ``` [DllImport("shell32.dll", SetLastError = true)] static extern IntPtr CommandLineToArgvW( [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs); public static string[] CommandLineToArgs(string commandLine) { int argc; var argv = CommandLineToArgvW(commandLine, out argc); if (argv == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(); try { var args = new string[argc]; for (var i = 0; i < args.Length; i++) { var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size); args[i] = Marshal.PtrToStringUni(p); } return args; } finally { Marshal.FreeHGlobal(argv); } } ```
It annoys me that there's no function to split a string based on a function that examines each character. If there was, you could write it like this: ``` public static IEnumerable<string> SplitCommandLine(string commandLine) { bool inQuotes = false; return commandLine.Split(c => { if (c == '\"') inQuotes = !inQuotes; return !inQuotes && c == ' '; }) .Select(arg => arg.Trim().TrimMatchingQuotes('\"')) .Where(arg => !string.IsNullOrEmpty(arg)); } ``` Although having written that, why not write the necessary extension methods. Okay, you talked me into it... Firstly, my own version of Split that takes a function that has to decide whether the specified character should split the string: ``` public static IEnumerable<string> Split(this string str, Func<char, bool> controller) { int nextPiece = 0; for (int c = 0; c < str.Length; c++) { if (controller(str[c])) { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } } yield return str.Substring(nextPiece); } ``` It may yield some empty strings depending on the situation, but maybe that information will be useful in other cases, so I don't remove the empty entries in this function. Secondly (and more mundanely) a little helper that will trim a matching pair of quotes from the start and end of a string. It's more fussy than the standard Trim method - it will only trim one character from each end, and it will not trim from just one end: ``` public static string TrimMatchingQuotes(this string input, char quote) { if ((input.Length >= 2) && (input[0] == quote) && (input[input.Length - 1] == quote)) return input.Substring(1, input.Length - 2); return input; } ``` And I suppose you'll want some tests as well. Well, alright then. But this must be absolutely the last thing! First a helper function that compares the result of the split with the expected array contents: ``` public static void Test(string cmdLine, params string[] args) { string[] split = SplitCommandLine(cmdLine).ToArray(); Debug.Assert(split.Length == args.Length); for (int n = 0; n < split.Length; n++) Debug.Assert(split[n] == args[n]); } ``` Then I can write tests like this: ``` Test(""); Test("a", "a"); Test(" abc ", "abc"); Test("a b ", "a", "b"); Test("a b \"c d\"", "a", "b", "c d"); ``` Here's the test for your requirements: ``` Test(@"/src:""C:\tmp\Some Folder\Sub Folder"" /users:""abcdefg@hijkl.com"" tasks:""SomeTask,Some Other Task"" -someParam", @"/src:""C:\tmp\Some Folder\Sub Folder""", @"/users:""abcdefg@hijkl.com""", @"tasks:""SomeTask,Some Other Task""", @"-someParam"); ``` Note that the implementation has the extra feature that it will remove quotes around an argument if that makes sense (thanks to the TrimMatchingQuotes function). I believe that's part of the normal command-line interpretation.
Split string containing command-line parameters into string[] in C#
[ "", "c#", "command-line", "text-parsing", "" ]
I am attempting to use a Stream Result to return an image from a struts2 application. I seem to be having problem with configuring the action. Here is the configuration: ``` <result name="success" type="stream"> <param name="contentType">image/jpeg</param> <param name="inputName">inputStream</param> <param name="contentDisposition">filename="${filename}"</param> <param name="bufferSize">1024</param> </result> ``` The problem seem to be the inputName parameter which according to the docs is: > the name of the InputStream property from the chained action (default = inputStream). I am not sure what name I should put there. The error I get is: > Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Has anyone used this before? Any advice? Thanks.
I found [this](http://www.nabble.com/Struts-2-File-upload-to-store-the-filedata-td14168069.html) which explained that the `InputStream` has to be created by me. It makes sense that I create an `InputStream` from the file that I want the user to download and then pass the Stream to the result. I guess that's my answer.
I believe you have the contentDisposition wrong, it should be: ``` <param name="contentDisposition">attachment; filename="${filename}"</param> ``` (*Chris*)
Using Stream Result with Struts2
[ "", "java", "struts2", "resulttype", "" ]
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of: ``` $("<div></div>"); ``` However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective? [This answer](https://stackoverflow.com/a/268520/32943) has the benchmarks to the suggestions below.
I use `$(document.createElement('div'));` [Benchmarking shows](http://jsperf.com/jquery-vs-createelement) this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself. You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.
personally i'd suggest (for readability): ``` $('<div>'); ``` some numbers on the suggestions so far (safari 3.2.1 / mac os x): ``` var it = 50000; var start = new Date().getTime(); for (i = 0; i < it; ++i) { // test creation of an element // see below statements } var end = new Date().getTime(); alert( end - start ); var e = $( document.createElement('div') ); // ~300ms var e = $('<div>'); // ~3100ms var e = $('<div></div>'); // ~3200ms var e = $('<div/>'); // ~3500ms ```
What is the most efficient way to create HTML elements using jQuery?
[ "", "javascript", "jquery", "html", "dom", "" ]
Im thinking of updating my practices, and looking for a little help and advice! I do a lot of work on sites that run joomla, oscommerce, drupal etc and so I have created a lot of custom components/plugins and hacks etc. Currently each site has its own folder on my xampp setup. What I would like to do is have a default setup of (for example) a Joomla setup and when I make changes updates, I can do something which updates all the other folders that contain joomla, almost like an auto update? Im also looking at using Aptana IDE more and SVN service such as [unfuddle](http://unfuddle.com/) to share my work with others, but I have not used SVN before and not sure if its possible to do the above using SVN? It would be great to be able to work on a main/core item and send the updates to both local updates and to actual servers, without having to maintain lots of different individual sites. Suggestions?
Yes, SVN would be a great tool for this purpose. Store your code (eg: a custom Joomla component) in source control. Wherever you want to use that component, just do a `checkout` or `export` of that particular folder into your live site. Here's one way you could structure your repository: ``` unfuddle.com/myRepo/trunk/com_myComponent unfuddle.com/myRepo/trunk/com_anotherComponent ``` Log in to your live server via SSH and run this command: ``` > cd path/to/joomla/components > svn co http://unfuddle.com/myRepo/trunk/com_myComponent ``` Any time you change your code, commit the changes and then log back into the server and run: ``` > cd path/to/joomla/components > svn up com_myComponent ``` A real benefit of this is that should you do an update and break something, you can always roll it back to the last known "good" version. As for automating this process, you might be out of luck if it's on different servers. For multiple deployments on the same server, you could quite easily write a shell script to run the above commands for each site/component. If you needed this to be fully automated, you could even set up a cron job to run this script every day at 2am or something - personally I'd stick with the manual approach, but it's still an option. For working locally with your SVN repositories, I'd recommend looking at [TortoiseSVN](http://tortoisesvn.tigris.org/) (if you're on Windows): it's the simplest and easiest way to work with SVN.
For automating things, you could use SVN hooks for this. There is a post-commit hook, so every time you do a commit, your hook script could tell the other machines to do an SVN update to get the latest code. For more info, see [Version Control with Subversion - Implementing Repository Hooks](http://svnbook.red-bean.com/en/1.5/svn.reposadmin.create.html#svn.reposadmin.create.hooks).
IDE, SVN and pushing to sites!
[ "", "php", "svn", "ide", "aptana", "unfuddle", "" ]
How can I bring my WPF application to the front of the desktop? So far I've tried: ``` SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true); SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle); ``` None of which are doing the job (`Marshal.GetLastWin32Error()` is saying these operations completed successfully, and the P/Invoke attributes for each definition do have `SetLastError=true`). If I create a new blank WPF application, and call `SwitchToThisWindow` with a timer, it works exactly as expected, so I'm not sure why it's not working in my original case. **Edit**: I'm doing this in conjunction with a global hotkey.
Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally. ``` void hotkey_execute() { IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle; BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(delegate { Thread.Sleep(10); SwitchToThisWindow(handle, true); }); bg.RunWorkerAsync(); } ```
``` myWindow.Activate(); ``` *Attempts to bring the window to the foreground and activates it.* That should do the trick, unless I misunderstood and you want Always on Top behavior. In that case you want: ``` myWindow.TopMost = true; ```
Bring a window to the front in WPF
[ "", "c#", ".net", "wpf", "winapi", "pinvoke", "" ]
I want to learn how to create **truly** robust applications in .net - ones that are fault tolerant and are capable of withstanding unexpected situations. Where can I find literature/guidance on this subject? So far, I am not having much luck.
I'm aware of at least a couple resources. First, there's a very useful article on MSDN titled [Keep Your Code Running with the Reliability Features of the .NET Framework](http://msdn.microsoft.com/en-us/magazine/cc163716.aspx). Chris Brumme also had a [post on hosting](http://blogs.msdn.com/cbrumme/archive/2004/02/21/77595.aspx) when the reliability features were being designed. This can provide some useful background information Search terms that you may find useful include "High Availability" "CER" and "Constrained Execution Regions". Good luck! Truly available code is pretty tricky stuff. :)
If you are looking from a software implementation perspective, then it may be worth looking into [Design by Contract (DbC)](http://en.wikipedia.org/wiki/Design_by_contract) According to [this source](http://archive.eiffel.com/doc/manuals/technology/contract/), the benefits of Design by Contract include the following: * A better understanding of the object-oriented method and, more generally, of software construction. * A systematic approach to building bug-free object-oriented systems. * An effective framework for debugging, testing and, more generally, quality assurance. * A method for documenting software components. * Better understanding and control of the inheritance mechanism. * A technique for dealing with abnormal cases, leading to a safe and effective language construct for exception handling. In addition, I would advocate looking into a [Test Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) approach, which should help drive out a more robust design.
Redundancy, reliability and fault tolerance in C# - where to look for examples?
[ "", "c#", "reliability", "redundancy", "" ]
Does anyone know what is wrong with this query? ``` SELECT DISTINCT c.CN as ClaimNumber, a.ItemDate as BillReceivedDate, c.DTN as DocTrackNumber FROM ItemData a, ItemDataPage b, KeyGroupData c WHERE a.ItemTypeNum in (112, 113, 116, 172, 189) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC; ``` I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL. Thanks! [EDIT] For future reference, the error given by SQL\*Plus was: "ORA-01791: not a SELECTed expression"
You will need to modify the query as such: ``` SELECT DISTINCT c.CN as ClaimNumber, a.ItemDate as BillReceivedDate, c.DTN as DocTrackNumber, a.DateStored FROM ItemData a, ItemDataPage b, KeyGroupData c WHERE a.ItemTypeNum in (112, 113, 116, 172, 189) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC; ``` When doing a DISTINCT your order by needs to be one of the selected columns.
Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works: ``` SELECT DISTINCT c.CN as ClaimNumber, a.ItemDate as BillReceivedDate, c.DTN as DocTrackNumber, a.DateStored FROM ItemData a, ItemDataPage b, KeyGroupData c WHERE a.ItemTypeNum in (112, 113, 116, 172, 189) AND a.ItemNum = b.ItemNum AND b.ItemNum = c.ItemNum ORDER BY a.DateStored DESC; ```
Oracle PL/SQL Query Order By issue with Distinct
[ "", "sql", "oracle", "" ]
I am using Context.RewritePath() in ASP.NET 3.5 application running on IIS7. I am doing it in application BeginRequest event and everything works file. Requests for /sports are correctly rewritten to default.aspx?id=1, and so on. The problem is that in my IIS log I see GET requests for /Default.aspx?id=1 and not for /sports. This kind of code worked perfectly under IIS6. Using Microsoft Rewrite module is not an option, due to some business logic which has to be implemented. Thanks. EDIT: It seems my handler is too early in the pipeline, but if I move the logic to a later event, than the whole rewrite thing doesn't work (it's too late, StaticFileHandler picks up my request). I googled and googled, asked around, can't believe that nobody has this problem? EDIT: Yikes! Here's what I found on the IIS forum: "This is because in integrated mode, IIS and asp.net share a common pipeline and the RewritePath is now seen by IIS, while in IIS6, it was not even seen by IIS - you can workaround this by using classic mode which would behave like IIS6." **Final update**: Please take a look at [my answer below](https://stackoverflow.com/questions/353541/iis7-rewritepath-and-iis-log-files/579141#579141), I've updated it with results after more than a year in production environment.
After some research, I've finally found a solution to the problem. I have replaced the calls to Context.RewritePath() method with the new (introduced in ASP.NET 3.5) **Context.Server.TransferRequest()** method. It seems obvious now, but not event Senior Dev Engineer on IIS Core team thought of that. I've tested it for session, authentication, postback, querystring, ... issues and found none. Tommorow I'll deploy the change to a very hight traffic site, and we'll soon know how it actually works. :) I'll be back with the update. **The update:** the solution is still not entirely on my production servers but it's tested and it does work and as far as I can tell so far, it's a solution to my problem. If I discover anything else in production, I will post an update. **The final update:** I have this solution in production for over a year and it has proven to be a good and stable solution without any problems.
You could set the path back to the original value after the request has been processed but before the IIS logging module writes the log entry. For example, this module rewrites the path on `BeginRequest` and then sets it back to the original value on `EndRequest`. When this module is used the original path appears in the IIS log file: ``` public class RewriteModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += OnBeginRequest; context.EndRequest += OnEndRequest; } static void OnBeginRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; app.Context.Items["OriginalPath"] = app.Context.Request.Path; app.Context.RewritePath("Default.aspx?id=1"); } static void OnEndRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; var originalPath = app.Context.Items["OriginalPath"] as string; if (originalPath != null) { app.Context.RewritePath(originalPath); } } public void Dispose() { } } ```
IIS7, RewritePath and IIS log files
[ "", "c#", "asp.net", "iis-7", "url-rewriting", "logging", "" ]
All the member variables and member functions in my class ClassA are static. If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class. Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object? Thank you
Like others said, a namespace is what you should use. If you want to stay with your class, create a class that has a private constructor, and derive from it, to make your intention obvious: ``` class NonConstructible { NonConstructible(); }; class SuperUtils: NonConstructible { static void foo(); // ... static std::vector<int> globalIDs; // ... }; ``` --- Ok, now let's look into the namespace which are the one and only way to do this: ``` namespace SuperUtils { void foo() { // .... } std::vector<int> globalIDs; }; ``` You can call that using `SuperUtils::foo();` in both cases, but the namespace has the advantage that in a scope you can use the namespace declaration and directive to bring certain or all members into the current scope, so that you can reference them without using `SuperUtils::`: ``` void superFunction() { using namespace SuperUtils; foo(); } ``` While generally that should be avoided, it can be helpful when the method is using exclusively much stuff from SuperUtils, which then can improve the readability of the code.
Instead of using a class with all static methods, you may be better off making the methods free-standing functions in a separate namespace. The call syntax would be the same: `namespace::function()` instead of `classname::function()` and you don't need to deal with someone trying to instantiate your class.
Prevent creation of class whose member functions are all static
[ "", "c++", "static", "constructor", "namespaces", "" ]
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent. The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not. The two ways are: ``` var functionOne = function() { // Some code }; ``` And, ``` function functionTwo() { // Some code } ``` What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
The difference is that `functionOne` is a function expression and so only defined when that line is reached, whereas `functionTwo` is a function declaration and is defined as soon as its surrounding function or script is executed (due to [hoisting](http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html)). For example, a function expression: ``` // TypeError: functionOne is not a function functionOne(); var functionOne = function() { console.log("Hello!"); }; ``` And, a function declaration: ``` // Outputs: "Hello!" functionTwo(); function functionTwo() { console.log("Hello!"); } ``` Historically, function declarations defined within blocks were handled inconsistently between browsers. [Strict mode](https://udn.realityripple.com/docs/Glossary/strict_mode) (introduced in ES5) resolved this by scoping function declarations to their enclosing block. ``` 'use strict'; { // note this block! function functionThree() { console.log("Hello!"); } } functionThree(); // ReferenceError ```
First I want to correct Greg: `function abc(){}` is scoped too — the name `abc` is defined in the scope where this definition is encountered. Example: ``` function xyz(){ function abc(){}; // abc is defined here... } // ...but not here ``` Secondly, it is possible to combine both styles: ``` var xyz = function abc(){}; ``` `xyz` is going to be defined as usual, `abc` is undefined in all browsers but Internet Explorer — do not rely on it being defined. But it will be defined inside its body: ``` var xyz = function abc(){ // xyz is visible here // abc is visible here } // xyz is visible here // abc is undefined here ``` If you want to alias functions on all browsers, use this kind of declaration: ``` function abc(){}; var xyz = abc; ``` In this case, both `xyz` and `abc` are aliases of the same object: ``` console.log(xyz === abc); // prints "true" ``` One compelling reason to use the combined style is the "name" attribute of function objects (**not supported by Internet Explorer**). Basically when you define a function like ``` function abc(){}; console.log(abc.name); // prints "abc" ``` its name is automatically assigned. But when you define it like ``` var abc = function(){}; console.log(abc.name); // prints "" ``` its name is empty — we created an anonymous function and assigned it to some variable. Another good reason to use the combined style is to use a short internal name to refer to itself, while providing a long non-conflicting name for external users: ``` // Assume really.long.external.scoped is {} really.long.external.scoped.name = function shortcut(n){ // Let it call itself recursively: shortcut(n - 1); // ... // Let it pass itself as a callback: someFunction(shortcut); // ... } ``` In the example above we can do the same with an external name, but it'll be too unwieldy (and slower). *(Another way to refer to itself is to use `arguments.callee`, which is still relatively long, and not supported in the strict mode.)* Deep down, JavaScript treats both statements differently. This is a function declaration: ``` function abc(){} ``` `abc` here is defined everywhere in the current scope: ``` // We can call it here abc(); // Works // Yet, it is defined down there. function abc(){} // We can call it again abc(); // Works ``` Also, it hoisted through a `return` statement: ``` // We can call it here abc(); // Works return; function abc(){} ``` This is a function expression: ``` var xyz = function(){}; ``` `xyz` here is defined from the point of assignment: ``` // We can't call it here xyz(); // UNDEFINED!!! // Now it is defined xyz = function(){} // We can call it here xyz(); // works ``` Function declaration vs. function expression is the real reason why there is a difference demonstrated by Greg. Fun fact: ``` var xyz = function abc(){}; console.log(xyz.name); // Prints "abc" ``` Personally, I prefer the "function expression" declaration because this way I can control the visibility. When I define the function like ``` var abc = function(){}; ``` I know that I defined the function locally. When I define the function like ``` abc = function(){}; ``` I know that I defined it globally providing that I didn't define `abc` anywhere in the chain of scopes. This style of definition is resilient even when used inside `eval()`. While the definition ``` function abc(){}; ``` depends on the context and may leave you guessing where it is actually defined, especially in the case of `eval()` — the answer is: It depends on the browser.
var functionName = function() {} vs function functionName() {}
[ "", "javascript", "function", "methods", "syntax", "" ]
I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python `SimpleHTTPServer.SimpleHTTPRequestHandler`? A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. [here](http://msdl.cs.mcgill.ca/people/julien/04Ajax)), but so far I could not come up with a truly minimal one. In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).
O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions. the python server file: ``` import threading import webbrowser import BaseHTTPServer import SimpleHTTPServer FILE = 'frontend.html' PORT = 8080 class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """The test example handler.""" def do_POST(self): """Handle a post request by returning the square of the number.""" length = int(self.headers.getheader('content-length')) data_string = self.rfile.read(length) try: result = int(data_string) ** 2 except: result = 'error' self.wfile.write(result) def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" server_address = ("", PORT) server = BaseHTTPServer.HTTPServer(server_address, TestHandler) server.serve_forever() if __name__ == "__main__": open_browser() start_server() ``` ...and the HTML file (I call it 'frontend.html', unfortunately the name has to appear in the JavaScript code as well): ``` <html> <head> <title>AJAX test</title> </head> <body> <script type="text/javascript"> function xml_http_post(url, data, callback) { var req = false; try { // Firefox, Opera 8.0+, Safari req = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } req.open("POST", url, true); req.onreadystatechange = function() { if (req.readyState == 4) { callback(req); } } req.send(data); } function test_button() { var data = document.test_form.test_text.value; xml_http_post("frontend.html", data, test_handle) } function test_handle(req) { var elem = document.getElementById('test_result') elem.innerHTML = req.responseText } </script> <form name=test_form> sqr( <input type="text" name="test_text" value="0" size="4"> ) = <span id="test_result">0</span> <input type=button onClick="test_button();" value="start" title="start"> </form> </body> </html> ``` Of course it would be much more convenient to use [jQuery](http://api.jquery.com/jQuery.ajax/) for the XML request, but in the interest of simplicity I'll leave it like that. Finally an alternative implementation using WSGI (unfortunately I didn't see a way to fall back on the standard file-serving handler if the request is not a POST): ``` import threading import webbrowser from wsgiref.simple_server import make_server FILE = 'frontend.html' PORT = 8080 def test_app(environ, start_response): if environ['REQUEST_METHOD'] == 'POST': try: request_body_size = int(environ['CONTENT_LENGTH']) request_body = environ['wsgi.input'].read(request_body_size) except (TypeError, ValueError): request_body = "0" try: response_body = str(int(request_body) ** 2) except: response_body = "error" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response_body] else: response_body = open(FILE).read() status = '200 OK' headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" httpd = make_server("", PORT, test_app) httpd.serve_forever() if __name__ == "__main__": open_browser() start_server() ```
Use the [WSGI reference implementation](https://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server). In the long run, you'll be happier. ``` from wsgiref.simple_server import make_server, demo_app httpd = make_server('', 8000, demo_app) print "Serving HTTP on port 8000..." # Respond to requests until process is killed httpd.serve_forever() ``` The demo\_app is relatively easy to write; it handles your Ajax requests.
How to implement a minimal server for AJAX in Python?
[ "", "python", "ajax", "user-interface", "" ]
Can any one explain why the output of this code is only 'hello' and what this code means? ``` ( 0, characterArray, 0, characterArray.Length ); ``` The output is showing: ``` The character array is: hello ``` The code follows: ``` string string1 = "hello there"; char[] characterArray = new char[ 5 ]; string1.CopyTo( 0, characterArray, 0, characterArray.Length ); Console.Write( "\nThe character array is: " ); for ( int i = 0; i < characterArray.Length; i++ ) Console.Write( characterArray[ i ] ); ```
It's because your array is only set for 5 characters. Expand it to 11 and it will work. Here is what the Copyto is: ``` public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) ``` ``` Parameters sourceIndex Type: System..::.Int32 A character position in this instance. destination Type: array[]()[] An array of Unicode characters. destinationIndex Type: System..::.Int32 An array element in destination. count Type: System..::.Int32 The number of characters in this instance to copy to destination. ``` Taken from: <http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx>
It's only showing 'hello' because your character array is only 5 chars long. As for the parameters to CopyTo, read <http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx>
What is String.CopyTo?
[ "", "c#", "" ]
I have a need to evaluate user-defined logical expressions of arbitrary complexity on some PHP pages. Assuming that form fields are the primary variables, it would need to: * substitute"varibles" for form fields values; * handle comparison operators, minimally ==, <, <=, >= and > by symbol, name (eg eq, lt, le, ge, gt respectively); * handle boolean operators not, and, or and possibly xor by name, symbol (eg !, &&, || and ^^ respectively); * handle literal values for strings and numbers; * be plaintext not XML (eg "firstname == '' or lastname == ''); and * be reasonably performant. Now in years gone by I've written recursive descent parsers that could build an expression tree and do this kind of thing but thats not a task I'm relishing in PHP so I'm hoping there are things out there that will at least get me some of the way there. Suggestions?
Check [create\_function](http://www.php.net/create_function), it creates an anonymous function from the string parameters passed, I'm not sure about its performance, but it's very flexible...
Much time has gone by since this question was asked, and I happened to be looking for an expression parser for php. I chose to use the [ExpressionLanguage](https://symfony.com/doc/current/components/expression_language.html) component from Symfony 2.4. It can be installed with no dependencies from composer via [packagist](https://packagist.org/packages/symfony/expression-language). `composer require symfony/expression-language`
Dynamic logical expression parsing/evaluation in PHP?
[ "", "php", "parsing", "" ]
> **Possible Duplicate:** > [Can’t operator == be applied to generic types in C#?](https://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c) I've got the following generic class and the compiler complains that "`Operator '!=' cannot be applied to operands of type 'TValue' and 'TValue'`" (see [CS0019](http://msdn.microsoft.com/en-us/library/a63h61ky.aspx)): ``` public class Example<TValue> { private TValue _value; public TValue Value { get { return _value; } set { if (_value != value) // <<-- ERROR { _value= value; OnPropertyChanged("Value"); } } } } ``` If I constrain `TValue` to `class`, I could use `Object.Equals()`. Since I need this for boths structs and classes I'd be very happy if I could avoid that though. So the question is, how can I compare two elements of the same but unconstrained generic type for equality?
Did you try something like this? ``` public class Example<TValue> { private TValue _value; public TValue Value { get { return _value; } set { if (!object.Equals(_value, value)) { _value = value; OnPropertyChanged("Value"); } } } } ```
Three options: * Constrain TValue to implement `IEquatable<TValue>` and then call `x.Equals(y)` * Take another parameter of type `IEqualityComparer<TValue>` and use that * Use `EqualityComparer<TValue>.Default` to perform the comparisons You could always mix and match options 2 and 3, of course - default to the default comparer, but also allow a specific one to be provided.
How to compare two elements of the same but unconstrained generic type for equality?
[ "", "c#", "generics", "class", "struct", "equals", "" ]
I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another. For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development. Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes: **mysite/blog/models.py** ``` from django.db import models class post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() ``` **mysite/comments/models.py** ``` from django.db import models from mysite.blog.models import post class comment(models.Model): id = models.AutoField() post = models.ForeignKey(post) author = models.CharField(max_length=200) text = models.TextField() ``` Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact? **Update** Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this: ``` from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contentypes import generic class comment(models.Model): id = models.AutoField() author = models.CharField(max_length=200) text = models.TextField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey(content_type, id) ``` Would this be correct?
Take a look at django's built-in [contenttypes framework](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes): `django.contrib.contenttypes` It allows you develop your applications as stand-alone units. This is what the django developers used to allow django's built-in [comment framework](http://docs.djangoproject.com/en/dev/ref/contrib/comments/#ref-contrib-comments-index) to attach a comment to any model in your project. For instance, if you have some content object that you want to "attach" to other content objects of different types, like allowing each user to leave a "favorite" star on a blog post, image, or user profile, you can create a `Favorite` model with a [generic relation field](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations) like so: ``` from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Favorite(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') ``` In this way you can add a `Favorite` star from any user to any model in your project. If you want to add API access via the recipient model class you can either add a [reverse generic relation field](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations) on the recipient model (although this would be "coupling" the two models, which you said you wanted to avoid), or do the lookup through the `Favorite` model with the `content_type` and `object_id` of the recipient instance, see the [official docs](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations) for an example.
"Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact?" Yep. Works for me. We have about 10 applications that borrow back and forth among themselves. This leads to a kind of dependency in our unit test script. It looks like this. * "ownership". We have a simple data ownership application that defines some core ownership concepts that other applications depend on. There are a few simple tables here. * "thing". [Not the real name]. Our thing application has data elements owned by different user groups. There are actually several complex tables the model for this app. It depends on "ownership". * "tables". [Not the real name]. Some of our users create fairly complex off-line models (probably with spreadsheets) and upload the results of that modeling in "tables". This has a cluster of fairly complex tables. It depends on "ownership". * "result". [Not the real name]. Our results are based on things which have owners. The results are based on things and tables, and are responses to customer requests. This isn't too complex, perhaps only two or three core tables. It depends on "things" and "table". No, it doesn't completely stand-alone. However, it is subject to more change than the other things on which it depends. That's why it's separate. * "processing". We schedule and monitor big batch jobs. This is in this application. It's really generic, and can be used in a variety of ways. It completely stands alone. * "welcome". We have a "welcome" app that presents a bunch of mostly static pages. This doesn't have too many tables. But it's on it's second incarnation because the first was too complex. It completely stands alone. The only relationship among the dependent apps is some table names. As long as we preserve those tables (and their keys) we can rearrange other apps as we see fit.
Beginner: Trying to understand how apps interact in Django
[ "", "python", "django", "django-models", "django-apps", "" ]
I have a custom XML schema defined for page display that puts elements on the page by evaluating XML elements on the page. This is currently implemented using the preg regex functions, primarily the excellent preg\_replace\_callback function, eg: ``` ... $s = preg_replace_callback("!<field>(.*?)</field>!", replace_field, $s); ... function replace_field($groups) { return isset($fields[$group[1]) ? $fields[$groups[1]] : ""; } ``` Just as an example. Now this works pretty well... so long as the XML elements aren't nested. At this point it gets a whole lot more complicated, like if you have: ``` <field name="outer"> <field name="inner"> ... </field> </field> ``` You want to make sure you replace the innermost field first. Judicious use of greedy/non-greedy regex patterns can go some of the way to handling these more complicated scenarios but the clear message is that I'm reaching the limits of what regex can reasonably do and really I need to be doing XML parsing. What I'd like is an XML transformation package that: allows me to conditionally evaluate/include the contained document tree or not based on a callback function ideally (analagous to preg\_replace\_callback); can handle nested elements of the same or different types; and handles attributes in a nice way (eg as an associative array). What can help me along the way?
PHP's [`XSLTProcessor`](https://www.php.net/manual/en/class.xsltprocessor.php) class ([ext/xsl](https://www.php.net/manual/en/book.xsl.php) - PHP 5 includes the XSL extension by default and can be enabled by adding the argument `--with-xsl[=DIR]` to your configure line) is quite sophisticated and allows among other things the use of PHP functions within your XSL document by using the [`XSLTProcessor::registerPHPFunctions()`](https://www.php.net/manual/en/xsltprocessor.registerphpfunctions.php) method. The following example is shamelessly pinched from the [PHP manual page](https://www.php.net/manual/en/xsltprocessor.registerphpfunctions.php): ``` $xml = '<allusers> <user> <uid>bob</uid> </user> <user> <uid>joe</uid> </user> </allusers>'; $xsl = '<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"> <xsl:output method="html" encoding="utf-8" indent="yes"/> <xsl:template match="allusers"> <html><body> <h2>Users</h2> <table> <xsl:for-each select="user"> <tr><td> <xsl:value-of select="php:function(\'ucfirst\',string(uid))"/> </td></tr> </xsl:for-each> </table> </body></html> </xsl:template> </xsl:stylesheet>'; $xmldoc = DOMDocument::loadXML($xml); $xsldoc = DOMDocument::loadXML($xsl); $proc = new XSLTProcessor(); $proc->registerPHPFunctions(); $proc->importStyleSheet($xsldoc); echo $proc->transformToXML($xmldoc); ```
You can use XSL to do this - just match the inner patterns first. Here is a good starting point for learning what you can do with XSL: <http://www.w3schools.com/xsl/> You can perform the xsl transformation server side or in the client (using js, activex or other). If you still hate this idea of xsl you could look at the xml parsing built into PHP - google for SAX parser PHP- which is a callback implementation to build your custom parser, currently using libxml2.
XML parsing and transformation in PHP?
[ "", "php", "xml", "regex", "parsing", "" ]
I have a site that connects using cURL (latest version) to a secure gateway for payment. The problem is cURL always returns 0 length content. I get headers only. And only when I set cURL to return headers. I have the following flags in place. ``` curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_URL, $gatewayURI); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_POST, 1); ``` The header returned is ``` HTTP/1.1 100 Continue HTTP/1.1 200 OK Date: Tue, 25 Nov 2008 01:08:34 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET Content-Length: 0 Content-Type: text/html Set-Cookie: ASPSESSIONIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; path=/ Cache-control: private ``` I have also tried cURL'ing different sites and they return content fine. I think the problem might have something to do with the https connection. I have spoken with the company and they are unhelpful. Has anyone else experienced this error and know a work around? Should I ditch cURL and try and use `fsockopen()` ? Thank you. :)
You should also try checking the error messages in curl\_error(). You might need to do this once after each curl\_\* function. <http://www.php.net/curl_error>
I had the same problem today. Curl comes with an outdated file to authenticate HTTPS certificates from. get the new one from: <http://curl.haxx.se/ca/cacert.pem> save it into some dir on your site and add ``` curl_setopt ($curl_ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem"); ``` To every request :-) IGNORE any dumbass comments about disabling CURLOPT\_VERIFYPEER and CURLOPT\_VERIFYHOST!! That leaves your code vulnerable to man in the middle attacks! **December 2016 edit:** Solve this properly by using Jasen's method mentioned below. add `curl.cainfo=/etc/ssl/certs/ca-certificates.crt` to you php.ini **October 2017 edit:** There is now a composer package that helps you manage the ca certificates, so that you're not vulnerable if your cacert.pem becomes outdated due to revoking certificates. <https://github.com/paragonie/certainty> -> `composer require paragonie/certainty:dev-master`
Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?
[ "", "php", "curl", "https", "" ]
In C# is there a technique using reflection to determine if a method has been added to a class as an extension method? Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class? ``` public static class StringExtensions { public static string Reverse(this string value) { char[] cArray = value.ToCharArray(); Array.Reverse(cArray); return new string(cArray); } } ``` We're looking for a mechanism to determine in unit testing that the extension method was appropriately added by the developer. One reason to attempt this is that it is possible that a similar method would be added to the actual class by the developer and, if it was, the compiler will pick that method up.
You have to look in all the assemblies where the extension method may be defined. Look for classes decorated with [`ExtensionAttribute`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx), and then methods within that class which are *also* decorated with `ExtensionAttribute`. Then check the type of the first parameter to see if it matches the type you're interested in. Here's some complete code. It could be more rigorous (it's not checking that the type isn't nested, or that there is at least one parameter) but it should give you a helping hand. ``` using System; using System.Runtime.CompilerServices; using System.Reflection; using System.Linq; using System.Collections.Generic; public static class FirstExtensions { public static void Foo(this string x) { } public static void Bar(string x) { } // Not an ext. method public static void Baz(this int x) { } // Not on string } public static class SecondExtensions { public static void Quux(this string x) { } } public class Test { static void Main() { Assembly thisAssembly = typeof(Test).Assembly; foreach (MethodInfo method in GetExtensionMethods(thisAssembly, typeof(string))) { Console.WriteLine(method); } } static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly, Type extendedType) { var isGenericTypeDefinition = extendedType.IsGenericType && extendedType.IsTypeDefinition; var query = from type in assembly.GetTypes() where type.IsSealed && !type.IsGenericType && !type.IsNested from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.IsDefined(typeof(ExtensionAttribute), false) where isGenericTypeDefinition ? method.GetParameters()[0].ParameterType.IsGenericType && method.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == extendedType : method.GetParameters()[0].ParameterType == extendedType select method; return query; } } ```
Based on John Skeet's answer I've created my own extension to the System.Type-type. ``` using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace System { public static class TypeExtension { /// <summary> /// This Methode extends the System.Type-type to get all extended methods. It searches hereby in all assemblies which are known by the current AppDomain. /// </summary> /// <remarks> /// Insired by Jon Skeet from his answer on http://stackoverflow.com/questions/299515/c-sharp-reflection-to-identify-extension-methods /// </remarks> /// <returns>returns MethodInfo[] with the extended Method</returns> public static MethodInfo[] GetExtensionMethods(this Type t) { List<Type> AssTypes = new List<Type>(); foreach (Assembly item in AppDomain.CurrentDomain.GetAssemblies()) { AssTypes.AddRange(item.GetTypes()); } var query = from type in AssTypes where type.IsSealed && !type.IsGenericType && !type.IsNested from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.IsDefined(typeof(ExtensionAttribute), false) where method.GetParameters()[0].ParameterType == t select method; return query.ToArray<MethodInfo>(); } /// <summary> /// Extends the System.Type-type to search for a given extended MethodeName. /// </summary> /// <param name="MethodeName">Name of the Methode</param> /// <returns>the found Methode or null</returns> public static MethodInfo GetExtensionMethod(this Type t, string MethodeName) { var mi = from methode in t.GetExtensionMethods() where methode.Name == MethodeName select methode; if (mi.Count<MethodInfo>() <= 0) return null; else return mi.First<MethodInfo>(); } } } ``` It get's all assemblies from the current AppDomain and searches for extended methods. Usage: ``` Type t = typeof(Type); MethodInfo[] extendedMethods = t.GetExtensionMethods(); MethodInfo extendedMethodInfo = t.GetExtensionMethod("GetExtensionMethods"); ``` The next step would be to extend System.Type with methods, which returns all Methods (also the "normal" ones with the extended ones)
Reflection to Identify Extension Methods
[ "", "c#", "reflection", "extension-methods", "" ]
I need to edit (using javascript) an SVG document embedded in an html page. When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded. To access the SVG dom, I use this code: ``` var svg = document.getElementById("chart").getSVGDocument(); ``` where "chart" is the id of the embed element. If I try to access the SVG when the html document is ready, in this way: ``` jQuery(document).ready( function() { var svg = document.getElementById("chart").getSVGDocument(); ... ``` svg is always null. I just need to know when it is not null, so I can start manipulate it. Do you know if there is a way to do it?
You could try polling every so often. ``` function checkReady() { var svg = document.getElementById("chart").getSVGDocument(); if (svg == null) { setTimeout("checkReady()", 300); } else { ... } } ```
On your embedding element (e.g 'embed', 'object', 'iframe') in the main document add an `onload` attribute which calls your function, or add the event listener in script, e.g `embeddingElm.addEventListener('load', callbackFunction, false)`. Another option might be to listen for `DOMContentLoaded`, depends on what you want it for. You can also add a load listener on the main document. `jQuery(document).ready` doesn't mean that all resources are loaded, just that the document itself has a DOM that is ready for action. However note that if you listen for load on the entire document your callback function won't be called until all resources in that document are loaded, css, javascript etc. If you use inline svg, then `jQuery(document).ready` will work just fine however. On a further note you might want to consider using `embeddingElm.contentDocument` (if available) instead of `embeddingElm.getSVGDocument()`.
How to check if an embedded SVG document is loaded in an html page?
[ "", "javascript", "jquery", "dom", "svg", "" ]
What's the easiest way to use a linked list in Python? In Scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
Here is some list functions based on [Martin v. Löwis's representation](https://stackoverflow.com/questions/280243/python-linked-list#280284): ``` cons = lambda el, lst: (el, lst) mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None) car = lambda lst: lst[0] if lst else lst cdr = lambda lst: lst[1] if lst else lst nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst) length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count begin = lambda *args: args[-1] display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n") ``` where `w = sys.stdout.write` Although doubly linked lists are famously used in Raymond Hettinger's [ordered set recipe](http://code.activestate.com/recipes/576694-orderedset/), singly linked lists have no practical value in Python. I've *never* used a singly linked list in Python for any problem except educational. Thomas Watnedal [suggested](https://stackoverflow.com/questions/280243/python-linked-list#280280) a good educational resource [How to Think Like a Computer Scientist, Chapter 17: Linked lists](http://greenteapress.com/thinkpython/html/chap17.html): A linked list is either: * the empty list, represented by None, or * a node that contains a cargo object and a reference to a linked list. ``` class Node: def __init__(self, cargo=None, next=None): self.car = cargo self.cdr = next def __str__(self): return str(self.car) def display(lst): if lst: w("%s " % lst) display(lst.cdr) else: w("nil\n") ```
For some needs, a [deque](https://docs.python.org/library/collections.html#collections.deque) may also be useful. You can add and remove items on both ends of a deque at O(1) cost. ``` from collections import deque d = deque([1,2,3,4]) print d for x in d: print x print d.pop(), d ```
How can I use a Linked List in Python?
[ "", "python", "linked-list", "" ]
I have a command-line process I would like to automate and capture in C#. At the command line, I type: ``` nslookup ``` This launches a shell which gives me a > prompt. At the prompt, I then type: ``` ls -a mydomain.local ``` This returns a list of local CNAMEs from my primary DNS server and the physical machines they are attached to. What I would like to do is automate this process from C#. If this were a simple command, I would just use Process.StartInfo.RedirectStandardOutput = true, but the requirement of a second step is tripping me up.
``` ProcessStartInfo si = new ProcessStartInfo("nslookup"); si.RedirectStandardInput = true; si.RedirectStandardOutput = true; Process nslookup = new Process(si); nslookup.Start(); nslookup.StandardInput.WriteLine("ls -a mydomain.local"); nslookup.StandardInput.Flush(); // use nslookup.StandardOutput stream to read the result. ```
Not what you asked, but I once wrote an app that did what you're doing. I eventually moved to using a .NET library to do the DNS lookups, which turned out to be a lot faster. I'm pretty sure I used [this library](http://www.codeproject.com/KB/IP/DNS_NET_Resolver.aspx) from the CodeProject site.
Capturing nslookup shell output with C#
[ "", "c#", "shell", ".net-2.0", "nslookup", "" ]
I plan on using MySQL and it's built-in encryption functionality to encrypt / decrypt certain columns in certain tables. The concern I have is that I need to store the key somewhere. I could certainly store the key in a file and control the permissions of that file and the permissions of the application that accesses it, but is that enough? I could also create a web service to get the key or something. I am in a small shop where I would be the only one (possibly one other person) that would have access to the machine that the application was on. **Edit: I should add that there is a web facing part of this application that would need to decrypt the data unless I added a tier.** I have looked ad nauseum, but no one seems to have a bulletproof answer. Is this one of those problems where you have to settle for good enough? Given that I am using MySQL and PHP (possibly Python) is there a better way to approach this?
I'm not sure if using MySQL build in encryption would be the best solution to your problem. PHP's [M\_CRYPT](http://www.php.net/manual/en/intro.mcrypt.php) package is thought to be quite good and it gives you the flexibility to choose the algorithm that is best suited for your needs. Storing your key on some other server has one big advantage: the key is not on the same machine as the encrypted data\*). So as long as the attacker does not have enough control over the compromised machine, they cannot get to the key. If the attacker gains full control of the machine the data is stored on, they most likely will be able to query the web-service for the key. However, transmitting the key from one machine to another opens up an entire new area that needs to be secured. Probably involving more key's and more encryption layers, thereby increasing the chance of mistakes being made. \*) The other option is to enter the password upon webserver start up and only keep it in memory. **Possible solution** If seen a solution employed that used the following method for encrypting files for users with web access (I'm not sure of your environment, but it might be helpful): * Upon user creation, a long random key is assigned to the new user. * This random key is stored in an encrypted column in the user record. (*only this column is encrypted as to not affect the performance of the rest of the record!*) * The encryption of the random-key column is done with 1 master password, stored in a file or in memory. (*The better option is to enter the password upon staring your webserver and only store it in memory.*) (*Another approach would be to let the user enter a password and use that to encrypt/decrypt the random-key column, but I'm not sure if that would increase or decrease security*) * Every document that needs to be encrypted is encrypted with the random-key for that user and then stored on disk. * Documents are stored with minimal permissions in the file-system. **The advantages of this approach are:** 1. The random-key is encrypted in the database. So you still have the added security of the database-server, in combination with the encrypted column. 2. Documents are stored with different keys, if the attacker gets hold of a key, only part of the documents is compromised. *However:* If the attacker gets hold of the master password and has read access to the user-table, the entire system is, once more, broken.
I'd probably store it in a file that is in a non-web-accessible directory and locked down with file system permissions as much as possible. Your web-facing script should not open any file system files using variables, especially user-provided ones. Don't even give them the option of slipping something passed your input filter (you are filtering your user-provided data right?) and possibly giving up the contents of the key file. Keep file paths to hard-coded strings and define()'s only. Since most of your data is stored in MySQL, this shouldn't be a problem. When doing the decryption, read the key into a cleanly initialized variable, do the decryption, then overwrite the key variable (say with a string of x's) and unset the variable. This probably all sounds a bit paranoid but if you minimize the time the key is in the clear in memory and isolate it from all the other variables flying around your PHP script it can't make you any ***less*** secure. If you and the one other person are the only ones that have physical access to the machine, this is probably just fine. If someone breaks in and steals the box, well, they've got all your data anyway so game over.
What's the best method to use / store encryption keys in MySQL
[ "", "php", "mysql", "security", "encryption", "key", "" ]
I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML: ``` <div id="menu"> <div class="menuItem"><a href=#>Bla</a></div> <div class="menuItem"><a href=#>Bla</a></div> <div class="menuItem"><a href=#>Bla</a></div> </div> ``` CSS: ``` .menuItem{ display:inline; height:30px; width:100px; background-color:#000; } ``` Javascript: ``` $('.menuItem').hover( function(){ $(this).css('background-color', '#F00'); }, function(){ $(this).css('background-color', '#000'); }); ``` **EDIT:** I forgot to say that I had reasons not to want to use the css way. And I indeed forgot to check if the DOM was loaded.
Your code looks fine to me. Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function: ``` $(function() { $('.menuItem').hover( function(){ $(this).css('background-color', '#F00'); }, function(){ $(this).css('background-color', '#000'); }); }); ```
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript. You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element. ``` .menuItem { display: inline; background-color: #000; /* width and height should not work on inline elements */ /* if this works, your browser is doing the rendering */ /* in quirks mode which will not be compatible with */ /* other browsers - but this will not work on touch mobile devices like android */ } .menuItem a:hover { background-color:#F00; } ```
jQuery hover and class selector
[ "", "javascript", "jquery", "html", "css", "" ]
Does anyone know where I can find an example of how to determine if the Maximize and/or Minimize buttons on a window are available and/or disabled? The window will not be in the same process as my application. I have the hWnd and I have tried using GetMenuItemInfo, but I can't find any good samples for how to do this. Thanks!
``` bool has_maximize_btn = (GetWindowLong(hWnd, GWL_STYLE) & WS_MAXIMIZEBOX) != 0; bool has_minimize_btn = (GetWindowLong(hWnd, GWL_STYLE) & WS_MINIMIZEBOX) != 0; ```
The Win32 API provides the [**GetTitleBarInfo** function](http://msdn.microsoft.com/en-us/library/ms633513(VS.85).aspx) which returns a [**TITLEBARINFO** Structure](http://msdn.microsoft.com/en-us/library/ms632608(VS.85).aspx): ``` typedef struct { DWORD cbSize; RECT rcTitleBar; DWORD rgstate[CCHILDREN_TITLEBAR+1]; } TITLEBARINFO, *PTITLEBARINFO, *LPTITLEBARINFO; ``` So you could check the `rgstate`: Pointer to an array that receives a DWORD value for each element of the title bar. The following are the title bar elements represented by the array. ``` Index Title Bar Element ----- -------------------- 0 The title bar itself 1 Reserved. 2 Minimize button 3 Maximize button <-------------- 4 Help button 5 Close button ``` Each array element is a combination of one or more of the following values. ``` Value Meaning ----- ------------------------------------------- STATE_SYSTEM_FOCUSABLE The element can accept the focus. STATE_SYSTEM_INVISIBLE The element is invisible. STATE_SYSTEM_OFFSCREEN The element has no visible representation. STATE_SYSTEM_UNAVAILABLE The element is unavailable. STATE_SYSTEM_PRESSED The element is in the pressed state.rgstate ```
Determining if the Maximize button is available
[ "", "c#", "winapi", "" ]
is there a managed code (without adding COM component or wrapped called to C++ routines) way to add integrated security to a C# Managed code assembly? i.e. I want to write a client-server system where the server uses Remoting instead of IIS, but I want the client to automatically pass it's credentials to the server just like a browser does when communicating with an IIS server that has Integrated security enabled... Can this be done? and if so, where is there some examples ?
No - there is no pure managed interface to [SSPI](http://msdn.microsoft.com/en-us/library/aa380493(VS.85).aspx). But, there is an MSDN sample that [wraps SSPI for you](http://msdn.microsoft.com/en-us/library/ms973911.aspx), and then [uses the wrapper for remoting](http://msdn.microsoft.com/en-us/library/ms973909.aspx).
.NET 2 has NegotiateStream which is used by TCP remoting to provide SSPI.
Integrated Security
[ "", "c#", "remoting", "windows-authentication", "" ]
How can I receive and send email in python? A 'mail server' of sorts. I am looking into making an app that listens to see if it receives an email addressed to foo@bar.domain.com, and sends an email to the sender. Now, am I able to do this all in python, would it be best to use 3rd party libraries?
Here is a very simple example: ``` import smtplib server = 'mail.server.com' user = '' password = '' recipients = ['user@mail.com', 'other@mail.com'] sender = 'you@mail.com' message = 'Hello World' session = smtplib.SMTP(server) # if your SMTP server doesn't need authentications, # you don't need the following line: session.login(user, password) session.sendmail(sender, recipients, message) ``` For more options, error handling, etc, look at the [smtplib module documentation](http://www.python.org/doc/2.5.2/lib/module-smtplib.html).
Found a helpful example for reading emails by connecting using IMAP: [Python — imaplib IMAP example with Gmail](http://yuji.wordpress.com/2011/06/22/python-imaplib-imap-example-with-gmail/) ``` import imaplib mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('myusername@gmail.com', 'mypassword') mail.list() # Out: list of "folders" aka labels in gmail. mail.select("inbox") # connect to inbox. result, data = mail.search(None, "ALL") ids = data[0] # data is a list. id_list = ids.split() # ids is a space separated string latest_email_id = id_list[-1] # get the latest # fetch the email body (RFC822) for the given ID result, data = mail.fetch(latest_email_id, "(RFC822)") raw_email = data[0][1] # here's the body, which is raw text of the whole email # including headers and alternate payloads ```
Receive and send emails in python
[ "", "python", "email", "" ]
I'm a little new to the Java 5 annotations and I'm curious if either of these are possible: This annotation would generate a simple getter and setter for you. ``` @attribute private String var = ""; ``` The `@NotNull` annotation indicates that a variable connot be null so you don't have to write that boilerplate code every time. ``` /* * @param s @NotNull */ public void setString(String s){ ... } ``` Will either of these work? They seem like the first things I would write annotations for if I could. Since I don't see much about these when I read the docs I'm assuming that it's not really what annotations are about. Any direction here would be appreciated.
Annotation processing occurs on the abstract syntax tree. This is a structure that the parser creates and the compiler manipulates. The current specification (link to come) says that annotation processors cannot alter the abstract syntax tree. One of the consequences of this is that it is not suitable to do code generation. If you'd like this sort of functionality, then have a look at [XDoclet](http://xdoclet.sourceforge.net/xdoclet/index.html). This should give you the code generation preprocessing I think you are looking for. For your `@NonNull` example, [JSR-305](http://jcp.org/en/jsr/detail?id=305) is a [set of annotations](http://today.java.net/cs/user/print/a/549) to enhance software defect detection, and includes `@NonNull` and `@CheckForNull` and a host of others. *Edit*: [Project Lombok](http://projectlombok.org/features/index.html) solves exactly the problem of getter and setter generation.
Getters/Setters: Yes, it is possible. The [Project Lombok](http://projectlombok.org/features/index.html) (<http://projectlombok.org/index.html>) defines annotations for generating getters/setters and more. So for example ``` @lombok.Data; public class Person { private final String name; private int age; } ``` Will generate `getName` (no setter since the variable is final) and `getAge`/`setAge`. It will also generate `equals`, `hashCode`, `toString` and aconstructor initializing the required fields (`name` in this case). Adding `@AllArgsConstructor` would generate a constructor initializing both fields. Using [`@Value`](https://projectlombok.org/features/Value) instead of `@Data` will make the objects immutable. There are other annotations and parameters giving you control over access rights (should your getter be protected or public), names (`getName()` or `name()`?), etc. And there is more. For example, I really like the annotations for [builders](https://projectlombok.org/features/Builder) and [extension methods](https://projectlombok.org/features/experimental/ExtensionMethod). Lombok is very easy to use: * Just download the jar and use the annotations, the automatically generated getter/setters can be used in your code without actually being spelled out. * The annotations are used only during compilation not during runtime, so you don't distribute lombok with your jar's. * Most IDE's support this, so that you see the getter/setter in code completion, navigation, etc. In Netbeans this works [out of the box](https://projectlombok.org/setup/netbeans). In IntelliJ IDEA use the [Lombok plugin](https://plugins.jetbrains.com/plugin/6317-lombok). NotNull: This is supported by findbugs and IDEA IDE, maybe others
Is there a way to use annotations in Java to replace accessors?
[ "", "java", "annotations", "metaprogramming", "" ]
I'm using hibernate 3 and want to stop it from dumping all the startup messages to the console. I tried commenting out the stdout lines in log4j.properties but no luck. I've pasted my log file below. Also I'm using eclipse with the standard project structure and have a copy of log4j.properties in both the root of the project folder and the bin folder. ``` ### direct log messages to stdout ### #log4j.appender.stdout=org.apache.log4j.ConsoleAppender #log4j.appender.stdout.Target=System.out #log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file hibernate.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=hibernate.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=warn, stdout #log4j.logger.org.hibernate=info log4j.logger.org.hibernate=debug ### log HQL query parser activity #log4j.logger.org.hibernate.hql.ast.AST=debug ### log just the SQL #log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### log4j.logger.org.hibernate.type=info #log4j.logger.org.hibernate.type=debug ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=debug ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log transaction activity #log4j.logger.org.hibernate.transaction=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trac5 ```
Try to set more reasonable logging level. Setting logging level to `info` means that only log event at `info` or higher level (`warn`, `error` and `fatal`) are logged, that is `debug` logging events are ignored. ``` log4j.logger.org.hibernate=info ``` or in [XML version](http://wiki.apache.org/logging-log4j/Log4jXmlFormat) of log4j config file: ``` <logger name="org.hibernate"> <level value="info"/> </logger> ``` See also [log4j manual](http://logging.apache.org/log4j/1.2/manual.html).
Important notice: the property (part of hibernate configuration, NOT part of logging framework config!) ``` hibernate.show_sql ``` controls the logging *directly* to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like log4j, **you should *always* set that property to false** because it gives you no benefit at all. That circumstance irritated me quite a long time because I never really cared about it until I tried to write some benchmark regarding Hibernate. **Spring** (tested with spring-boot 3.0.6 and hibernate 5.6.15) If you're using Spring Boot with properties file: ``` spring.jpa.properties.hibernate.show_sql=false ```
Turning off hibernate logging console output
[ "", "java", "hibernate", "logging", "" ]
The code I have pasted below is meant to display images on the middle 2 links without text and go back to text on the reset and fourth link. I have set display:none for the span tag only, but it does nothing. Is there anyway to do what I am after simply, without using a framework? edit: example ``` <html> <head> <style type="text/css"> .class1{color:#000; background-image:url('1.jpg');} .class1 span { display: none;} .class2{color:#00f; background-image:url('2.jpg');} .class2 span { display: none;} .class3{color:#0f0; background-image:url('1.jpg');} .class3 span { display: none;} .class4{color:#f00;} </style> </head> <body> <script type="text/javascript"> function sbox(divid, classname) { document.getElementById(divid).className=classname; } </script> <div> <a href="#" onclick="sbox('div1','class1');return false;">Reset</a><br/> <a href="#" onclick="sbox('div1','class2');return false;">try here</a><br/> <a href="#" onclick="sbox('div1','class3'); return false;">or here</a><br/> <a href="#" onclick="sbox('div1','class4');return false;">or maybe here</a> </div> <div id="div1" class="class4"><span id="div1_text">Blah blah blah</span></div> </body> </html> ```
The `rel` attribute is supposed to describe the relationship of the link to the current document. It should have one of the values described [here](http://www.w3.org/TR/html401/types.html#type-links). A DIV is a block-level grouping element, whereas a SPAN is an inline grouping element. SPANs allow you to group text and tags together for some purpose (common styles, etc.) without changing the flow of the markup. **EDIT:** The question changed out from under me so the above seems really disconnected from the current context. You need to do as @llandril says and give the DIV some size. I would suggest giving the DIV fixed width and height -- either always or when one of the classes that displays an image is used. Use the width and height of your background image if you want the whole thing displayed. You may also need to give it some content as well, but I don't think so. Here is what class1 would look like, I think. I haven't tested this. ``` /* in case color needs to apply to other elements */ .class1 { color: #000; } div .class1 { background-image:url('1.jpg'); width: 60px; height: 30px; } div .class1 span { display: none;} ```
The div tag encloses a block of content. The span tag is similar, but encloses inline content. Difference? You can use span to style a phrase inside a paragraph, but div to wrap that paragraph and separate it from others. See [this](http://www.w3schools.com/tags/tag_DIV.asp) for divs, and [this](http://www.w3schools.com/tags/tag_span.asp) for spans. After some comments: here it is, [from the horse's mouth:](http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.4) > The DIV and SPAN elements, in conjunction with the id and class attributes, offer a generic mechanism for adding structure to documents. These elements define content to be inline (SPAN) or block-level (DIV) but impose no other presentational idioms on the content. Thus, authors may use these elements in conjunction with style sheets, the lang attribute, etc., to tailor HTML to their own needs and tastes.
css page problem
[ "", "javascript", "html", "css", "" ]
I need to perform a HTTP GET from PHP. More specifically, from within /index.php I need to get the content of /trac/ and /svn/, find the "ul" element and then render then inline on the index.php. /trac and /svn are relative URLs and not filesystem folders. <http://myserver/trac> and <http://myserver/svn>
The simplest way is [`file_get_contents()`](http://www.php.net/file_get_contents). ``` $str = file_get_contents('http://myserver/svn/'); // Or, if you don't want to hardcode the server $str = file_get_contents('http://' . $_SERVER['HTTP_HOST'] . '/svn/'); if ($str) { // Find the ul } ```
I suggest you have a look at... * the [HTTP\_Request2](http://pear.php.net/package/HTTP_Request2) PEAR Package, * the [CURL Library](http://de3.php.net/manual/en/book.curl.php) in PHP (if installed) or * plain [Filesystem Functions](http://de3.php.net/manual/en/ref.filesystem.php) in PHP (if you have [allow\_url\_fopen](http://de3.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) enabled).
PHP HttpRequest
[ "", "php", "" ]
Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing. ``` $customer['address'] = '123 fake st'; $customer['name'] = 'Tim'; $customer['dob'] = '12/08/1986'; $customer['dontSortMe'] = 'this value doesnt need to be sorted'; ``` And I'd like to do something like ``` $properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address')); ``` Because at the end I use a foreach() and they're not in the right order (because I append the values to a string which needs to be in the correct order and I don't know in advance all of the array keys/values). I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically.
Just use [`array_merge`](https://www.php.net/manual/en/function.array-merge.php) or [`array_replace`](https://www.php.net/manual/en/function.array-replace.php). `array_merge` works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array: ``` $customer['address'] = '123 fake st'; $customer['name'] = 'Tim'; $customer['dob'] = '12/08/1986'; $customer['dontSortMe'] = 'this value doesnt need to be sorted'; $properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer); // or $properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer); // $properOrderedArray: array( // 'name' => 'Tim', // 'dob' => '12/08/1986', // 'address' => '123 fake st', // 'dontSortMe' => 'this value doesnt need to be sorted') ``` PS: I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.
There you go: ``` function sortArrayByArray(array $array, array $orderArray) { $ordered = array(); foreach ($orderArray as $key) { if (array_key_exists($key, $array)) { $ordered[$key] = $array[$key]; unset($array[$key]); } } return $ordered + $array; } ```
Custom key-sort a flat associative based on another array
[ "", "php", "arrays", "sorting", "key", "associative-array", "" ]
Where I work, people mostly think that objects are best initialised using C++-style construction (with parentheses), whereas primitive types should be initialised with the = operator: ``` std::string strFoo( "Foo" ); int nBar = 5; ``` Nobody seems to be able to explain why they prefer things this way, though. I can see that `std::string strFoo = "Foo";` would be inefficient because it would involve an extra copy, but what's wrong with just banishing the `=` operator altogether and using parentheses everywhere? Is it a common convention? What's the thinking behind it?
Unless you've proven that it matters with respect to performance, I wouldn't worry about an extra copy using the assignment operator in your example (`std::string foo = "Foo";`). I'd be pretty surprised if that copy even exists once you look at the optimized code, I believe that will actually call the appropriate parameterized constructor. In answer to your question, yes, I'd say that it's a pretty common convention. Classically, people have used assignment to initialize built-in types, and there isn't a compelling reason to change the tradition. Readability and habit are perfectly valid reasons for this convention given how little impact it has on the ultimate code.
Initializing variables with the = operator or with a constructor call are semantically the same, it's just a question of style. I prefer the = operator, since it reads more naturally. Using the = operator *usually* does not generate an extra copy - it just calls the normal constructor. Note, however, that with non-primitive types, this is only for initializations that occur at the same time as the declarations. Compare: ``` std::string strFooA("Foo"); // Calls std::string(const char*) constructor std::string strFoo = "Foo"; // Calls std::string(const char*) constructor // This is a valid (and standard) compiler optimization. std::string strFoo; // Calls std::string() default constructor strFoo = "Foo"; // Calls std::string::operator = (const char*) ``` When you have non-trivial default constructors, the latter construction can be slightly more inefficient. The [C++ standard](http://www.parashift.com/c++-faq-lite/big-picture.html#faq-6.13), section 8.5, paragraph 14 states: > Otherwise (i.e., for the remaining copy-initialization cases), a temporary is created. User-defined conversion sequences that can convert from the source type to the destination type or a derived class thereof are enumerated (13.3.1.4), and the best one is chosen through overload resolution (13.3). The user-defined conversion so selected is called to convert the initializer expression into a temporary, whose type is the type returned by the call of the user-defined conversion function, with the cv-qualifiers > of the destination type. If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The object being initialized is then direct-initialized > from the temporary according to the rules above.87) **In certain cases, an implementation is permitted to eliminate the temporary by initializing the object directly; see 12.2.** Part of section 12.2 states: > Even when the creation of the temporary object is avoided, all the semantic restrictions must be respected as if the temporary object was created. [Example: > even if the copy constructor is not called, all the semantic restrictions, such as accessibility (11), shall be satisfied. ]
Why use = to initialise a primitive type in C++?
[ "", "c++", "coding-style", "c++03", "" ]
I've used [UPX](http://upx.sourceforge.net/) before to reduce the size of my Windows executables, but I must admit that I am naive to any negative side effects this could have. What's the downside to all of this packing/unpacking? Are there scenarios in which anyone would recommend NOT UPX-ing an executable (e.g. when writing a DLL, Windows Service, or when targeting Vista or Win7)? I write most of my code in Delphi, but I've used UPX to compress C/C++ executables as well. On a side note, I'm **not** running UPX in some attempt to protect my exe from disassemblers, only to reduce the size of the executable and prevent cursory tampering.
> ... there are downsides to > using EXE compressors. Most notably: > > * Upon startup of a compressed EXE/DLL, all of the code is > decompressed from the disk image into > memory in one pass, which can cause > disk thrashing if the system is low on > memory and is forced to access the > swap file. In contrast, with > uncompressed EXE/DLLs, the OS > allocates memory for code pages on > demand (i.e. when they are executed). > * Multiple instances of a compressed EXE/DLL create multiple > instances of the code in memory. If > you have a compressed EXE that > contains 1 MB of code (before > compression) and the user starts 5 > instances of it, approximately 4 MB of > memory is wasted. Likewise, if you > have a DLL that is 1 MB and it is used > by 5 running applications, > approximately 4 MB of memory is > wasted. With uncompressed EXE/DLLs, > code is only stored in memory once and > is shared between instances. <http://www.jrsoftware.org/striprlc.php#execomp>
I'm surprised this hasn't been mentioned yet but using UPX-packed executables also increases the risk of producing false-positives from heuristic anti-virus software because statistically a lot of malware also uses UPX.
Are there any downsides to using UPX to compress a Windows executable?
[ "", "c++", "delphi", "winapi", "compression", "upx", "" ]
I'm wondering what good ways there would be make assertions about synchronization or something so that I could detect synchronization violations (while testing). That would be used for example for the case that I'd have a class that is not thread-safe and that isn't going to be thread-safe. With some way I would have some assertion that would inform me (log or something) if some method(s) of it was called from multiple threads. I'm longing for something similar that could be made for AWT dispatch thread with the following: ``` public static void checkDispatchThread() { if(!SwingUtilities.isEventDispatchThread()) { throw new RuntimeException("GUI change made outside AWT dispatch thread"); } } ``` I'd only want something more general. The problem description isn't so clear but I hope somebody has some good approaches =)
You are looking for the holy grail, I think. AFAIK it doesn't exist, and Java is not a language that allows such an approach to be easily created. "Java Concurrency in Practice" has a section on testing for threading problems. It draws special attention to how hard it is to do.
When an issue arises over threads in Java it is usually related to deadlock detection, more than just monitoring what Threads are accessing a synchronized section at the same time. [JMX](http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/) extension, added to JRE since 1.5, can help you detect those deadlocks. In fact we use JMX inside our own software to automatically detect deadlocks an trace where it was found. Here is an [example](http://www.javaspecialists.co.za/archive/Issue093.html) about how to use it.
How to detect synchronization violations with Java
[ "", "java", "multithreading", "synchronization", "error-detection", "" ]
I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use `os.walk` but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.
``` import glob, os, shutil files = glob.iglob(os.path.join(source_dir, "*.ext")) for file in files: if os.path.isfile(file): shutil.copy2(file, dest_dir) ``` Read the [documentation](http://www.python.org/doc/2.5.2/lib/module-shutil.html) of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()).
If you're not recursing, you don't need walk(). Federico's answer with glob is fine, assuming you aren't going to have any directories called ‘something.ext’. Otherwise try: ``` import os, shutil for basename in os.listdir(srcdir): if basename.endswith('.ext'): pathname = os.path.join(srcdir, basename) if os.path.isfile(pathname): shutil.copy2(pathname, dstdir) ```
How do I copy files with specific file extension to a folder in my python (version 2.5) script?
[ "", "python", "file", "copy", "" ]
Can anyone explain the difference between the types mentioned above and some sample usage to clearly explain the difference between the two? Any help would be highly appreciated! Note: this question is a spin-off from [this other question](https://stackoverflow.com/questions/324168/msxml2ixmldomdocument2ptr-getxml-messing-up-my-string)
`BSTR` is the string data type used with COM. `_bstr_t` is a wrapper class that works like a smart pointer, so it will free the allocated memory when the variable is destroyed or goes out of scope. `_bstr_t` also has reference counting, which increases every time you pass the `_bstr_t` variable by value (avoiding unnecessary copy) and decrement when it is no longer used. Whenever all references are destroyed, the allocated memory for the string is freed. An alternative to `BSTR` is the `CComBSTR`. It also manages the memory for the `BSTR`, but has no reference counting.
**BSTR** is a raw pointer, while **`_bstr_t`** is a class encapsulating that pointer. It's the same difference as **char\*** vs. **std::string**.
What's the difference between BSTR and _bstr_t?
[ "", "c++", "com", "smart-pointers", "" ]
Are there any alternatives to JSTL? One company I worked for 3 years ago used JSTL and custom tag libraries to separate presentation from logic. Front-end developers used EL to do complex presentation logic, generate layouts in JSP pages and it worked out great. Perhaps new technologies have come out. Anything better these days?
JSTL and EL are two distinct concepts. JSTL is just one tag library. Most frameworks provide their own taglib that approximately duplicates the functionality of JSTL. I say approximately, because these often misuse or overlook key principles of JSP and the Servlet API. The strength of JSTL is that it was designed by the authors of JSP, with a solid understanding of JSP and servlets. Third-party taglibs are often created by some guy who didn't want to RTFM and decided to "start from scratch" and come up with "something simpler". However, JSTL wasn't intended to do everything. It can be used very successfully in conjunction with other taglibs, including your own custom tags. Expression language is fundamental to JSP. It is interpreted by the container, and can be used in many contexts. It is also largely side-effect free, and has a simple, easily comprehensible syntax that doesn't allow a lot of logic to get stuffed into the presentation layer. Being part of the Java EE spec, it also enjoys wide tool support. For example, many IDEs can refactor dependent EL expression when you rename a property. Struts2 introduced OGNL to a wider audience. OGNL is a throwback to the evil days of scriptlets. It is more powerful, and so developers happily abuse it to invoke arbitrary methods in the presentation layer and other atrocities. Attackers happily exploit it too; it is a common source of [vulnerabilities in Struts2-based applications.](http://struts.apache.org/release/2.3.x/docs/security-bulletins.html) I was familiar with OGNL from years of previous experience with WebWork, and my greatest disappointment in Struts2 was the failure to jettison this dreck. Even WebWork founder, Patrick Lightbody, [acknowledges that adoption was a mistake.\*](https://news.ycombinator.com/item?id=6081428) Luckily, it can only be used in limited contexts, like OGNL-aware tags (and some other surprising places), unlike EL, which is supported by the container itself and can be used anywhere in a page. If you want to get away from JSP, but aren't into a component-based approach like JSF, you might check out Terrence Parr's [StringTemplate](http://www.stringtemplate.org/) project. The focus there is to be side-effect–free, which gives valuable improvements to safety and scalability. \* QFT: After a successful attack on the Struts2-based Apple Developer site, Patrick Lightbody said, "Sadly, I feel some responsibility for this pretty major security hole. There have been a few like this and they are all rooted in the fact that almost 9 years ago I made the (bad) decision to use OGNL as WebWork's expression language. I did so because it was 'powerful' but it opened up all sorts of extra binding trickery I never intended."
I've used [velocity](http://velocity.apache.org/) with great success and it works great as a simple way to separate business logic from presentation logic. And it's simple enough that your average web developer can understand it. [Freemarker](http://freemarker.sourceforge.net/) is another templating alternative that a lot of people like, as well.
What are the alternatives to JSTL?
[ "", "java", "model-view-controller", "jsp", "jstl", "" ]
With generics, is there ever a reason to create specific derived EventArg classes It seems like now you can simply use them on the fly with a generic implementation. Should i go thorugh all of my examples and remove my eventArg classes (StringEventArgs, MyFooEventArgs, etc . .) ``` public class EventArgs<T> : EventArgs { public EventArgs(T value) { m_value = value; } private T m_value; public T Value { get { return m_value; } } } ```
What you are describing are essentially [tuples](http://en.wikipedia.org/wiki/Tuple), grouped values used for a particular purpose. They are a useful construct in [functional programming](http://en.wikipedia.org/wiki/Functional_programming) and support that style very well. The downside is that their values are not named, and they require context to be understood. `EventArgs` by their very nature are often consumed far away from their relevant context. Therefore, tuple-esque `EventArgs` can be very confusing for the consumer. Let's say we have an event indicating some division has been completed, and it carries the numerator, denominator, and result: ``` public event EventHandler<EventArgs<double, double, double>> Divided; ``` The event handler has some ambiguity: ``` private void OnDivided(object sender, EventArgs<double, double, double> e) { // I have to just "know" this - it is a convention var numerator = e.Value1; var denominator = e.Value2; var result = e.Value3; } ``` This would be much clearer with an `EventArgs` representing the event: ``` private void OnDivided(object sender, DividedEventArgs e) { var numerator = e.Numerator; var denominator = e.Denominator; var result = e.Result; } ``` Generic reusable `EventArgs` classes ease development of the mechanism at the expense of expressing intent.
Look at the [Custom Generic EventArgs](http://www.c-sharpcorner.com/UploadFile/rmcochran/customgenericeventargs05132007100456AM/customgenericeventargs.aspx) article written by [Matthew Cochran](http://www.c-sharpcorner.com/Authors/AuthorDetails.aspx?AuthorID=rmcochran), in that article he describes how to expand it even further with two and three members. Using generic EventArgs have their uses, and of course their misuses, as type information is lost in the process. ``` public class City {...} public delegate void FireNuclearMissile(object sender, EventArgs<City> args); public event FireNuclearMissile FireNuclearMissileEvent; public delegate void QueryPopulation(object sender, EventArgs<City> args); public event QueryPopulation QueryPopulationEvent; ``` In the following example it is type-safe, but a bit more LOC: ``` class City {...} public class FireNuclearMissileEventArgs : EventArgs { public FireNuclearMissileEventArgs(City city) { this.city = city; } private City city; public City City { get { return this.city; } } } public delegate void FireNuclearMissile(object sender, FireNuclearMissileEventArgs args); public event FireNuclearMissile FireNuclearMissileEvent; public class QueryPopulationEventArgs : EventArgs { public QueryPopulationEventArgs(City city) { this.city = city; } private City city; public City City { get { return this.city; } } } public delegate void QueryPopulation(object sender, QueryPopulationEventArgs args); public event QueryPopulation QueryPopulationEvent; ```
Are EventArg classes needed now that we have generics
[ "", "c#", "generics", "eventargs", "" ]
I am making a Color class, and provide a standard constructor like ``` Color(int red, int green, int blue) ``` And then I want to provide an easy way to get the most common colors, like Color.Blue, Color.Red. I see two possible options: ``` public static readonly Color Red = new Color(255, 0, 0); public static Color Red { get { return new Color(255, 0, 0); } } ``` What I don't fully understand is if there is an advantage of one over the other, and how exactly the static keyword works. My thoughts are: The first creates one instance, and then that instance stays in memory for the entire duration of the program, and every time Red is called, this instance is used. The latter only creates something when first used, but creates a new instance every time. If this is correct, then I would argue that if I supply a lot of predefined colors, then the first would use a lot of unnecessary memory? So it is memory usage vs the runtime overhead of instantiating an object every time I guess. Is my reasoning correct? Any advice for best practices when designing classes and use of the static keyword would be great.
I'm guessing that you're probably already aware that the framework provides a `Color` struct. I'm guessing that you're creating a `Color` class just for practice. You expressed uncertainty about the meaning of the `static` keyword, although you've used it correctly. When `static` is applied to a member of a class or struct, it means that that member belongs to the class as a whole, and does not apply to individual instances. Static data members (fields) are created only once; instances do not get their own copies. Static functions (methods and properties) are called without an instance reference. As far as memory usage goes, I wouldn't worry too much about it in your case. Your `Color` class shouldn't use more than a few bytes per instance (for instance, the framework's `Color` structure stores red, green, blue, and alpha in one 32-bit `int`.). If your `Color` is a really a `class` instead of a `struct`, then you'll have a few more bytes in overhead (each instance will have an additional 32-bit v-table/typeinfo pointer, and each reference is an additional 32-bits), but even so, you're talking about 12 bytes or so per instance. If you have 100 different colors predefined, you'll use <= 1200 bytes. Really no big deal. There are reasons for lazy-instantiation, though. There are classes that *do* use a lot of memory, and ones that hold on to limited system resources, and ones that take a long time to construct themselves, etc. For these classes it's sometimes better to use a pattern like: ``` class Heavy{ static Heavy first; static Heavy second; public static Heavy First{ get{ if(first == null) first = new Heavy(); return first; } } public static Heavy Second{ get{ if(second == null) second = new Heavy(); return second; } } } ``` Another consideration is mutability. Is your `Color` class mutable or immutable? In other words, can instances of your class have their value changed, or do they always, once created, represent the same value? If your `Color` is mutable, then the only correct way to have a static "Red" accessor would be your second example, where you create a new one every access. That way someone can't do something like: ``` Color.Red.G = 255; ``` and make the single shared Color.Red instance actually represent yellow, instead. But also keep in mind that in a case like: ``` for(int y = 0; y < bmp.Height; y++) for(int x = 0; x < bmp.Width; x++) if(bmp.GetPixel(x, y) == Color.Red)) MessageBox.Show("Found a red pixel!"); ``` A **lot** of instances of your `Color` class are going to be created. They'll be garbage collected later, of course, but this is still a case argument for your first construct above (or the "Heavy" example I gave). Now if your `Color` is actually a struct, then it's a slightly difference story. There's no heap allocation when you `new` a struct, and there's no v-table or reference pointer, so the real consideration is then just how long your constructor takes.
Your reasoning and identification of the trade-off seems sound. If you look at the System.Drawing.Color structure, you'll see it uses the second technique. The overhead of initializing a new struct is trivial, so this is probably better than having a large number of known colors pre-created. I would expect Color to be an immutable struct. But if you're planning to create a class, you'd want to ensure it's immutable if you decide to use the first technique.
C#, correct use of the static keyword when designing a basic color class
[ "", "c#", "static", "" ]
In the standard PrintDialog there are four values associated with a selected printer: Status, Type, Where, and Comment. If I know a printer's name, how can I get these values in C# 2.0?
As [dowski suggested](https://stackoverflow.com/questions/296182/how-to-get-printer-info-in-cnet#296232), you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc. ``` using System.Management; ``` ... ``` string printerName = "YourPrinterName"; string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) using (ManagementObjectCollection coll = searcher.Get()) { try { foreach (ManagementObject printer in coll) { foreach (PropertyData property in printer.Properties) { Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value)); } } } catch (ManagementException ex) { Console.WriteLine(ex.Message); } } ```
This *should* work. ``` using System.Drawing.Printing; ``` ... ``` PrinterSettings ps = new PrinterSettings(); ps.PrinterName = "The printer name"; // Load the appropriate printer's setting ``` After that, the various [properties](http://msdn.microsoft.com/en-us/library/system.drawing.printing.printersettings_members(VS.80).aspx) of PrinterSettings can be read. Note that `ps.isValid()` can see if the printer actually exists. Edit: One additional comment. Microsoft recommends you use a [PrintDocument](http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument(VS.80).aspx) and modify its PrinterSettings rather than creating a PrinterSettings directly.
How to get Printer Info in .NET?
[ "", "c#", ".net", "printing", "printers", "printdialog", "" ]
Although I know how to build a DOM the long, arduous way using the DOM API, I'd like to do something a bit better than that. Is there a nice, tidy way to build hierarchical documents with, say, an API that works something like Hibernate's Criteria API? So that I can chain calls together like this, for example: ``` Document doc = createDocumentSomehow (); doc.createElement ("root").createElements ( doc.newElement ("subnode") .createElement ("sub-subnode") .setText("some element text") .addAttribute ("attr-name","attr-value"), doc.newElement ("other_subnode")); ``` Ideally, this would result in XML like this: ``` <root> <subnode> <sub-subnode attr-name = "attr-value">some element text</sub-subnode> <other_subnode /> </root> ``` Basically, I'd like something where the Java itself isn't nearly four times longer than the document I'm generating. Does it exist?
You definitely want to use `JDom`: <http://www.jdom.org/docs/apidocs/> . It can be used as you described as many methods return a reference to `this`. Here is some code our teacher showed us for this XML document. Haven't tested it, but the teacher is great i believe in him: ``` <adressbuch aktualisiert="1.4.2008"> <adresse> <vorname> Hugo </vorname> <nachname> Meier </nachname> <telefon typ="mobil">0160/987654 </telefon> </adresse> </adressbuch> ``` Code: ``` new Document( new Element ("adressbuch") .setAttribute("aktualisiert", "1.4.2008") .addContent( (Element) new Element("adresse") .addContent( (Element) new Element("vorname") .addContent("Hugo")) .addContent( (Element) new Element("nachname") .addContent("Meier")) .addContent( (Element) new Element("telefon") .setAttribute("typ", "mobil") .addContent("0160/987654")))); ``` From the API manual, it looks like the casts he did aren't necassary. Maybe he just did it for documentation purposes.
I highly recommend Elliotte Rusty Harold's [XOM](http://xom.nu/) API. It inter-operates with the W3C API, in that you can convert between XOM and DOM. The API guarantees a well-formed structure at all times. It's performant, robust, and follows consistent design principles.
What is an efficient way to create a W3C DOM programatically in Java?
[ "", "java", "xml", "dom", "" ]
I have below a list of text, it is from a popular online game called EVE Online and this basically gets mailed to you when you kill a person in-game. I'm building a tool to parse these using PHP to extract all relevant information. I will need all pieces of information shown and i'm writting classes to nicely break it into relevant encapsulated data. ``` 2008.06.19 20:53:00 Victim: Massi Corp: Cygnus Alpha Syndicate Alliance: NONE Faction: NONE Destroyed: Raven System: Jan Security: 0.4 Damage Taken: 48436 Involved parties: Name: Kale Kold Security: -10.0 Corp: Vicious Little Killers Alliance: NONE Faction: NONE Ship: Drake Weapon: Hobgoblin II Damage Done: 22093 Name: Harulth (laid the final blow) Security: -10.0 Corp: Vicious Little Killers Alliance: NONE Faction: NONE Ship: Drake Weapon: Caldari Navy Scourge Heavy Missile Damage Done: 16687 Name: Gistatis Tribuni / Angel Cartel Damage Done: 9656 Destroyed items: Capacitor Power Relay II, Qty: 2 Paradise Cruise Missile, Qty: 23 Cataclysm Cruise Missile, Qty: 12 Small Tractor Beam I Alloyed Tritanium Bar, Qty: 2 (Cargo) Paradise Cruise Missile, Qty: 1874 (Cargo) Contaminated Nanite Compound (Cargo) Capacitor Control Circuit I, Qty: 3 Ballistic Deflection Field I 'Malkuth' Cruise Launcher I, Qty: 3 Angel Electrum Tag, Qty: 2 (Cargo) Dropped items: Ballistic Control System I Shield Boost Amplifier I, Qty: 2 Charred Micro Circuit, Qty: 4 (Cargo) Capacitor Power Relay II, Qty: 2 Paradise Cruise Missile, Qty: 10 Cataclysm Cruise Missile, Qty: 21 X-Large Shield Booster II Cataclysm Cruise Missile, Qty: 3220 (Cargo) Fried Interface Circuit (Cargo) F-S15 Braced Deflection Shield Matrix, Qty: 2 Salvager I 'Arbalest' Cruise Launcher I 'Malkuth' Cruise Launcher I, Qty: 2 ``` I'm thinking about using regular expressions to parse the data but how would you approach this? Would you collapse the mail into a one line string or parse each line from an array? The trouble is there are a few anomalies to account for. First, the 'Involved parties:' section is dynamic and can contain lots of people all with the similar structure as below but if a computer controlled enemy takes a shot at the victim too, it gets shortened to only the 'Name' and 'Damage Done' fields, as shown above (Gistatis Tribuni / Angel Cartel). Second, the 'Destroyed' and 'Dropped' items are dynamic and will be different lengths on each mail and i will also need to get the quantity and wether or not they are in cargo. Ideas for an approach are welcome.
If you want something flexible, use the state machine approach. If you want something quick and dirty, use regexp. For the first solution, you can use libraries that are specialized in parsin since it's not a trivial task. But because it's fairly simple format, you can hack a naive parser, as for example : ``` <?php class Parser { /* Enclosing the parser in a class is not mandatory but it' clean */ function Parser() { /* data holder */ $this->date = ''; $this->parties = array(); $this->victim = array(); $this->items = array("Destroyed" => array(), "Dropped" => array()); /* Map you states on actions. Sub states can be necessary (and sub parsers too :-) */ $this->states = array('Victim' => 'victim_parsing', 'Involved' => 'parties_parsing' , 'items:' => "item_parsing"); $this->state = 'start'; $this->item_parsing_state = 'Destroyed'; $this->partie_parsing_state = ''; $this->parse_tools = array('start' => 'start_parsing', 'parties_parsing' =>'parties_parsing', 'item_parsing' => 'item_parsing', 'victim_parsing' => 'victim_parsing'); } /* the magic job is done here */ function checkLine($line) { foreach ($this->states as $keyword => $state) if (strpos($line, $keyword) !== False) $this->state = $this->states[$keyword]; return trim($line); } function parse($file) { $this->file = new SplFileObject($file); foreach ($this->file as $line) if ($line = $this->checkLine($line)) $this->{$this->parse_tools[$this->state]}($line); } /* then here you can define as much as parsing rules as you want */ function victim_parsing($line) { $victim_caract = explode(': ', $line); $this->victim[$victim_caract[0]] = $victim_caract[1]; } function start_parsing($line) { $this->date = $line; } function item_parsing($line) { if (strpos($line, 'items:') !== False) { $item_state = explode(' ', $line); $this->item_parsing_state = $item_state[0]; } else { $item_caract = explode(', Qty: ', $line); $this->items[$this->item_parsing_state][$item_caract[0]] = array(); $item_infos = explode(' ', $item_caract[1]); $this->items[$this->item_parsing_state][$item_caract[0]] ['qty'] = empty($item_infos[0]) ? 1 : $item_infos[0]; $this->items[$this->item_parsing_state][$item_caract[0]] ['cargo'] = !empty( $item_infos[1]) ? "True": "False"; if (empty( $this->items[$this->item_parsing_state][$item_caract[0]] ['qty'] )) print $line; } } function parties_parsing($line) { $partie_caract = explode(': ', $line); if ($partie_caract[0] == "Name") { $this->partie_parsing_state = $partie_caract[1]; $this->parties[ $this->partie_parsing_state ] = array(); } else $this->parties[ $this->partie_parsing_state ][$partie_caract[0]] = $partie_caract[1]; } } /* a little test */ $parser = new Parser(); $parser->parse('test.txt'); echo "======== Fight report - ".$parser->date." ==========\n\n"; echo "Victim :\n\n"; print_r($parser->victim); echo "Parties :\n\n"; print_r($parser->parties); echo "Items: \n\n"; print_r($parser->items); ?> ``` We can do that because here, reliability and perf are not an issue :-) Happy game !
I'd probably go with a state machine approach, reading each line in sequence and dealing with it depending on the current state. Some lines, like "Dropped items:" change the state, causing you to interpret following lines as items. While in the "reading involved parties" state you'd be adding each line to an array of data about the person, and when you read a blank line, you know you have a complete record. Here's a rough FSM I knocked up in GraphViz [![State machine](https://i.stack.imgur.com/lYm6R.png)](https://i.stack.imgur.com/lYm6R.png) Some edges will trigger actions in your code, like reading blank lines.
Best way to parse a dynamic text list in PHP
[ "", "php", "regex", "text", "parsing", "" ]
Using LINQ to Entities sounds like a great way to query against a database and get actual CLR objects that I can modify, data bind against and so forth. But if I perform the same query a second time do I get back references to the same CLR objects or an entirely new set? I do not want multiple queries to generate an ever growing number of copies of the same actual data. The problem here is that I could alter the contents of one entity and save it back to the database but another instance of the entity is still in existence elsewhere and holding the old data.
Within the same DataContext, my understanding is that you'll always get the same objects - for queries which return full objects instead of projections. Different DataContexts will fetch different objects, however - so there's a risk of seeing stale data there, yes.
In the same DataContext you would get the same object if it's queried (DataContext maintains internal cache for this). Be aware that that the objects you deal are most likely mutable, so instead of one problem (data duplication) you can get another (concurrent access). Depending on business case it may be ok to let the second transaction with stale data to fail on commit. Also, imagine a good old IDataReader/DataSet scenario. Two queries would return two different readers that would fill different datasets. So the data duplication problem isn't ORM specific.
Does LINQ to Entities reuse instances of objects?
[ "", "c#", "linq", "entities", "" ]
How can I compile/run C or C++ code in a Unix console or a Mac terminal?
If it is a simple single-source program, ``` make foo ``` where the source file is *foo.c*, *foo.cpp*, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension. Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in `$PATH` to find executables, and most often that does not include the current directory (`.`). So to run the built executable `foo`: ``` ./foo ```
``` gcc main.cpp -o main.out ./main.out ```
How can I compile and run C/C++ code in a Unix console or Mac terminal?
[ "", "c++", "c", "macos", "console", "terminal", "" ]
i connecting to a access database with php and adodb. Strings with characters like ® are saved in the database as ® . What can i do to store it correctly?
Looks like you're passing in a UTF8 string but you're not storing it as UTF8. Change it one way or the other so they match up (preferably change your database to UTF8).
@RoBOrg: Yes, but i didn't find a way to store it as utf8. The connection string is allready with charset=utf8 "DRIVER=Microsoft Access Driver (\*.mdb);DBQ=something.mdb;UID=Administrator;Charset=utf8" and i didn't find any possibility in adodb to change the storing charset for access databases. I'm updating with command text. (I sent this as comment before, sorry.)
adodb and access changing ® to ®
[ "", "php", "ms-access", "adodb", "" ]
I need to validate a certain property to one of my classes. When I set the property, the class should validate the input and if incorrect, set the object to an invalid state. Question : The property value must be in a certain mask/format eg. &&&&-&&&&-&&&&. I cannot use regular expressions. Is it possible to validate text against a mask value?
Regular expressions are often over-used, but this is a pretty good example of when a regex is ideal... so: why can't you use them here?
> Is it possible to validate text > against a mask value ? Of course it's possible, in that you could write a function to take a string and a mask and check one against another. So I'm unclear on what you're asking - are you asking if there are functions in the standard .Net libraries to do this? Or asking for an implementation of a mask-validation function? Or something else? If you're looking for something in the library to help, [MaskedTextProvider](http://msdn.microsoft.com/en-us/library/system.componentmodel.maskedtextprovider.aspx) would probably do it, although it's overkill.
Validate text against mask value in C#
[ "", "c#", "masking", "" ]
Beyond the official documentation, are there any recommended resources for learning to build jQuery plugins. I'm particularly interested in building plugins for the UI libary. I've been looking at the source for some of the official ones, but I've found they all look quite different from each other. Many are not well commented and it is difficult to tell what blocks of code are part of the essential structure and what is specific to a particular plugin. If there aren't yet any good resources for this, can anyone clue me in on what basic structure I should be starting with when writing a plugin from scratch?
## Tutorial at "Learning jQuery" [Learning jQuery](http://www.learningjquery.com) is a very helpful site, and has a [great tutorial on plugin authoring](http://www.learningjquery.com/2007/10/a-plugin-development-pattern). One principle I really liked was: **create default settings that users can override**. So maybe you can say $(this).highlight() and it will highlight blue by default. Or you can say $(this).highlight("green") and it will highlight green. But you should also make it possible to say: ``` $(this).highlight({ foreground: 'red' }); ``` ...and it will highlight red **from then on** by default. ## Other good resources * [Fuel Your Coding article](http://fuelyourcoding.com/jquery-plugin-design-patterns-part-i/) * [Starter](http://starter.pixelgraphics.us/) - tool for jumpstarting a plugin
Have you tried the Manning Publications book on jQuery, [jQuery In Action](http://www.manning.com/bibeault/)? The [table of contents](http://www.manning.com/bibeault/excerpt_contents.html) indicates there is good material on writing your own plugins.
Building jQuery UI Plugins
[ "", "javascript", "jquery", "jquery-plugins", "jquery-ui-plugins", "" ]
I'm building a with-source system which I am giving out on the 'net for providing adoptable virtual pets. The system will be owned mainly by kids. Since I want it to be usable for absolute beginner programmers, there are several complexity constraints on my system: It can't use libraries that don't commonly ship with PHP, and it can't touch a database or write to other permanent storage. When each pet is adopted, the visitor will randomly get given one of a series of slightly different variations of that pet. The variations initially look the same, but grow up over time to become different pets. The visitor will be given a short code in HTML which links to the image of their pet. Since there is no permanent storage available server-side, the user's image link must contain all of the information to determine which pet variation they ended up getting. At the moment, the URL just contains the ID of the pet and the ID of the variation that the user got. The problem with this is that, by comparing codes with each other, the users can figure out who amongst them ended up with the same variation. Since some variations are rarer than others, users can spot the rare variations easily before the difference is even visually apparent. What I would like is an encryption system for the details in the URL. Something that obscures the variation ID so that each user gets a different URL with high probability. I thought of using the variation ID (3 or 4 bits) as the low bits or high bits of a large random number, but the users will spot the pattern in this. Ideally the encryption system would be parametrized so that each installation of my system would use a slightly different encryption. PHP's mcrypt library would probably have something useful in it, but it doesn't seem to be very common amongst hosters. Is there a simple, parametrized, obfuscation/encryption I can use here?
If you are expecting a relatively low sophistication level, then you can do a very simple "xor" encryption and "store" the key as part of the URL. Then you can just use php's rand() or /dev/random or whatever to generate keys. Low-sophistication users won't readily figure out that all they need to do is xor the lower half of their pet ID with the upper half to get a value which can be compared to their friends. I would guess most people who would be able to recognize that was what was going on wouldn't take the time to figure it out, and those people are outside of your target audience anyways. Edit: If it wasn't obvious, I'm saying you give a different key to every pet (since giving the same one would not solve your problem). So if the pet variation (petvar) is a 16 bit number, you generate a 16-bit random number (rnd), then you do this: `petvar = (petvar^rnd)<<16 | rnd;` and then you can reverse that operation to extract the rnd and then petvar^rnd, and then just xor it again to get the original petvar.
You are looking for "one time padding" encryption. It takes a key and does modulus addition to characters to create the encrypted string. ``` function ecrypt($str){ $key = "abc123 as long as you want bla bla bla"; for($i=0; $i<strlen($str); $i++) { $char = substr($str, $i, 1); $keychar = substr($key, ($i % strlen($key))-1, 1); $char = chr(ord($char)+ord($keychar)); $result.=$char; } return urlencode(base64_encode($result)); } function decrypt($str){ $str = base64_decode(urldecode($str)); $result = ''; $key = "must be same key as in encrypt"; for($i=0; $i<strlen($str); $i++) { $char = substr($str, $i, 1); $keychar = substr($key, ($i % strlen($key))-1, 1); $char = chr(ord($char)-ord($keychar)); $result.=$char; } return $result; } ``` So that's simple string encryption. What I would do is serialize the array of the user's parameters and pass it as a variable in the link: ``` $arr = array( 'pet_name'=>"fido", 'favorite_food'=>"cat poop", 'unique_id'=>3848908043 ); $param_string = encrypt(serialize($arr)); $link = "/load_pet.php?params=$param_string"; ``` In load\_pet.php you should do the opposite: ``` $param_string = $_GET["params"]; $params = unserialize(decrypt($param_string)); ``` Bam.
Simple encryption in PHP
[ "", "php", "encryption", "" ]
This question deals with concurrency issues, for suggestions on how to display a busy icon see this question: [Javascript - loading/busy indicator or transparent div over page on event click](https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click) When a user initiates an AJAX request on a page it's useful to show some kind of "working" or busy icon or progress indicator. If there is only one long-running process this can be handled in a relatively straightforward way: ``` function do_action() { show_busy_icon(); long_running_asynchronous_process(function() { // Callback function run when process finishes hide_busy_icon(); }); } ``` However, if multiple asynchronous processes are running on the page, using on/off methods wouldn't work. The first process to finish switches off the icon even though there are additional processes running. So, **how do you handle displaying an indicator, on a web page, that is on when there are one or more processes running, and off when there are no processes running?** I imagine it would be possible to maintain a count of the number of processes running. `hide_busy_icon()` only hides the icon if the process count is 0. That seems kinda prone to failure. Perhaps there's a better/simpler way that I'm not seeing. Thanks for your ideas and suggestions! Edit: After working with the solution in the marked answer for a while, I'm happy to say it works very well. The only issue I've run into are cases where my own scripts call functions of scripts I don't control. Unless those functions allow callbacks to be supplied there's no way to update the process-count when they begin and end. An example of where this can occurs is adding a set of markers to a Google map. Once my script calls the Google maps function the busy icon disappears, while the markers are still being loaded. I'm not sure of a good way to handle this.
If you want the same busy indicator for all actions, then use a counter. Instead of "show\_busy\_icon()", do a "increment\_busy\_count()", which calls "show\_busy\_icon()" if busy count goes from 0 to 1. Instead of "hide\_busy\_icon()", do a "decrement\_busy\_count()", which calls "hide\_busy\_icon()" if busy count goes from 1 to 0.
I think the problem is really that you are using only one indicator. It may be easier to have an indicator for each action that needs one. So, if you have multiple searches on a page each search area would have it's own independent indicator that is shown or hidden in the appropriate javascript functions.
How do you handle busy icons in an AJAX site?
[ "", "javascript", "jquery", "ajax", "concurrency", "callback", "" ]
I do remember seeing someone ask something along these lines a while ago but I did a search and couldn't find anything. I'm trying to come up with the cleanest way to clear all the controls on a form back to their defaults (e.g., clear textboxes, uncheck checkboxes). How would you go about this?
What I have come up with so far is something like this: ``` public static class extenstions { private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { {typeof(TextBox), c => ((TextBox)c).Clear()}, {typeof(CheckBox), c => ((CheckBox)c).Checked = false}, {typeof(ListBox), c => ((ListBox)c).Items.Clear()}, {typeof(RadioButton), c => ((RadioButton)c).Checked = false}, {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()}, {typeof(Panel), c => ((Panel)c).Controls.ClearControls()} }; private static void FindAndInvoke(Type type, Control control) { if (controldefaults.ContainsKey(type)) { controldefaults[type].Invoke(control); } } public static void ClearControls(this Control.ControlCollection controls) { foreach (Control control in controls) { FindAndInvoke(control.GetType(), control); } } public static void ClearControls<T>(this Control.ControlCollection controls) where T : class { if (!controldefaults.ContainsKey(typeof(T))) return; foreach (Control control in controls) { if (control.GetType().Equals(typeof(T))) { FindAndInvoke(typeof(T), control); } } } } ``` Now you can just call the extension method ClearControls like this: ``` private void button1_Click(object sender, EventArgs e) { this.Controls.ClearControls(); } ``` EDIT: I have just added a generic ClearControls method that will clear all the controls of that type, which can be called like this: ``` this.Controls.ClearControls<TextBox>(); ``` At the moment it will only handle top level controls and won't dig down through groupboxes and panels.
I know its an old question but just my 2 cents in. This is a helper class I use for form clearing. ``` using System; using System.Windows.Forms; namespace FormClearing { class Helper { public static void ClearFormControls(Form form) { foreach (Control control in form.Controls) { if (control is TextBox) { TextBox txtbox = (TextBox)control; txtbox.Text = string.Empty; } else if(control is CheckBox) { CheckBox chkbox = (CheckBox)control; chkbox.Checked = false; } else if (control is RadioButton) { RadioButton rdbtn = (RadioButton)control; rdbtn.Checked = false; } else if (control is DateTimePicker) { DateTimePicker dtp = (DateTimePicker)control; dtp.Value = DateTime.Now; } } } } } ``` And I call the method from any form like this passing a form object as a parameter. ``` Helper.ClearFormControls(this); ``` You can extend it for other types of controls. You just have to cast it.
What is the best way to clear all controls on a form C#?
[ "", "c#", "controls", "" ]
I'm wondering why the `assert` keyword is so underused in Java? I've almost never seen them used, but I think they're a great idea. I certainly much prefer the brevity of: ``` assert param != null : "Param cannot be null"; ``` to the verbosity of: ``` if (param == null) { throw new IllegalArgumentException("Param cannot be null"); } ``` My suspicion is that they're underused because * They arrived relatively late (Java 1.4), by which time many people had already established their Java programming style/habit * They are turned off at runtime by default
*assertions* are, in theory, for testing [invariants](http://en.wikipedia.org/wiki/Invariant_(computer_science)), assumptions that **must** be true in order for the code to complete properly. The example shown is testing for valid input, which isn't a typical usage for an assertion because it is, generally, user supplied. Assertions aren't generally used in production code because there is an overhead and it is assumed that situations where the invariants fail have been caught as coding errors during development and testing. Your point about them coming "late" to java is also a reason why they aren't more widely seen. Also, unit testing frameworks allow for some of the need for programmatic assertions to be external to the code being tested.
It's an abuse of assertions to use them to test user input. Throwing an `IllegalArgumentException` on invalid input is more correct, as it allows the calling method to catch the exception, display the error, and do whatever it needs to (ask for input again, quit, whatever). If that method is a private method inside one of your classes, the assertion is fine, because you are just trying to make sure you aren't accidentally passing it a null argument. You test with assertions on, and when you have tested all the paths through and not triggered the assertion, you can turn them off so that you aren't wasting resources on them. They are also useful just as comments. An `assert` at the start of a method is good documentation to maintainers that they should be following certain preconditions, and an `assert` at the end with a postcondition documents what the method should be doing. They can be just as useful as comments; moreso, because with assertions on, they actually TEST what they document. Assertions are for testing/debugging, not error-checking, which is why they are off by default: to discourage people from using assertions to validate user input.
Java assertions underused
[ "", "java", "assertion", "" ]
On several of my usercontrols, I change the cursor by using ``` this.Cursor = Cursors.Wait; ``` when I click on something. Now I want to do the same thing on a WPF page on a button click. When I hover over my button, the cursor changes to a hand, but when I click it, it doesn't change to the wait cursor. I wonder if this has something to do with the fact that it's a button, or because this is a page and not a usercontrol? This seems like weird behavior.
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using [Mouse.OverrideCursor](http://msdn.microsoft.com/en-us/library/system.windows.input.mouse.overridecursor.aspx): ``` Mouse.OverrideCursor = Cursors.Wait; try { // do stuff } finally { Mouse.OverrideCursor = null; } ``` This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
One way we do this in our application is using IDisposable and then with `using(){}` blocks to ensure the cursor is reset when done. ``` public class OverrideCursor : IDisposable { public OverrideCursor(Cursor changeToCursor) { Mouse.OverrideCursor = changeToCursor; } #region IDisposable Members public void Dispose() { Mouse.OverrideCursor = null; } #endregion } ``` and then in your code: ``` using (OverrideCursor cursor = new OverrideCursor(Cursors.Wait)) { // Do work... } ``` The override will end when either: the end of the using statement is reached or; if an exception is thrown and control leaves the statement block before the end of the statement. **Update** To prevent the cursor flickering you can do: ``` public class OverrideCursor : IDisposable { static Stack<Cursor> s_Stack = new Stack<Cursor>(); public OverrideCursor(Cursor changeToCursor) { s_Stack.Push(changeToCursor); if (Mouse.OverrideCursor != changeToCursor) Mouse.OverrideCursor = changeToCursor; } public void Dispose() { s_Stack.Pop(); Cursor cursor = s_Stack.Count > 0 ? s_Stack.Peek() : null; if (cursor != Mouse.OverrideCursor) Mouse.OverrideCursor = cursor; } } ```
Changing the cursor in WPF sometimes works, sometimes doesn't
[ "", "c#", "wpf", "" ]
Has anybody used or seen a website that uses [FlapJax](http://www.flapjax-lang.org/) to function, rather than just as a demo? I'm curious to see how they operate / how difficult they were to write. List one example per answer.
I'm going to ignore the one app per answer request: <http://continue2.cs.brown.edu/> <http://resumedemo.cs.brown.edu/> Keep in mind though that these were made by the developers of Flapjax.
I've been using it for a page internal to my employer that is largely a very fancy clock. Just using the library directly (skipping the compiler, which they plan to deprecate) has worked great. Event streams are very convenient when you've got a whole lot of different components, coming and going, that have to be synchronized. So, sorry, can't show you anything, but I've been very pleased with it.
Practical FlapJax
[ "", "javascript", "" ]
Is it possible to create an integer (or DataTime, etc) column in ListView? It is quite important, because I would like to properly sort the list according to this column. The only way to add subItems to a ListViewItem I found are: ``` listviewitem.SubItems.Add("1"); ``` I would like to avoid parsing these strings to get the int representation for every sort!
You could use the Tag property. These little helper functions take care of it: ``` private void setListItem(int row, int column, int value) { ListViewItem.ListViewSubItem item = listView1.Items[row].SubItems[column]; item.Tag = value; item.Text = value.ToString(); } private int getListItem(int row, int column) { return (int)listView1.Items[row].SubItems[column].Tag; } ```
Rather than that you just add strings to the list and receive strings by using `.Text` property. Example: ``` int a = 0; listView1.Items.Add(a.ToString()); ``` or ``` int a = Convert.ToInt32(listView1.Items[0].SubItems[0].Text); ``` You can do this same with `DataTime` and other datatypes, just by converting them to `String` type. How you interpret the column containing i.e dates it fully depends of you. Just implement your algorithm of sorting particular `ListView` column.
Create an int column in ListView (Winforms)
[ "", "c#", ".net", "winforms", "" ]
I have this function in my head: ``` <head> window.onload = function(){ var x = new Array(0,2,3,4,5,6,7,8); var y = new Array(20,10,40,30,60,50,70,10); drawGraph(y,x); } </head> ``` Can I declare the function drawGraph() somewhere in the body? Do I need to declare it before it is called?
The order does matter. You'll need to have the drawGraph() function declared before it's called.
Keep in mind that many web platforms already use the window.onload method, and owing to the fact that window.onload can be called only once, you could have a script collision. You might consider using a different method for loading your script that builds the window.onload or waits for the page load to complete. An example without using a JavaScript framework like JQuery would look like: ``` function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); var x = new Array(0,2,3,4,5,6,7,8); var y = new Array(20,10,40,30,60,50,70,10); drawGraph(y,x); } } } ``` An example using JQuery would look like: ``` $(document).ready(function() { var x = new Array(0,2,3,4,5,6,7,8); var y = new Array(20,10,40,30,60,50,70,10); drawGraph(y,x); }) ```
Beginner: Javascript must be on header to run? Does the declaration order of the functions matter?
[ "", "javascript", "" ]
Is there an similar property like System.getProperty("java.home") that will return the JDK directory instead of the JRE directory? I've looked <https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()> and there doesn't seem to be anything for the JDK.
One route would be to set a system environment variable like "JAVA\_HOME" and use that. It may not be the best solution, but it would work, and this is what other apps which require JDK rather than JRE (like CruiseControl) require you to do when you set them up.
There's not a property similar to `java.home` for the JDK. There are some rules of thumb that help detect whether the JRE you're running in is part of a JDK. For example, look for "${java.home}/../lib/tools.jar". In other words, in some cases, you might be able to suggest a default, but in general, the user should tell you which JDK to use.
How can I get the location of the JDK directory in Java?
[ "", "properties", "java", "" ]
This is for .NET. IgnoreCase is set and MultiLine is NOT set. Usually I'm decent at regex, maybe I'm running low on caffeine... Users are allowed to enter HTML-encoded entities (<lt;, <amp;, etc.), and to use the following HTML tags: ``` u, i, b, h3, h4, br, a, img ``` Self-closing <br/> and <img/> are allowed, with or without the extra space, but are not required. I want to: 1. Strip all starting and ending HTML tags other than those listed above. 2. Remove attributes from the remaining tags, *except* anchors can have an href. My search pattern (replaced with an empty string) so far: ``` <(?!i|b|h3|h4|a|img|/i|/b|/h3|/h4|/a|/img)[^>]+> ``` This *seems* to be stripping all but the start and end tags I want, but there are three problems: 1. Having to include the end tag version of each allowed tag is ugly. 2. The attributes survive. Can this happen in a single replacement? 3. Tags *starting with* the allowed tag names slip through. E.g., "<abbrev>" and "<iframe>". The following suggested pattern does not strip out tags that have no attributes. ``` </?(?!i|b|h3|h4|a|img)\b[^>]*> ``` As mentioned below, ">" is legal in an attribute value, but it's safe to say I won't support that. Also, there will be no CDATA blocks, etc. to worry about. Just a little HTML. Loophole's answer is the best one so far, thanks! Here's his pattern (hoping the PRE works better for me): ``` static string SanitizeHtml(string html) { string acceptable = "script|link|title"; string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>"; return Regex.Replace(html, stringPattern, "sausage"); } ``` Some small tweaks I think could still be made to this answer: 1. I think this could be modified to capture simple HTML comments (those that do not themselves contain tags) by adding "!--" to the "acceptable" variable and making a small change to the end of the expression to allow for an optional trailing "\s--". 2. I think this would break if there are multiple whitespace characters between attributes (example: heavily-formatted HTML with line breaks and tabs between attributes). **Edit 2009-07-23:** Here's the final solution I went with (in VB.NET): ``` Dim AcceptableTags As String = "i|b|u|sup|sub|ol|ul|li|br|h2|h3|h4|h5|span|div|p|a|img|blockquote" Dim WhiteListPattern As String = "</?(?(?=" & AcceptableTags & _ ")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>" html = Regex.Replace(html, WhiteListPattern, "", RegExOptions.Compiled) ``` The caveat is that the HREF attribute of A tags still gets scrubbed, which is not ideal.
Here's a function I wrote for this task: ``` static string SanitizeHtml(string html) { string acceptable = "script|link|title"; string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*?\1?)?)*\s*/?>"; return Regex.Replace(html, stringPattern, "sausage"); } ``` Edit: For some reason I posted a correction to my previous answer as a separate answer, so I am consolidating them here. I will explain the regex a bit, because it is a little long. The first part matches an open bracket and 0 or 1 slashes (in case it's a close tag). Next you see an if-then construct with a look ahead. (?(?=SomeTag)then|else) I am checking to see if the next part of the string is one of the acceptable tags. You can see that I concatenate the regex string with the acceptable variable, which is the acceptable tag names seperated by a verticle bar so that any of the terms will match. If it is a match, you can see I put in the word "notag" because no tag would match that and if it is acceptable I want to leave it alone. Otherwise I move on to the else part, where i match any tag name [a-z,A-Z,0-9]+ Next, I want to match 0 or more attributes, which I assume are in the form attribute="value". so now I group this part representing an attribute but I use the ?: to prevent this group from being captured for speed: (?:\s[a-z,A-Z,0-9,-]+=?(?:(["",']?).*?\1?))* Here I begin with the whitespace character that would be between the tag and attribute names, then match an attribute name: [a-z,A-Z,0-9,-]+ next I match an equals sign, and then either quote. I group the quote so it will be captured, and I can do a backreference later \1 to match the same type of quote. In between these two quotes, you can see I use the period to match anything, however I use the lazy version \*? instead of the greedy version \* so that it will only match up to the next quote that would end this value. next we put a \* after closing the groups with parenthesis so that it will match multiple attirbute/value combinations (or none). Last we match some whitespace with \s, and 0 or 1 ending slashes in the tag for xml style self closing tags. You can see I'm replacing the tags with sausage, because I'm hungry, but you could replace them with empty string too to just clear them out.
This is a good working example on html tag filtering: [Sanitize HTML](http://web.archive.org/web/20100901160940/http://refactormycode.com/codes/333-sanitize-html)
How do I filter all HTML tags except a certain whitelist?
[ "", "c#", "html", "vb.net", "regex", "" ]
I'm trying to read data from a.csv file to ouput it on a webpage as text. It's the first time I'm doing this and I've run into a nasty little problem. My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string. like this: ``` $contents = file_get_contents("files/data.csv"); ``` In this example file I made, there are 2 lines. > Paul Blueberryroad > 85 us Flashlight,Bag November 20, > 2008, 4:39 pm > > Hellen Blueberryroad > 85 us lens13mm,Flashlight,Bag,ExtraBatteries November > 20, 2008, 16:41:32 But the string read by PHP is this: Paul;Blueberryroad 85;us;Flashlight,Bag;November 20, 2008, 4:39 pmHellen;Blueberryroad 85;us;lens13mm,Flashlight,Bag,ExtraBatteries;November 20, 2008, 16:41:32 I'm splitting this with: ``` list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents); ``` What I want is for $name[] to contain "Paul" and "Hellen" as its contents. And the other arrays to receive the values of their respective columns. Instead I get only Paul and the content of $orderdate[] is > November 20, 2008, 4:39 pmHellen So all the rows are concatenated. Can someone show me how i can achieve what I need? EDIT: solution found, just one werid thing remaining: I've solved it now by using this piece of code: ``` $fo = fopen("files/users.csv", "rb+"); while(!feof($fo)) { $contents[] = fgetcsv($fo,0,';'); } fclose($fo); ``` For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.
You are better off using [fgetcsv()](http://www.php.net/fgetcsv) which is aware of CSV file structure and has designated options for handling CSV files. Alternatively, you can use [str\_getcsv()](http://www.php.net/manual/en/function.str-getcsv.php) on the contents of the file instead.
The [file()](http://it.php.net/file) function reads a file in an array, every line is an entry of the array. So you can do something like: ``` $rows = array(); $name = array(); $street = array(); $country = array(); $rows = file("file.csv"); foreach($rows as $r) { $data = explode(";", $r); $name[] = $data[0]; $street[] = $data[1]; $country[] = $data[2]; } ```
problem with PHP reading CSV files
[ "", "php", "file-io", "csv", "" ]
I would like to be able to detect what country a visitor is from on my website, using PHP. Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words *(Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks)*, and perhaps to give a default option in a "Select your country" list. As such, using a Geolocation database is a tad over-the-top and I really don't want to muck about with installing new PHP libraries just for this, so **what's the easiest/simplest way to find what country a visitor is from?**
Not guaranteed, but most browsers submit an Accept-Language HTTP header that specifies en-us if they're from the US. Some older browsers only said they are en, though. And not all machines are set up correctly to indicate which locale they prefer. But it's a good first guess. English-UK based-users usually set their system or user locale to English-UK, which in default browser configurations should result in en-gb as the Accept Language header. (An earlier version of this said en-uk; that was a typo, sorry.) Other countries also have en locales, such as en-za (south africa), and, primarily theoretically, combinations like en-jp are also possible. Geo-IP based guesses will less likely be correct on the preferred language/locale, however. Google thinks that content-negotiation based on IP address geolocation makes sense, which really annoys me when I'm in Japan or Korea...
PHP provides a function since 5.3.0 to parse the `$_SERVER['HTTP_ACCEPT_LANGUAGE']` variable into a locale. ``` $locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); echo $locale; // returns "en_US" ``` Documentation: <https://www.php.net/manual/en/locale.acceptfromhttp.php>
Simplest way to detect client locale in PHP
[ "", "php", "locale", "" ]
**In brief:** Is it ever excusable to have assembly names and class names stored in the database? Does it break the layers of an application for the data layer to have explicit knowledge of the internals of the business layer? **Full explanation:** I have a boot strapper that runs "jobs" (classes that inherit from a common base) that exist in separate assemblies. The jobs have configuration parameters stored in the database to allow their operation to be altered by means of a GUI. In order to locate and run a job, the boot strapper has an app.config file that contains the name of the job, and the assembly name and class name that defines it. I have been asked to move the assembly name and class name into the database so that we can get rid of the app.config file. (Reason given is to keep all configuration in the one place - the database.) However, the boot strapper is the only code that will run the job and this "configuration" information will never be changed after deployment. I think that putting such information into the database gives the data layer too much information about the layers above, and will get in the way of refactoring and maintenance. However, I know that Windows Workflow Foundation does exactly this, and so perhaps I am wrong to think it is a poor practice? **Edit:** In answer to a question below, the database connection string is stored in a separate config file that is managed by a shared configuration framework. This framework makes it technically possible to remove the app.config file completely.
I think it's perfectly acceptable to store configuration info including assembly/class names in the database. I wouldn't consider data stored in the database to be part of the data layer.
To sidestep this a little bit, with an example which justifies your implementation: When you use an IoC container like Windsor or Unity, you store your assembly/class names in your config file. Again, this is not compiler checked, as you can change this without having to recompile your code. It's similar to storing your mappings in a database, the only thing that changes is the source of your config. Best thing you can do (and I gather from your question that you do) is to program against abstract base classes or interfaces, so you don't have to rely on reflection to get information about the class you have to run. That way you can essentially create all your logic, and inject your dependency at runtime when you have to by reading your config from the database.
How bad is it to store class and assembly names in the database?
[ "", "c#", ".net", "database", "" ]
I'm working on some Flex spike in my company. We are basically evaluating different scenarios etc. What solution would you recommend for embedding Flex components into Java app? Flex <-> Java communication is not (yet...) an issue, just embedding swf into JFrame.
I've done it with EasyJCom. It's pretty straight forward as long as you're using one of the standard Java windowing libraries (Swing, awt). You can see an example (From the EZJCom site) here: <http://www.ezjcom.com/FlashTest.java.txt> The people responsible for EasyJCom are also very responsive, and even though we ended up not using their product (Switching platforms), I'd recommend them. I haven't used JFlashPlayer, but did take a look at the docs, it seems to be adequate as well. I think their license requires you to obfuscate your code. I thought it was a little odd, but maybe I mis-understood the license. It gets quite a bit more complicated if you don't want to use Com, or if you need to embed in another type of window. If you need to embed flash cross platform, you may be stuck rolling your own Jini library for the Mozilla plugin. At that point... Maybe it's worth just switching platforms if you aren't too far in. ;)
Haven't tested this, but it looks like JFlashPlayer will do the job. <http://www.jpackages.com/jflashplayer/>
Embedding Flash / Flex component into Java app
[ "", "java", "apache-flex", "flash", "" ]
How can I get a PHP function go to a specific website when it is done running? For example: ``` <?php //SOMETHING DONE GOTO(http://example.com/thankyou.php); ?> ``` I would really like the following... ``` <?php //SOMETHING DONE GOTO($url); ?> ``` I want to do something like this: ``` <?php //SOMETHING DONE THAT SETS $url header('Location: $url'); ?> ```
``` <? ob_start(); // ensures anything dumped out will be caught // do stuff here $url = 'http://example.com/thankyou.php'; // this can be set based on whatever // clear out the output buffer while (ob_get_status()) { ob_end_clean(); } // no redirect header( "Location: $url" ); ?> ```
You could always just use the tag to refresh the page - or maybe just drop the necessary javascript into the page at the end that would cause the page to redirect. You could even throw that in an onload function, so once its finished, the page is redirected ``` <?php echo $htmlHeader; while($stuff){ echo $stuff; } echo "<script>window.location = 'http://www.yourdomain.com'</script>"; ?> ```
Redirect to specified URL on PHP script completion?
[ "", "php", "url", "" ]
I am not sure what `optparse`'s `metavar` parameter is used for. I see it is used all around, but I can't see its use. Can someone make it clear to me? Thanks.
As @Guillaume says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the `metavar` parameter to the `add_option` call so your preferred argument name/descriptor is output in the help message. From [the current module documentation](http://docs.python.org/library/optparse.html#generating-help): ``` usage = "usage: %prog [options] arg1 arg2" parser = OptionParser(usage=usage) parser.add_option("-f", "--filename", metavar="FILE", help="write output to FILE"), ``` would produce help like this: ``` usage: <yourscript> [options] arg1 arg2 options: -f FILE, --filename=FILE ``` The "FILE" after the "-f" and the "--filename" comes from the metavar.
metavar seems to be used for generating help : <http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html>
Python optparse metavar
[ "", "python", "optparse", "" ]
The database type is PostGres 8.3. If I wrote: ``` SELECT field1, field2, field3, count(*) FROM table1 GROUP BY field1, field2, field3 having count(*) > 1; ``` I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to delete them all.) Example: ``` 1-2-3 1-2-3 1-2-3 2-3-4 4-5-6 ``` Should become : ``` 1-2-3 2-3-4 4-5-6 ``` *The only answer I found is [there](http://www.siafoo.net/article/64) but I am wondering if I could do it without hash column.* **Warning** I do not have a PK with an unique number so I can't use the technique of min(...). The PK is the 3 fields.
This is one of many reasons that all tables should have a primary key (not necessarily an ID number or IDENTITY, but a combination of one or more columns that uniquely identifies a row and which has its uniqueness enforced in the database). Your best bet is something like this: ``` SELECT field1, field2, field3, count(*) INTO temp_table1 FROM table1 GROUP BY field1, field2, field3 having count(*) > 1 DELETE T1 FROM table1 T1 INNER JOIN (SELECT field1, field2, field3 FROM table1 GROUP BY field1, field2, field3 having count(*) > 1) SQ ON SQ.field1 = T1.field1 AND SQ.field2 = T1.field2 AND SQ.field3 = T1.field3 INSERT INTO table1 (field1, field2, field3) SELECT field1, field2, field3 FROM temp_table1 DROP TABLE temp_table1 ```
One possible answer is: ``` CREATE <temporary table> (<correct structure for table being cleaned>); BEGIN WORK; -- if needed INSERT INTO <temporary table> SELECT DISTINCT * FROM <source table>; DELETE FROM <source table> INSERT INTO <source table> SELECT * FROM <temporary table>; COMMIT WORK; -- needed DROP <temporary table>; ``` I'm not sure whether the 'work' is needed on transaction statements, nor whether the explicit BEGIN is necessary in PostgreSQL. But the concept applies to any DBMS. The only thing to beware of is referential constraints and in particular triggered delete operations. If those exist, this may prove less satisfactory.
Remove duplicate from a table
[ "", "sql", "postgresql", "" ]
consider this code block ``` public void ManageInstalledComponentsUpdate() { IUpdateView view = new UpdaterForm(); BackgroundWorker worker = new BackgroundWorker(); Update update = new Update(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += new DoWorkEventHandler(update.DoUpdate); worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback); worker.RunWorkerAsync(); Application.Run(view as UpdaterForm); } ``` It all works great but I want to understand why the objects (worker,view and update) don't get garbage collected
Threads count as root objects; I don't know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited. Of course; collection also requires that all other (live) objects have de-referenced the worker object; note also that collection of stack variables can be different in debug/release, and with/without a debugger attached. [edit] As has also been noted; the event handlers on the worker (in your code) will keep the "view" and "update" objects alive (via the delegate), but not the other way around. As long as the worker has a shorter life than the "view" and "update", you don't need to get paranoid about unsubscribing the events. I've edited the code to include a "SomeTarget" object that isonly referenced by the worker: you should see this effect (i.e. the target dies with the worker). Re worker getting collected when the thread dies: here's the proof; you should see "worker finalized" after the worker reports exit: ``` using System; using System.ComponentModel; using System.Threading; using System.Windows.Forms; class Demo : Form { class ChattyWorker : BackgroundWorker { ~ChattyWorker() { Console.WriteLine("Worker finalized"); } } class SomeTarget { ~SomeTarget() { Console.WriteLine("Target finalized"); } public SomeTarget() { Console.WriteLine("Target created"); } public void Foo(object sender, EventArgs args) { Console.WriteLine("Foo"); } } static void Collect(object sender, EventArgs args) { Console.WriteLine("Collecting..."); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Interval = 100; timer.Tick += Collect; timer.Start(); ChattyWorker worker = new ChattyWorker(); worker.RunWorkerCompleted += new SomeTarget().Foo; worker.DoWork += delegate { Console.WriteLine("Worker starting"); for (int i = 0; i < 10; i++) { Thread.Sleep(250); Console.WriteLine(i); } Console.WriteLine("Worker exiting"); }; worker.RunWorkerAsync(); } [STAThread] static void Main() { // using a form to force a sync context Application.Run(new Demo()); } } ```
Event handlers are references, so until you have event handler attached to the worker, it would not be considered "unreachable". In your ComplitionCallback take care to unhook the event handlers.
When will my BackgroundWorker instance be garbage collected
[ "", "c#", ".net", "events", "garbage-collection", "backgroundworker", "" ]
What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements?
The `readonly` keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the `const` modifier, which must have its value set at compile time. Using `readonly` you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of. Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).
I don't believe there are any performance gains from using a readonly field. It's simply a check to ensure that once the object is fully constructed, that field cannot be pointed to a new value. However "readonly" is very different from other types of read-only semantics because it's enforced at runtime by the CLR. The readonly keyword compiles down to .initonly which is verifiable by the CLR. The real advantage of this keyword is to generate immutable data structures. Immutable data structures by definition cannot be changed once constructed. This makes it very easy to reason about the behavior of a structure at runtime. For instance, there is no danger of passing an immutable structure to another random portion of code. They can't changed it ever so you can program reliably against that structure. Robert Pickering has written a good blog post about the benefits of immutability. The post can be found [here](https://dzone.com/articles/getting-know-immutable-data-st) or at the [archive.org backup](https://web.archive.org/web/20190910111734/http://strangelights.com/blog/archive/2008/05/18/1617.aspx).
What are the benefits to marking a field as `readonly` in C#?
[ "", "c#", "readonly", "processing-efficiency", "memory-efficient", "" ]
i want something like this 1. the user enter a website link 2. i need check the link if the link doesn't start with 'http://' I want to append 'http://' to the link . how can I do that in PHP ?
``` if (stripos($url, 'http://') !== 0) { $url = 'http://' . $url; } ```
I'll recommend a slight improvement over tom's > ``` > if (0 !== stripos($url, 'http://') && 0 !== stripos($url, 'https://')) { > $url = 'http://' . $url; > } > ``` However, this will mess up links that use other protocols (ftp:// svn:// gopher:// etc)
how can i check the start of the string in php?
[ "", "php", "string", "hyperlink", "" ]
Consider the following code snippet ``` private void ProcessFile(string fullPath) { XmlTextReader rdr = new XmlTextReader("file:\\\\" + fullPath); while (rdr.Read()) { //Do something } return; } ``` Now, this functions fine when passed a path like: "C:\Work Files\Technical Information\Dummy.xml" But throws an error when passed "C:\Work Files\#Technical Information\Dummy.xml" Note that all folders and files specified exist and that the hash character is a valid character for paths. The error details are: System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Work Files\'. at System.IO.\_\_Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY\_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver) at System.Threading.CompressedStack.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state) at System.Xml.XmlTextReaderImpl.OpenUrl() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlTextReader.Read() Anybody know what's going on?
Try omitting the `file:///` protocol prefix. It works for me without one. I believe .NET will truncate any part after the `#` if it believes this to be a URL. This is only a guess based on the error message but it seems logical considering that the part after the `#` character isn't processed by the server but rather by the client in other scenarios (e.g. web browsers).
Adding to Konrad's answer, if you are using the file:// protocol, you need to use %23 for # then it works fine
Hash character in path throws DirectoryNotFoundException
[ "", "c#", ".net", "xmltextreader", "" ]
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like; "loop again? y/n"
``` while True: func() answer = raw_input( "Loop again? " ) if answer != 'y': break ```
``` keepLooping = True while keepLooping: # do stuff here # Prompt the user to continue q = raw_input("Keep looping? [yn]: ") if not q.startswith("y"): keepLooping = False ```
python - check at the end of the loop if need to run again
[ "", "python", "loops", "" ]
Java and C# support the notion of classes that can't be used as base classes with the `final` and `sealed` keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not? --- **Edit:** Since C++11 this is no longer true, you can specify that a class is [`final`](http://en.cppreference.com/w/cpp/language/final). --- On the one hand giving an object a virtual destructor means it will have a `vtable` and therefore consume 4 (or 8 on 64 bit machines) additional bytes per-object for the `vptr`. On the other hand if someone later derives from this class and deletes a derived class via a pointer to the base class the program will be ill-defined (due to the absence of a virtual destructor), and frankly optimizing for a pointer per object is ridiculous. On the [gripping hand](http://en.wikipedia.org/wiki/Gripping_hand) having a virtual destructor (arguably) advertises that this type is meant to be used polymorphically. Some people think you need an explicit reason to not use a virtual destructor (as is the subtext of [this question](https://stackoverflow.com/questions/300986)) and others say that you should use them only when you have reason to believe that your class is to be derived from, what do *you* think?
The question is really, do you want to *enforce* rules about how your classes should be used? Why? If a class doesn't have a virtual destructor, anyone using the class knows that it is not intended to be derived from, and what limitations apply if you try it anyway. Isn't that good enough? Or do you need the compiler to throw a hard error if anyone *dares* to do something you hadn't anticipated? Give the class a virtual destructor if you intend for people to derive from it. Otherwise don't, and assume that anyone using your code is intelligent enough to use your code correctly.
Every abstract class should either have a, * protected destructor, or, * virtual destructor. If you've got a public non-virtual destructor, that's no good, since it allows users to delete through that pointer a derived object. Since as we all know, that's undefined behavior. For an abstract class, you already need a virtual-table pointer in the object, so making the destructor `virtual` doesn't (as far as I'm aware) have a high cost in terms of space or runtime performance. And it has the benefit that derived classes automatically have their destructors `virtual` (see @Aconcagua's comment). Of course, you can also make the destructor `protected virtual` for this case. For a non-abstract class not intended to be deleted through a pointer to it, I don't think there's good reason to have a virtual destructor. It would waste resources, but more importantly it would give users a wrong hint. Just think about what weird sense it would make to give `std::iterator` a virtual destructor.
Should every class have a virtual destructor?
[ "", "c++", "virtual-destructor", "" ]
I have an ASP.NET page that uses a repeater nested within another repeater to generate a listing of data. It's to the effect of the following: ``` <asp:Repeater> <ItemTemplate> <span><%#Eval("Data1") %></span> <!-- and many more --> <asp:Repeater DataSource='<%#Eval("Data2")%>'> <HeaderTemplate> <ul> </HeaderTemplate> <ItemTemplate> <li><%#Container.DataItem%></li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater> </ItemTemplate> </asp:Repeater> ``` In the (C#) code-behind I'm basically using LINQ to pull a listing of information from an XML document and bind that information to the first repeater. Searching for the answer to this, it seems the method is to determine whether the data for the nested repeater is empty. If it is, then you set the visibility of the repeater to false. Unfortunately, I haven't been able to determine how to do that inline, and not in the code-behind (since it won't necessarily work for what I'm doing). Since my pages aren't validating now, because the ul ends up being empty for any items without Data2, and because I'd like to keep using an unordered list, I seek your help. Any ideas? Thanks! UPDATE: If it helps, since it could very well be possible to do in the code-behind, the LINQ is something to this effect: ``` var x = from y in z select new { Data1 = d, // etcetera Data2 = (from j in k where j.Value != String.Empty select j.Value).ToList() }; blah.DataSource = x; blah.DataBind(); ```
This won't **hide** the repeater completely, but you can subclass the Repeater control so that it includes a GridView-like empty data template: ``` using System; using System.Web.UI; using System.Web.UI.WebControls; public class EmptyCapableRepeater : Repeater { public ITemplate EmptyDataTemplate { get; set; } protected override void OnDataBinding ( EventArgs e ) { base.OnDataBinding( e ); if ( this.Items.Count == 0 ) { EmptyDataTemplate.InstantiateIn( this ); } } } ``` You can them use it in your .aspx like this: ``` <custom:EmptyCapableRepeater runat="server" ID="rptSearchResults"> <ItemTemplate> <%# Eval( "Result" )%> </ItemTemplate> <SeparatorTemplate> <br /> </SeparatorTemplate> <EmptyDataTemplate> <em>No results were found.</em> </EmptyDataTemplate> </custom:EmptyCapableRepeater> ```
Try something like: ``` <asp:Repeater runat="server" DataSource='<%#Eval("Data2")%>' Visible='<%# ((IEnumerable)Eval("Data2")).GetEnumerator().MoveNext() %>'> ``` for the nested repeater
How can I hide a repeater in ASP.NET C# if the DataSource contains no items?
[ "", "c#", "asp.net", "repeater", "" ]
When moving my .Net Compact Framework application to the SD-card of a Windows CE device, the program executes slower then running it from the internal memory. I thought, the start-up might be slower, but it is the whole program. There is no IO to the storage card. Why is my application so slow and how does the compact framework handles and loads the assemblies?
It has to do with demand-paging. Your app cannot be run directly from the SD-card, as SD is not executable media so it has to be pulled into RAM to run. Windows CE doesn't typically have a whole lot of RAM, so the loader doesn't pull your entire application into RAM to run. Sure, your heaps and stacks will be in RAM, but the actual IL code in the assembly itself is paged in as needed. It's also paged out when the system decides it no longer needs a specific page. This paging can have an impact on performance, though I'm a bit surprised that it's a large impact unless the app itself is really large (like if you have lots of embedded resources that it's pulling out of the assembly).
I agree with the previous "demand-paging" answer by ctacke. **A solution** you might try is to execute a loader program from the SD-card that copies your actual executable and DLLs from card to hard disk, and then execute your program from the loader. In subsequent executions the loader can detect if the hard disk version is up to date, and if so just launch it directly. If the hard disk version is not up to date, the loader will again copy out-of-date files from card and then execute the actual program. I have done this before from a program loaded at a remote network location, and it worked very well.
Why are my programs running from my SD card so slow?
[ "", "c#", "performance", "compact-framework", "sd-card", "" ]