Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am trying to insert a standard record into my db using linq2db, but i keep seeing examples to ADD method which i don't appear to have ... what i have currently is the following, as you can see i have my datacontext.... (no add method) ... the Reservation class is a separate class i created as a DTO - i presume this is correct? Any help really appreciated, ``` public bool AddReservation(Reservation reservation) { bool success = false; try { MiningDataContext db = new MiningDataContext(); db.Reservations. // NO ADD HERE } catch { } return success; } ```
You should use the method InsertOnSubmit() and then call SubmitChanges(). ``` public bool AddReservation(Reservation reservation) { bool success = false; try { MiningDataContext db = new MiningDataContext(); db.Reservations.InsertOnSubmit(reservation); db.SubmitChanges(); ... } catch { } return success; } ```
try ``` db.Reservations.InsertOnSubmit(reservation); db.SubmitChanges(); ```
Insert record into db using linq2sql/datacontext
[ "", "c#", "database", "visual-studio-2008", "linq", "linq-to-sql", "" ]
Trying to decide on a library for creating a window and capturing user input for my OpenGL app, but there are just way too many choices: * [GLUT](http://www.opengl.org/resources/libraries/glut/) ([win32](http://www.xmission.com/~nate/glut.html)) * [FreeGLUT](http://freeglut.sourceforge.net/) * [OpenGLUT](http://openglut.sourceforge.net/) * [SFML](http://www.sfml-dev.org/) * [GLFW](http://glfw.sourceforge.net/) * [SDL](http://www.libsdl.org/) * [FLTK](http://www.fltk.org/) * [OGLWFW](http://oglwfw.sourceforge.net/) * [Clutter](http://www.clutter-project.org/) * [Qt](http://qt.nokia.com/) * Others? GLUT is simply outdated. I liked GLFW but it seems you can't set the window position before displaying it (I wanted it centered, is that so much to ask?) so you see it appear and then shift over, which bothers me. Plus development seems to have stopped on it too. SFML has some nice features, but it uses event polling rather than callbacks which I prefer for decoupling. I don't think I need all the GUI features of FLTK. SDL is slow (doesn't seem to take advantage of the GPU). And the other 3 I don't know much about (FreeGLUT, OpenGLUT, OGLWFW). So which is the lesser of the evils? Are there others I haven't heard about? I'm just trying to make a simple 2D game. I'm familiar enough with OpenGL that I don't really need drawing routines, but I probably wouldn't complain about other functions that might be useful if they are implemented properly.
I'd go for Qt. Nice general purpose library + opengl support
[SDL](http://libsdl.org) allows you to create an OpenGL context that is accelerated (depending on drivers / hardware support). I know you tagged as C++, however **[pygame](http://www.pygame.org/news.html)** (python) is a great library for creating 2D games, which also supports an OpenGL context. Pygame is built on SDL. [Clutter](http://www.clutter-project.org/) is a new OpenGL based GUI library with bindings for Perl, Python, C#, C++, Vala and Ruby. I haven't used it myself. From the website: > Clutter uses OpenGL (and optionally > OpenGL ES for use on Mobile and > embedded platforms) for rendering but > with an API which hides the underlying > GL complexity from the developer. The > Clutter API is intended to be easy to > use, efficient and flexible.
OpenGL Windowing Library for 2009
[ "", "c++", "opengl", "" ]
Is it possible to Embed a PowerPoint Viewer into a C# Windows Form? I am currently use the following code: ``` objApp = new PowerPoint.Application(); //objApp.Visible = MsoTriState.msoTrue; objPresSet = objApp.Presentations; objPres = objPresSet.Open(ppsAction.FileInfo.FullName, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse); objSlides = objPres.Slides; //Run the Slide show objSSS = objPres.SlideShowSettings; objSSS.ShowType = Microsoft.Office.Interop.PowerPoint.PpSlideShowType.ppShowTypeSpeaker; objSSS.LoopUntilStopped = MsoTriState.msoTrue; objSSS.Run(); WindowWrapper handleWrapper = new WindowWrapper(objPres.SlideShowWindow.HWND); SetParent(handleWrapper.Handle, this.ApplicationPanel.Handle); this.ApplicationPanel.Visible = true; objPres.SlideShowWindow.Height = ApplicationPanel.Height; objPres.SlideShowWindow.Width = ApplicationPanel.Width; objPres.SlideShowWindow.Top = 0; objPres.SlideShowWindow.Left = 0; ``` It shows the viewer on the form but the placement and sizing is wrong. How would one size and place it correctly. **Another option**: I have encountered the Aximp.exe application meant to be used for showing ActiveX controls on the Win Forms in C#. How would I use this with the PPT Viewer?
See [this](http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/739d453e-092e-46c3-8bc2-1836d5a9b4f8) link. You can also display the ppt in a WebBrowser control. [This](http://support.microsoft.com/kb/304662) might also be useful.
Thanks for good links, <http://support.microsoft.com/kb/304662> has useful info... That helped me :)
Embed PowerPoint Viewer in C# Win Form
[ "", "c#", "powerpoint", "" ]
> **Possible Duplicate:** > [Javascript Object.Watch for all browsers?](https://stackoverflow.com/questions/1029241/javascript-object-watch-for-all-browsers) I just read Mozilla's documentation for the [watch() method](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch). It looks very useful. However, I can't find something similar for Safari. Neither Internet Explorer. How do you manage portability across browsers?
I have created a small [object.watch shim](https://gist.github.com/384583) for this a while ago. It works in IE8, Safari, Chrome, Firefox, Opera, etc. ``` /* * object.watch v0.0.1: Cross-browser object.watch * * By Elijah Grey, http://eligrey.com * * A shim that partially implements object.watch and object.unwatch * in browsers that have accessor support. * * Public Domain. * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ // object.watch if (!Object.prototype.watch) Object.prototype.watch = function (prop, handler) { var oldval = this[prop], newval = oldval, getter = function () { return newval; }, setter = function (val) { oldval = newval; return newval = handler.call(this, prop, oldval, val); }; if (delete this[prop]) { // can't watch constants if (Object.defineProperty) // ECMAScript 5 Object.defineProperty(this, prop, { get: getter, set: setter }); else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy Object.prototype.__defineGetter__.call(this, prop, getter); Object.prototype.__defineSetter__.call(this, prop, setter); } } }; // object.unwatch if (!Object.prototype.unwatch) Object.prototype.unwatch = function (prop) { var val = this[prop]; delete this[prop]; // remove accessors this[prop] = val; }; ```
Unfortunately, this is not a portable solution. IE has nothing like this to my knowledge, though it would be awesome if there was
Watch for object properties changes in JavaScript
[ "", "javascript", "object", "cross-browser", "properties", "watch", "" ]
I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys & "string" values are `unicode`, but the layer they're being passed onto only accepts `str`. This is going to be called often, so I'd like to know what would be the fastest way to convert something like: ``` { u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } } ``` ...to: ``` { 'spam': 'eggs', 'foo': True, 'bar': { 'baz': 97 } } ``` ...bearing in mind the non-"string" values need to stay as their original type. Any thoughts?
``` DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 }, u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]} def convert(data): if isinstance(data, basestring): return str(data) elif isinstance(data, collections.Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, collections.Iterable): return type(data)(map(convert, data)) else: return data print DATA print convert(DATA) # Prints: # {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'} # {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'} ``` Assumptions: * You've imported the collections module and can make use of the abstract base classes it provides * You're happy to convert using the default encoding (use `data.encode('utf-8')` rather than `str(data)` if you need an explicit encoding). If you need to support other container types, hopefully it's obvious how to follow the pattern and add cases for them.
I know I'm late on this one: ``` def convert_keys_to_string(dictionary): """Recursively converts dictionary keys to strings.""" if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items()) ```
Fastest way to convert a dict's keys & values from `unicode` to `str`?
[ "", "python", "casting", "types", "" ]
How can I replace the number inside the brackets for any strings not matching the word "Field". So the number inside 'SomethingElse' and 'SomethingMore' could be replaced to a new value, but any bracketed value to the right side of the term 'Field' would not be touched. Note, the word "Field" will always stay the same, so it can be referenced as a magic string in the regex. ``` Field[50].SomethingElse[30] Field[50].SomethingMore[30] ``` Thanks. PS. Using JavaScript.
Try ``` str.replace(/(Field\[[^\]]*\]\.[^\[]*)\[(.*)\]/g, "$1["+value+"]"); ```
``` str.replace(/\b((?!Field\[)\w+)\[\d+\]/g, '$1[' + repl + ']'); ```
Replace value inside brackets using RegEx only where does not match
[ "", "javascript", "jquery", "regex", "" ]
Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?
Try using the `%default` string placeholder: ``` # This example taken from http://docs.python.org/library/optparse.html#generating-help parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: novice, intermediate, " "or expert [default: %default]") ```
And if you want to add default values automatically to all options that you have specified, you can do the following: ``` for option in parser.option_list: if option.default != ("NO", "DEFAULT"): option.help += (" " if option.help else "") + "[default: %default]" ```
Can Python's optparse display the default value of an option?
[ "", "python", "optparse", "" ]
Why can't I do: ``` Enumeration e = ... for (Object o : e) ... ```
Because [`Enumeration<T>`](http://java.sun.com/javase/6/docs/api/java/util/Enumeration.html) doesn't extend [`Iterable<T>`](http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html). Here is an [example of making Iterable Enumerations](http://www.javaspecialists.eu/archive/Issue107.html) using the adapter pattern. As to why that's an interesting question. This isn't exactly your question but it sheds some light on it. From the [Java Collections API Design FAQ](http://docs.oracle.com/javase/7/docs/technotes/guides/collections/designfaq.html): > **Why doesn't Iterator extend Enumeration?** > > We view the method names for > Enumeration as unfortunate. They're > very long, and very frequently used. > Given that we were adding a method and > creating a whole new framework, we > felt that it would be foolish not to > take advantage of the opportunity to > improve the names. Of course we could > support the new and old names in > Iterator, but it doesn't seem > worthwhile. That basically suggests to me that Sun wants to distance themselves from Enumeration, which is very early Java with quite a verbose syntax.
Using the `Collections` utility class, `Enumeration` can be made iterable like: ``` Enumeration headerValues=request.getHeaders("mycustomheader"); List headerValuesList=Collections.list(headerValues); for(Object headerValueObj:headerValuesList){ ... do whatever you want to do with headerValueObj } ``` This uses the [`Collections.list`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/Collections.html#list(java.util.Enumeration)) method, which copies the `Enumeration` data into a new `ArrayList`. > Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.
Why can't I use foreach on Java Enumeration?
[ "", "java", "loops", "" ]
I'm messing with the CSS on an input box in CSS, to make the text bigger, adding a border, changing color, etc. I've aligned the bigger text to fit nicely (vertically-aligned) within my input box using padding, but the little blinking text cursor is terribly aligned (hugs the bottom). I'm wondering if there is a way to adjust the blinking text cursor on its own without messing up the positioning of the text. Thanks! Matt Heres the CSS: ``` div#search_box { height:32px; width: 366px; float:left; margin-left:86px; margin-top:14px; background-color: #ffffff; border: 2px solid #b66b01; } input#search_input { border:none; position: relative; float: left; height: 32px; width: 335px; font-size: 18px; padding-top: 9px; padding-left: 4px; outline-style:none; font-family: Helvetica, Arial, "MS Trebuchet", sans-serif; color: #5a5a5a; } div#search_icon { width:22px; height:24px; float:right; margin-right:5px; margin-top:4px; cursor: pointer; background: url('images/magnifier.png'); } ``` HTML: ``` <div id="search_box"> <input type="text" name="query" id="search_input" autocomplete="off"/> <div id="search_icon"> </div> ``` Result: [![search](https://i.stack.imgur.com/y1cr8.png)](https://i.stack.imgur.com/y1cr8.png)
Your problem is that you're not taking into account padding on the input box when you're specifying its height. You're specifying a height of 32px, but any padding gets added to that, so the height of your input box is actually 32 + 9 + 4 = 45px. The cursor is being vertically centered in the 45px tall input box, but your border is around the 32px tall div. Change 'height: 32px' to 'height: 19px' on the search input and it works. I (very highly) recommend using [Firebug](http://getfirebug.com/). It's very useful for figuring out these sorts of things.
Sidenote: you don't need `div#search_icon`, your input could have the following background: ``` background: white url('images/magnifier.png') no-repeat right NNpx; ```
Vertically aligning the text cursor (caret?) in an input box with jQuery, Javascript or CSS
[ "", "javascript", "jquery", "html", "css", "input", "" ]
I have a huge array coming back as search results and I want to do the following: Walk through the array and for each record with the same "spubid" add the following keys/vals: "sfirst, smi, slast" to the parent array member in this case, $a[0]. So the result would be leave $a[0] in tact but add to it, the values from sfirst, smi and slast from the other members in the array (since they all have the same "spubid"). I think adding the key value (1, 2, 3) to the associate key (sfirst1=> "J.", smi1=>"F.", slast1=>"Kennedy") would be fine. I would then like to DROP (unset()) the rest of the members in the array with that "spubid". Here is a simplified example of the array I am getting back and in this example all records have the same "spubid": ``` Array ( [0] => Array ( [spubid] => A00502 [sfirst] => J. [smi] => A. [slast] => Doe [1] => Array ( [spubid] => A00502 [sfirst] => J. [smi] => F. [slast] => Kennedy [2] => Array ( [spubid] => A00502 [sfirst] => B. [smi] => F. [slast] => James [3] => Array ( [spubid] => A00502 [sfirst] => S. [smi] => M. [slast] => Williamson ) ) ``` So in essence I want to KEEP $a[0] but add new keys=>values to it (sfirst$key, smi$key, slast$key) and append the values from "sfirst, smi, slast" from ALL the members with that same "spubid" then unset $a[1]-[3]. Just to clarify my IDEAL end result would be: ``` Array ( [0] => Array ( [spubid] => A00502 [sfirst] => J. [smi] => A. [slast] => Doe [sfirst1] => J. [smi1] => F. [slast1] => Kennedy [sfirst2] => B. [smi2] => F. [slast2] => James [sfirst3] => S. [smi3] => M. [slast3] => Williamson ) ) ``` In most cases I will have a much bigger array to start with that includes a multitude of "spubid"'s but 99% of publications have more than one author so this routine would be very useful in cleaning up the results and making the parsing process for display much easier. \*\*\*UPDATE I think by over simplifying my example I may have made things unclear. I like both Chacha102's and zombat's responses but my "parent array" contains A LOT more than just a pubid, that just happens to be the primary key. I need to retain a lot of other data from that record, a small portion of that is the following: ``` [spubid] => A00680 [bactive] => t [bbatch_import] => t [bincomplete] => t [scitation_vis] => I,X [dentered] => 2009-08-03 12:34:14.82103 [sentered_by] => pubs_batchadd.php [drev] => 2009-08-03 12:34:14.82103 [srev_by] => pubs_batchadd.php [bpeer_reviewed] => t [sarticle] => A case study of bora-driven flow and density changes on the Adriatic shelf (January 1987) . . . . . ``` There are roughly 40 columns that come back with each search query. Rather than hard coding them as these examples do with the pubid, how can I include them while still making the changes as you both suggested. Creating a multi-dimensional array (as both of you suggested) with the authors being part of the multi-dimension is perfectly fine, thank you both for the suggestion. \*\*\*\* UPDATE: Here is what I settled on for a solution, very simple and gets the job done nicely. I do end up creating a multi-dimensional array so the authors are broken out there. Over simplified solution: ``` $apubs_final = array(); $spubid = NULL; $ipub = 0; foreach($apubs as $arec) { if($spubid != $arec['spubid']) { $ipub++; $apubs_final[$ipub] = $arec; // insert UNSET statements here for author data $iauthor = 0; $spubid = $arec['spubid']; } $iauthor++; $apubs_final[$ipub]['authors'][$iauthor]['sauthor_first'] = $arec['sfirst']; } ```
``` // First, probably the more parsable way. foreach($array as $key => $values) { $end[$spuid] = $values; $spuid = $values['spuid'] $end[$spuid]['authors'][] = array('sfirst' => $values['sfirst'], 'smi' => $values['smi'], 'slast' => $values['slast']); } ``` Which will get an array like this ``` Array( [A00502] => Array( [supid] => A00502 .... other values ..... [authors] => Array( [0]=> Array( ['sfirst'] => '', ['smi'] => '', ['slast'] => '') ) ) ) ``` I find this way to be much more parse-able if you plan on showing it on a page, because it uses arrays so you can foreach the authors, which is how I've seen many people do it for attributes like that. If you really do want your ideal format, use this afterwards ``` $count = 0; foreach ($end as $supid => $values) { $other_end[$count] = $values; $other_end[$count]['spuid'] = $spuid; foreach($values['authors'] as $key => $author) { if($key == 0) { $suffix = ''; } else { $suffix = $key; } $other_end[$count]['sfirst'.$suffix] = $author['sfirst']; $other_end[$count]['smi'.$suffix] = $author['smi']; $other_end[$count]['slast'.$suffix] = $author['slast']; } } ```
Why not instead make an array keyed on the spubid: ``` // assuming $array is your array: $storage = array(); foreach($array as $entry) { $bid = $entry['spubid']; if (!isset($storage[$bid])) { // duplicate entry - taking the author out of it. $stortmp = $entry; unset($stortmp['sfirst'], $stortmp['smi'], $stortmp['slast']); // add an authors array $stortmp['authors'] = array(); $storage[$bid] = $stortmp; } $author = array( 'sfirst' => $entry['sfirst'], 'smi' => $entry['smi'], 'slast' => $entry['slast']); $storage[$bid]['authors'][] = $author; } ``` Now your $storage array should look like: ``` Array( "A00502" => Array( "spubid" => "A00502", "authors" => Array( [0] => Array ( [sfirst] => J. [smi] => A. [slast] => Doe [1] => Array ( [sfirst] => J. [smi] => F. [slast] => Kennedy ``` And you could easily do a foreach on the authors to print them: ``` foreach ($storage as $pub) { echo 'Pub ID: '.$pub['spubid']."<br/>"; foreach ($pub['authors'] as $author) { echo 'Author: '.$author['sfirst'].' '.$author['smi'].' '.$author['slast']."<br/>"; } } ``` And as an added bonus, you can access `$storage['A00502']`. **UPDATED FOR COMMENT** It seems that your array is probably coming from some sort of SQL query that involves a JOIN from a publications table to a authors table. This is making your result dataset duplicate a lot of information it doesn't really need to. There is no reason to have all the publication data transferred/retrieved from the database multiple times. Try rewriting it to get a query of all the books its going to display, then have a "authors" query that does something like: ``` SELECT * FROM authors WHERE spubid IN ('A00502', 'A00503', 'A00504'); ``` Then convert it into this array to use for your display purposes. Your database traffic levels will thank you.
Group 2d array rows by identifying column value and append incremented number to the keys of subsequent group data
[ "", "php", "arrays", "multidimensional-array", "append", "grouping", "" ]
Did any body implemented a Monitor with signaling (wake up waiting threads) using a mutex and condition variables in C++. I dont know how to start. Any sample code or online article will be great. Are there any open source libraries who have implemented these? I need for windows and linux. But to start with windows(win32) will be fine.
[This Qt Quarterly article](http://doc.trolltech.com/qq/qq21-monitors.html) explains how to do this using Qt's QMutex and QWaitCondition. But you should be able to reimplement it with whatever mutex class you want to use.. See also the more advanced example in [here](http://doc.trolltech.com/qq/qq22-monitors2.html)..
Check out [boost::thread::condition\_variable](http://www.boost.org/doc/libs/1_39_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref) together with samples. It can be used to wait for the condition with or without a timeout. I think it's a fairly elegant solution which should do exactly what you need in this case, and do it in a portable way.
Implementing Monitor with signaling using mutex and condition variable in C++
[ "", "c++", "multithreading", "synchronization", "" ]
I've been programming for a few years in C# and XML. I used only the basics of those languages and have survived on the web for info like arrays and text manipulations. But when I am get interview, the interviewers ask only advanced questions - I found the answers later in the Advanced sections in the books on the subject. Why do the interviewers ask such advanced questions? The job looks almost the same as what I was previously doing, so there's need for advanced knowledge, like what class delegate is or XPath commands. Questions are: 1. What version of XSL does .NET 3.5 uses? 2. What XPath command to use to get value in element X? 3. What are class delegates in C# 4. Does C# allows multiple interface inheritance? 5. How do you access GAC in C#?
There are two reasons that I ask them. 1. To see a person actually say "I do not know the answer to that", as opposed to trying to BS through the question. 2. To see what kind of logical problem solving skills a person has. Usually a question will be of one or the other, but not both. Both are extremely valuable in screening a perspective employee, however. Also, the question might not actually be "advanced" for the position. It is reasonable to assume that Senior-level and/or Architects can answer questions that a Junior to Mid-level might not.
Perhaps because they are trying to find programmers who know more than the basic stuff. If they are trying to distinguish between a field of candidates, it isn't helpful to ask questions that everyone knows the answer to - how do you select among those candidates? If you're going to hire only 1 or 2 out of a pool of candidates, you need to find some harder questions that only 1 or 2 out the pool can answer.
Why do interviewers ask advanced questions?
[ "", "c#", ".net", "xml", "" ]
I am creating a C# class library for use by other developers. How should I package it up - just zip up the DLL and put it on the website?
The recommended way is to upload the code source including build scripts to a web site such as [googlecode](http://code.google.com/intl/bg-BG/) so that other developers could download it and compile it but if it is closed source library zipping the assembly (mylibrary.DLL), documentation (mylibrary.XML) and debug information file (mylibrary.PDB) should be enough.
If it is just a DLL then I wouldn't bother zipping it. However it would be nice if you did zip up some documentation with it along with a sample configuration file if applicable.
What is the recommended way to package up a C# Class Library (DLL)?
[ "", "c#", "packaging", "" ]
I'm really trying to like generics, but so far the trouble they've caused outweighs any benefits. Please, please show me I'm wrong. I understand the necessity of adding @SuppressWarnings("unchecked") when using generic-free frameworks (Spring, Hibernate). This alone really reduces generics' value, as does requiring classes be passed into the constructor to avoid the pitfalls of erasure. However, the real thorn always seems to be casting. I usually try for a while to get the syntax right, but then give up my attempt at purity, add a @SuppressWarnings, and move on with my life. Here's an example: I'm reflecting over a bean to look for differences between two instances. Some properties implement Comparable such that (a.equals(b) == false) but (a.compareTo(b) == 0) (e.g. BigDecimal, Date). In these cases, I want the property to be considered the same. ``` MyObject original = getOriginal(); MyObject updated = getUpdated(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(MyObject.class)) { // Assume I'm putting in the try/catch block Object pOriginal = pd.getReadMethod().invoke(original, (Object[]) null); Object pUpdated = pd.getReadMethod().invoke(updated, (Object[]) null); boolean isPropertySame; if (Comparable.class.isAssignableFrom(pOriginal.getClass())) { // Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable<T> should be parameterized isPropertySame = Comparable.class.cast(pOriginal).compareTo(Comparable.class.cast(pUpdated)) == 0; // The method compareTo(capture#19-of ?) in the type Comparable<capture#19-of ?> is not applicable for the arguments (capture#21-of ? extends Comparable) Comparable<?> comparable = Comparable.class.cast(pOriginal); isPropertySame = comparable.compareTo(comparable.getClass().getTypeParameters()[0].getGenericDeclaration().cast(pUpdated)) == 0; // Even if I get the generics right, I still get an error if pOriginal is java.sql.Timestamp and pUpdated is java.util.Date (happens all the time with Hibernate). isPropertySame = (help); } else { isPropertySame = pOriginal.equals(pUpdated); } if (!isPropertySame) { PropertyDelta delta = new PropertyDelta(pd, pOriginal, pUpdated); dao.save(delta); } } ``` Any ideas on what I could put into (help)?
Well, given that I was not able to find a "pure" way to do this, and the fact that I kept running into corner cases (like, in addition to this one, the difficulty of handling properties that are collections), I decided to make my delta-generating method *way* dumber. I realized that I'm only testing 9 different types of objects, so I can just test which of the 9 objects I'm comparing, then cast to that object and do object-specific testing. Implementing in this way took about an hour, and even though I have to re-compile every time any of the objects change, I figure I'm still in the black even if I spend days on this maintenance. So, in the end, I guess the answer is that there is no answer. Java generics are implemented in such a way that it is impossible to avoid occasionally suppressing compiler warnings and risk run-time class cast exceptions.
This looks to me like going about it the hard way. You can either have your beans implement comparable, in which case you just compare them directly, or you create a comparator - ``` public class Bean implements Comparable<Bean> {...} public int compareTo(Bean other){ ... } } ``` or ``` public int compare(Bean a, Bean b){ Comparator<Bean> c = new Comparator<Bean>(){ public int compareTo(Bean a, Bean b){ ... } public boolean equals(Object o){.. } }; return c.compare(a, b); } ``` I agree with you that java generics can get a bit, er... convoluted.
Casting to a Comparable, then Comparing
[ "", "java", "generics", "" ]
So I started reading [Jon Skeet's 2nd edition of C# in depth](http://www.manning.com/skeet2/) and kind of confused about the following code in terms what it does and what is wrong with it (ch 13, section: Immutability and object initialization) ``` Message message = new Message( "skeet@pobox.com", "csharp-in-depth-readers@everywhere.com", "I hope you like the second edition") { Subject = "A quick message" // <= {Subject = "A quick message" }; what is it? }; ``` Elaboration on this topic, would help tremendously! Would someone explain that?
This code: ``` Message message = new Message( "skeet@pobox.com", "csharp-in-depth-readers@everywhere.com", "I hope you like the second edition") { Subject = "A quick message" }; ``` is equivalent to this: ``` Message tmp = new Message("skeet@pobox.com", "csharp-in-depth-readers@everywhere.com", "I hope you like the second edition"); tmp.Subject = "A quick message"; Message message = tmp; ``` That's just object initializer syntax: see chapter 8 for more details. The problems with this are: * It's not clear what all the string arguments mean - what's "from", what's "to", what's the body etc * It requires the type to be mutable (unfortunate for all kinds of reasons) * If you want to *also* specify the subject in the constructor, you end up with a bunch of different overloads * If you have cross-validation between (say) subject and body, you need to be careful about when you do it With optional parameters and named arguments, all of this is solved: ``` // The argument names may be wrong here; I don't have the book with me. // Intellisense will prompt you though :) Message message = new Message( from: "skeet@pobox.com", to: "csharp-in-depth-readers@everywhere.com", body: "I hope you like the second edition", subject: "A quick message); ``` It's clear what means what, it's all in a constructor call so the type can be immutable, you can have a single constructor with optional parameters (e.g. here we could have a `byte[] attachment = null` parameter specified in the constructor), and you can do all the validation in one place. Lovely.
Well, the "Message" class is clearly mutable, as you are setting various properties; in the constructor and in the initialisation clause. It's also confusing, I imagine, because he's setting the 'subject' field twice. Which one will be used?
Question about Immutability and object initialization from C# in depth 2nd. ed( MEAP)
[ "", "c#", ".net", "" ]
If I have a button: ``` <button id="button1"> ``` Normally I would write: ``` $("#button1").click(function () { //do something } ``` But I want to define a function that responds to all click events **except** when someone clicks on this button. Is there a selector that would allow me to target all other clickable elements in the document except `button1`?
I know you have accepted the answer above but I would advise strongly against this. You can use event delegation to do what you want with a lot less overhead to the dom. I know .live() exists but too many live handlers also impact performance. I prefer event delegation old style. Demo [here](http://jsbin.com/umaga) ``` $(function(){ $('body').click( clickFn ); }); function clickFn( ev ) { if (ev.target.id != 'button1' ){ //do your stuff console.log('not a #button1 click'); } } ```
You could use the [:not selector](http://docs.jquery.com/Selectors/not): ``` $('button:not(#button1)').click(function(){ //Do something }); ``` The above selector will match all the button elements, except the one with id = "button1". If you want really to select all the elements under the body tag, you can use the ["All"](http://docs.jquery.com/Selectors/all) (`*`) selector, and also exclude the elements with [:not(selector)](http://docs.jquery.com/Selectors/not) or [.not(expr)](http://docs.jquery.com/Traversing/not#expr): ``` $('body *:not(#button1)').click(function(){ //Do something }); ``` Or ``` $('body *').not('#button1').click(function(){ //Do something }); ``` If you do so, you could have some event bubbling or propagation issues, you can handle this with the [event.stopPropagation](http://docs.jquery.com/Events/jQuery.Event#event.stopPropagation.28.29) function.
How to use a global selector to respond to all click events except on one element?
[ "", "javascript", "jquery", "css-selectors", "global", "" ]
I have a data-analysis question, that I could easily solve with some T-SQL or some scripting, but I was wondering if there was a clever SQL solution. The problem is that it messes a bit with SQL's row-independence assumption a bit. I have a table that consists of name-value pairs associated with a user and ordered by submission, for example: ``` ID USERID VARIABLE VALUE SUBMITTED 3115 2287 votech05 2 2009-02-02 15:34:00 3116 2287 comcol05 1 2009-02-02 15:34:00 3117 2287 fouryr05 1 2009-02-02 15:35:00 3118 2287 none05 2 2009-02-02 15:35:00 3119 2287 ocol1_05 2 2009-02-02 15:44:00 3120 2287 disnone 2 2009-02-02 15:45:00 3121 2287 dissense 2 2009-02-02 15:49:00 3122 2287 dismobil 3 2009-02-02 15:51:00 3123 2287 dislearn 3 2009-02-02 15:51:00 3124 2287 disment 3 2009-02-02 15:52:00 3125 2287 disother 2 2009-02-02 15:55:00 3126 2287 disrefus 7 2009-02-02 15:58:00 ``` I'd like to be able to determine the value and count of the largest group of identical values (when the data is ordered the ID primary key). So, for the above example, because I have four value=2 appearing in sequence, and only three value=3, I would want to report: ``` USERID VALUE COUNT 2287 2 4 ``` for the given user. Again, this would could be done fairly-quickly using other tools, but since the data set is quite large (about 75 million records) and frequently changing, it would be nice to be able to solve this problem with a query. I'm working with SQL Server 2005.
(Edited after comment) You can do that by assigning a "head" number to each group of consecutive values. After that you select the head number for each row, and do an aggregate per head. Here's an example, with CTE's for readability: ``` WITH OrderedTable as ( select value, rownr = row_number() over (order by userid, id) from YourTable where userid = 2287 ), Heads as ( select cur.rownr, CurValue = cur.value , headnr = row_number() over (order by cur.rownr) from OrderedTable cur left join OrderedTable prev on cur.rownr = prev.rownr+1 where IsNull(prev.value,-1) != cur.value ), ValuesWithHead as ( select value , HeadNr = (select max(headnr) from Heads where Heads.rownr <= data.rownr) from OrderedTable data ) select Value, [Count] = count(*) from ValuesWithHead group by HeadNr, value order by count(*) desc ``` This will output: ``` Value Count 2 4 3 3 1 2 2 1 2 1 7 1 ``` Use "top 1" to select the first row only. Here's my query to create the test data: ``` create table YourTable ( id int primary key, userid int, variable varchar(25), value int ) insert into YourTable (id, userid, variable, value) values (3115, 2287, 'votech05', 2) insert into YourTable (id, userid, variable, value) values (3116, 2287, 'comcol05', 1) insert into YourTable (id, userid, variable, value) values (3117, 2287, 'fouryr05', 1) insert into YourTable (id, userid, variable, value) values (3118, 2287, 'none05', 2) insert into YourTable (id, userid, variable, value) values (3119, 2287, 'ocol1_05', 2) insert into YourTable (id, userid, variable, value) values (3120, 2287, 'disnone', 2) insert into YourTable (id, userid, variable, value) values (3121, 2287, 'dissense', 2) insert into YourTable (id, userid, variable, value) values (3122, 2287, 'dismobil', 3) insert into YourTable (id, userid, variable, value) values (3123, 2287, 'dislearn', 3) insert into YourTable (id, userid, variable, value) values (3124, 2287, 'disment', 3) insert into YourTable (id, userid, variable, value) values (3125, 2287, 'disother', 2) insert into YourTable (id, userid, variable, value) values (3126, 2287, 'disrefus', 7) ```
This may be one of those problems best solved with cursors. Give this a try. It should be close, but it's not tested, since you didn't provide CREATE TABLE and INSERT statements with sample data to make that easy. ``` declare @userid int set @userid = 2287; declare C cursor fast_forward for select VALUE from T where USERID = @userid order by ID; declare @value int, @prevvalue int; declare @runcount int, @runlongest int; set @runlongest = 0; declare @valuelongest int; open C; fetch next from C into @value; while @@fetch_status = 0 begin if @value = @prevvalue set @runcount = @runcount + 1 else set @runcount = 1; if @runcount > @runlongest begin set @runlongest = @runcount; set @valuelongest = @value; end; set @prevvalue = @value; fetch next from C into @value; end; select @userid as USERID, @valuelongest as VALUE, @runlongest as [COUNT]; close C; deallocate C; ``` It won't be fast with 75M rows, but it probably won't be too slow, either. If your runs are very long, and you have the right indexes, you can do better by numbering the rows with row\_number in a temp table, then using a WHILE loop that jumps through a run at a time. Let me know if you think that's worth looking at (and if you can, post CREATE TABLE and INSERT statements with sample data).
Counting consecutive duplicate records with SQL
[ "", "sql", "sql-server-2005", "" ]
Can someone explain why the first of the two following examples is valid and the other is not? More specifically, how is a relationship created between T and TProperty in the first example? ``` //Example 1 class SomeClass<T> where T : class { void SomeMethod<TProperty>( Expression<Func<T,TProperty>> expression ){ ... } } //Example 2 class SomeClass { void SomeMethod<T,TProperty>( Expression<Func<T,TProperty>> expression ) where T : class{ ... } } ``` Given the two examples I would expect that the following implementations would work, but the second one does not. ``` //Implementation w/ Example 1 var sc = new SomeClass<MyDateClass>(); sc.SomeMethod( dt => dt.Year ); //Implementation w/ Example 2 var sc = new SomeClass(); sc.SomeMethod<MyDateClass>( dt => dt.Year ); ``` What I'm having difficulty wrapping my mind around is how the first example/implementation can ignore the TProperty generic type when executing SomeMethod, yet the second example/implementation can't and how an implicit relationship seems to be established between T and TProperty in example/implementation 1. **Solution** Change signature of method in example 2 as follows: ``` void SomeMethod<T>( Expression<Func<T,Object>> expression ){ ... } ``` While this will allow arbitrary objects to be used in the expression as a result it does allow for property articulation as described in implementation 2.
You're allowing the compiler to infer the type parameters. This works fine for case 1: ``` class SomeClass<T> where T : class { void SomeMethod<TProperty>( Expression<Func<T,TProperty>> expression ){ ... } } ``` because you first declare an instance: ``` var sc = new SomeClass<MyDateClass>(); ``` which tells the compiler that `T is MyDateClass`. Then, when you call the method: ``` sc.SomeMethod( dt => dt.Year ); ``` the compiler knows that `T is MyDateClass`, so `T.Year` must be an int. That's enough info to resolve `SomeMethod` as `SomeMethod<MyDateClass, int>`. Your second example, however, is explicitly stating the type parameter(s) - telling the compiler to *not* infer it: ``` sc.SomeMethod<MyDateClass>( dt => dt.Year ); ``` Unfortunately, it is trying to call `SomeMethod` with only a single type parameter (the `<MyDateClass>` bit). Since that doesn't exist, it'll complain and say you need 2 type parameters. If, instead, you were to call it like you did the first example: ``` sc.SomeMethod( dt => dt.Year ); ``` The compiler will complain, telling you that it cannot infer the type parameters - there's simply not enough info to determine what `dt` is. So, you could explicitly state *both* type parameters: ``` sc.SomeMethod<MyDateClass, int>( dt => dt.Year ); ``` Or, tell the compiler what `dt` is (which is what you did in the first example by newing `SomeClass<MyDateClass>`): ``` sc.SomeMethod((MyDateClass dt) => dt.Year ); ``` Edits and Updates: > So effectively the compiler is performing magic in the first example? Making an assumption that TProperty should be an int because .Year is an int? That would answer my question, can't say it's satisfying though. Not really magic, but a series of small steps. To illustate: 1. `sc` is of type `SomeClass<MyDateClass>`, making `T = MyDateClass` 2. `SomeMethod` is called with a parameter of `dt => dt.Year`. 3. `dt` *must* be a T (that's how `SomeMethod` is defined), which *must* be a `MyDateClass` for the instance `sc`. 4. `dt.Year` *must* be an int, as `MyDateClass.Year` is declared an int. 5. Since `dt => dt.Year` will *always* return an int, the return of `expression` *must* be int. Therefore `TProperty = int`. 6. That makes the parameter `expression` to `SomeMethod`, `Expression<Func<MyDateClass,int>>`. Recall that `T = MyDateClass` (step 1), and `TProperty = int` (step 5). 7. Now we've figured out all of the type parameters, making `SomeMethod<T, TProperty>` = `SomeMethod<MyDateClass, int>`. > [B]ut what's the difference between specifying T at the class level and specifying at the method level? `SomeClass<SomeType>` vs. `SomeMethod<SomeType>`... in both cases T is known is it not? Yes, `T` is known in both cases. The problem is that `SomeMethod<SomeType>` calls a method with only a single type parameter. In example 2, there are *2* type parameters. You can either have the compiler infer *all* type parameters for the method, or *none* of them. You can't just pass 1 and have it infer the other (`TProperty`). So, if you're going to explicitly state `T`, then you must also explicitly state `TProperty`.
First of all, your first example is incorrect, and won't compile as given. Aside from the missing `public` on the method, you define `T` twice - once on class, and once on method. This isn't an error in and of itself (though you'll get a warning), but when compiling the method call, you'll get the same error as you describe getting for example #2. So, I assume the actual code is like this: ``` //Example 1 class SomeClass<T> where T : class { public void SomeMethod<TProperty>(Expression<Func<T,TProperty>> expression) {} } ``` Furthermore, both your examples "ignore" (that is, infer) the actual type of `TProperty` in your call to `SomeMethod`. Your second example explicitly specifies the type of `T`, yes, but not `TProperty`. There's no implicit relationship established in the first example, either. When you instantiate `SomeClass<>` with `T=MyDateClass`, the signature of `SomeMethod` for that instantiation effectively becomes: ``` void SomeMethod<TProperty>(Expression<Func<MyDateClass, TProperty>> expression) ``` So the argument type of the lambda is known at this point, so you don't have to specify it. The return type of expression lambda is inferred as the type of expression on the right of `=>`, and that will be the inferred type of `TProperty`. In the second example, since `T` was not explicitly specified when instantiating the class, and since there's no way to infer it from method arguments, it has to be specified explicitly. Once you specify it, `TProperty` is inferred in exact same way as for example #1.
Lambda Expression for Class Property
[ "", "c#", ".net", "generics", "lambda", "" ]
I have a matrix class with the size determined by template parameters. ``` template <unsigned cRows, unsigned cCols> class Matrix { ... }; ``` My program uses matrices of a few sizes, typically 2x2, 3x3, and 4x4. By setting the matrix size with template parameters rather than run-time parameters allows the compiler to do a lot of inlining and optimization. But now I need a member function that returns a new matrix that has one fewer row and one fewer column. ``` Matrix<cRows - 1, cCols - 1> Reduced(unsigned row, unsigned col) const { ... } ``` The idea is that that it will return a matrix with the specified row and column deleted. In practice, this will only ever be called with a matrix that has at least three rows and three columns, returning a 2x2 at the smallest. The compiler doesn't see the lower bound, so it gets stuck in an infinite recursion trying to instantiate the templates with ever decreasing sizes. I tried putting two clues in the function itself that these smaller sizes cannot occur: ``` Matrix<cRows - 1, cCols - 1> Reduced(unsigned row, unsigned col) const { static_assert(cRows > 1 && cCols > 1); if (cRows <= 1 || cCols <= 1) throw std::domain_error(); Matrix<cRows - 1, cCols - 1> r; // ... initialize r ... return r; } ``` Neither the `static_assert` nor the `if`-statement seems to be a strong enough clue to the compiler that a 0x0 matrix will never be generated. (Ironically, it does complain about the `if`-statement having a constant compile-time condition.) Does anyone have any suggestions on how to avoid this compile-time infinite recursion?
You need to provide a specialization for a Matrix that has no rows or no columns. E.g. ``` template<unsigned cRows> class Matrix< cRows, 0 > { Matrix<cRows - 1, 0> Reduced() { return Matrix<cRows - 1, 0>(); } }; template<unsigned cCols> class Matrix< 0, cCols > { Matrix<0, cCols - 1> Reduced() { return Matrix<0, cCols - 1>(); } }; template<> class Matrix< 0, 0 > { Matrix<0, 0> Reduced() { return Matrix<0, 0>(); } }; ``` The issue you have is that attempting to instantiate the Matrix Reduced function with a particular set of template parameters always required instantiating the Matrix template for a different set of parameters (cRows - 1, cCols -1). This recursion has to be stopped somewhere. If you are only ever dealing with square matrices, then you can get away with fewer specializations. Also, you can could stop the recursion with a completely empty class if you are never going to use, say, a 1x1 matrix, the result of reduce on a 2x2 matrix. ``` template<> class Matrix< 1, 1 > {}; ```
You can specify a template specializations for small values of cRows or cCols which does not include that method.
How to avoid infinite recursion in C++ class templates
[ "", "c++", "templates", "recursion", "matrix", "" ]
I have a database storing "wiki formatted" text which I would like to display in XHTML using PHP. Here is an example output with all the wiki markup: ``` Default text == Heading 1 == === Heading 2 === ==== Heading 3 ==== ===== Heading 4 ===== ====== Heading 5 ====== '''Bold''' ''Italic'' <s>Strikethrough</s> * List item 1 * List item 2 # Numbered item 1 # Numbered item 2 [[Image:http://domain.com/image.png|Image name]] [http://google.com Link text goes here] > Blockquote <source lang="language">Source code</source> ``` Is that fairly standard wiki syntax? Is there a fairly standard way of interpreting it with PHP? Thanks in advance!
I came up with a hack, but it breaks on a lot of things. Is this the best way forward? **PHP:** ``` function wiki2html($text) { $text = preg_replace('/&lt;source lang=&quot;(.*?)&quot;&gt;(.*?)&lt;\/source&gt;/', '<pre lang="$1">$2</pre>', $text); $text = preg_replace('/======(.*?)======/', '<h5>$1</h5>', $text); $text = preg_replace('/=====(.*?)=====/', '<h4>$1</h4>', $text); $text = preg_replace('/====(.*?)====/', '<h3>$1</h3>', $text); $text = preg_replace('/===(.*?)===/', '<h2>$1</h2>', $text); $text = preg_replace('/==(.*?)==/', '<h1>$1</h1>', $text); $text = preg_replace("/'''(.*?)'''/", '<strong>$1</strong>', $text); $text = preg_replace("/''(.*?)''/", '<em>$1</em>', $text); $text = preg_replace('/&lt;s&gt;(.*?)&lt;\/s&gt;/', '<strike>$1</strike>', $text); $text = preg_replace('/\[\[Image:(.*?)\|(.*?)\]\]/', '<img src="$1" alt="$2" title="$2" />', $text); $text = preg_replace('/\[(.*?) (.*?)\]/', '<a href="$1" title="$2">$2</a>', $text); $text = preg_replace('/&gt;(.*?)\n/', '<blockquote>$1</blockquote>', $text); $text = preg_replace('/\* (.*?)\n/', '<ul><li>$1</li></ul>', $text); $text = preg_replace('/<\/ul><ul>/', '', $text); $text = preg_replace('/# (.*?)\n/', '<ol><li>$1</li></ol>', $text); $text = preg_replace('/<\/ol><ol>/', '', $text); $text = str_replace("\r\n\r\n", '</p><p>', $text); $text = str_replace("\r\n", '<br/>', $text); $text = '<p>'.$text.'</p>'; return $text; } ``` **Input:** ``` Default text == Heading 1 == === Heading 2 === ==== Heading 3 ==== ===== Heading 4 ===== ====== Heading 5 ====== '''Bold''' ''Italic'' <s>Strikethrough</s> * List item 1 * List item 2 # Numbered item 1 # Numbered item 2 [[Image:http://domain.com/image.png|Image name]] [http://google.com Link text goes here] > Blockquote <source lang="language">Source code</source> ``` **Output:** ``` <p> Default text<br/> <h1> Heading 1 </h1><br/> <h2> Heading 2 </h2><br/> <h3> Heading 3 </h3><br/> <h4> Heading 4 </h4><br/> <h5> Heading 5 </h5><br/> <strong>Bold</strong><br/> <em>Italic</em><br/> <strike>Strikethrough</strike> </p> <p> <ul> <li>List item 1</li> <li>List item 2</li> </ul> <br/> <ol> <li>Numbered item 1</li> <li>Numbered item 2</li> </ol> <br/> <img src="http://domain.com/image.png" alt="Image name" title="Image name" /> </p> <p> <a href="http://google.com" title="Link text goes here">Link text goes here</a> </p> <p> <blockquote> Blockquote</blockquote><br/> <pre lang="language">Source code</pre><br/> </p> ```
I would say that the most standard wiki-like format around today is [markdown](http://daringfireball.net/projects/markdown/). There are libraries available for almost any platform, [including PHP](http://michelf.com/projects/php-markdown/).
Converting wiki format to XHTML
[ "", "php", "xhtml", "wiki", "" ]
I have a cron that for the time being runs once every 20 minutes, but ultimately will run once a minute. This cron will process potentially hundreds of functions that grab an XML file remotely, and process it and perform its tasks. Problem is, due to speed of the remote sites, this script can sometimes take a while to run. Is there a safe way to do this without [a] the script timing out, [b] overloading the server [c] overlapping and not completing its task for that minute before it runs again (would that error out?) Unfortunately caching isnt an option as the data changes near real-time, and is from a variety of sources.
I think a slight design change would benefit this process quite a bit. Given that a remote server could time out, or a connection could be slow, you'll definitely run into concurrency issues if one slow job is still writing files when another one starts up. I would break it into two separate scripts. Have one script that is only used for fetching the latest XML data, and another for processing it. The fetch script can take it's sweet time if it needs to, while the process script continually looks for the newest file available in order to process it. This way they can operate independently, and the processing script can always work with the latest data, irregardless of how long either script takes to perform.
have a stack that you keep all the jobs on, have a handful of threads who's job it is to: * Pop a job off the stack * Check if you need to refresh the xml file (check for etags, expire headers, etc.) * grab the XML (this is the bit that could take the time hence spreading the load over threads) if need be, this should time out if it takes too long and raise the fact it did to someone as you might have a site down, dodgy rss generator or whatever. * then process it This way you'll be able to grab lots of data each time. It could be that you don't need to grab the file at all (would help if you could store the last etag for a file etc.) One tip, don't expect any of them to be in a valid format. Suggest you have a look at Mark Pilgrims RSS RegExp reader which does a damn fine job of reading most RSS's Addition: I would say hitting the same sites every minute is not really playing nice to the servers and creates alot of work for your server, do you really need to hit it that often?
Processing many rss/xml feeds in a cron file without overloading server
[ "", "php", "cron", "" ]
A C++ hash\_map has the following template parameters: ``` template<typename Key, typename T, typename HashCompare, typename Allocator> ``` How can I specify a Allocator without specifying the HashCompare? This won't compile :( ``` hash_map<EntityId, Entity*, , tbb::scalable_allocator> ```
There's one trick you can use which will at least save you having to work out what the default is, but it does require that you know the name of the type as it is defined in `hash_map`. The hash\_map will probably be declared something like: ``` class allocator {}; class hash_compare {}; template<typename Key , typename T , typename HashCompare = hash_compare , typename Allocator = allocator> class hash_map { public: typedef HashCompare key_compare; // ... }; ``` We cannot leave out the default for the hash, but we can refer to the default using the member typedef: ``` hash_map<EntityId , Entity* , hash_map<EntityId,Entity*>::key_compare // find out the default hasher , tbb::scalable_allocator> hm; ``` If you're going to use the type a lot, then create a typedef: ``` typedef hash_map<EntityId,Entity*>::key_compare EntityKeyCompare; hash_map<EntityId , Entity* , EntityKeyCompare , tbb::scalable_allocator> hm; ```
The simple answer is that you can't. You cannot skip a template parameter and have it choose the default value for the template. Your only option is to find out what the default is and insert it into your declaration.
Skipping a C++ template parameter
[ "", "c++", "templates", "" ]
A Microsoft Access implementation is throwing a type mismatch error while trying to execute a macro that opens up some queries. Most of the tables are linked to a SQL Server and I need to join two of the tables together that have different datatypes. **Table A:** REFERENCE TEXT **Table B:** REFNO NUMBER I would ordinarily want to correct the issue on the SQL Server side, but there are multiple apps hitting the same database and it would take a considerable amount of time to test all of them. Furthermore, we are in the process of completely rewriting this application and any work I do today is completely throw-away... If there is a way to make this join possible in access, I would save all kinds of time...
Within Access you could use the CLng (or Cint) function to convert the Table A's REFERENCE values from text to number. I would prefer to create a view of Table A in SQL Server to transform the field's data type before Access gets the data. You shouldn't need to test the view against your other existing apps. When your re-write make the view no longer useful, just discard it.
You can do the comparison in the criteria. ``` SELECT [REFERENCE], [REFNO] FROM [Table a], [Table b] WHERE [REFERENCE]=cstr(nz([REFNO],"")) ``` You can also do a passthrough - a query in access that executes on the sql server and returns only the data. ``` SELECT [REFERENCE], [REFNO] FROM [Table a], [Table b] WHERE [REFERENCE]=cast([REFNO] as varchar(25)) ``` HTH
How to join tables together on columns with different datatypes?
[ "", "sql", "database", "ms-access", "join", "types", "" ]
Can someone please explain the following Argument Exception : **The structure must not be a value class** to me please. It's being cause by the following line of code in my program: ``` Marshal.PtrToStructure(m.LParam, dbh); ``` given that `dbh` is of type: ``` [StructLayout(LayoutKind.Sequential)] public struct Device_Broadcast_Header { public int dbch_size; public int dbch_devicetype; public int dbch_reserved; } ``` Thanks
You cannot call this particular [`Marshal.PtrToStructure`](http://msdn.microsoft.com/en-us/library/30ex8z62.aspx) overload with a value type (i.e. a `struct`). If you call [this overload](http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx) you can receive an instance of your type back.
Sorry for not giving a code example, but here is a [link](http://207.46.19.190/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.interop&tid=9b5d0652-cc9c-4ab1-87c2-baa5405d988c&cat=&lang=&cr=&sloc=&p=1) that might help you. Here is the key text from the above link: > The problem does nothing with the > RegisterTraceGuids API. > > According to the doc of > Marshal.PtrToStructure(IntPtr, Object) > <http://msdn.microsoft.com/en-us/library/30ex8z62.aspx> > , it throws the ArgumentException that > you saw when structure layout is not > sequential or explicit or structure is > a boxed value type. > > In this case, the structure is > declared as sequential, however, the > elements in the array > (traceGuidReg[i]) are boxed on the > managed heap because of the array > object, thus you got the error "the > structure must not be a value class." > > You would need to use the overload > Marshal.PtrToStructure Method (IntPtr, > Type) > <http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx> > and assign the result of > PtrToStructure to the array elements.
Argument Exception thrown by PtrToStructure
[ "", "c#", ".net", "marshalling", "hid", "" ]
many weeks ago recommended me for send emails, ActiveMQ. So i search information about this, but i don't understand totally how this works. Could someone explain me why i should use ActiveMQ for send emails ?
I think there has been a communication breakdown. `ActiveMQ` is a **"messaging"** system - this has nothing to do with emails! A messaging system (AMQ is built on the AMQp messaging protocol) is about *the reliable communication of data* and addresses issues such as: * Publish / subscribe * Point-to-point * Guaranteed delivery
@oxbow\_lakes's answer maybe correct for your situation, but there's another possibility. Maybe the reason for that recommendation (to use ActiveMQ) was so that the client application that wants to send an email can delegate the task of sending an email to an email service application through ActiveMQ. The benefit I can see is that the call would be asynchronous, so the client application will not block even when there are millions of emails to send, since that can be taken care of by the email service application in the background.
Why i should use ActiveMQ for send emails?
[ "", "java", "messaging", "activemq-classic", "" ]
How do I resize the info window once it's opened? I have a hyperlink inside the window which generates an AJAX-request; on the callback I would like to resize the info window.
It isn't possible to animate the resize of the info window, but there is a [reset](http://code.google.com/apis/maps/documentation/reference.html#GInfoWindow.reset) function. The documentation says that you can leave any parameter null, but if you leave the 'size' parameter null, you'll get an error. This means that you have to specify the size of the InfoWindow. However, since that ruins the original point of dynamically resizing the window, **I would strongly recommend simply closing the original info window and creating a new one** - which is what the reset function will appear to do anyhow.
Check out the following. What happens is that i create an initial info window with minimal info (see getInfoWindowHtml). The gmap.openInfoWindowHtml call provides for a callback which gets called after the infowindow opens. In that callback, make your ajax call and reset the window contents. There are two issues though: i couldnt get the window to resize exactly to the returned content, so i just used a standard size (see the new GSize(300, 150) in the anonymous function returned by markerClickFn) 2. Im my case, if a marker is near the extremes of the image bounds, parts of the info window would be clipped. IOW, the map does not recenter to include the infowindow. I can probably fix this, but it has not been a pressing issue. ``` function markerClickFn(venue, latlng) { return function() { var title = venue.Name; var infoHtml = getInfoWindowHtml(venue); // need to zoom in gmap.setZoom(13); gmap.openInfoWindowHtml(latlng, infoHtml, { onOpenFn: function() { var iw = gmap.getInfoWindow(); iw.reset(iw.getPoint(), iw.getTabs(), new GSize(300, 150), null, null); $("#info-" + venue.Id.toString()).load("/Venue/MapInfoWindow/" + venue.Id); } } ); }; } function getSidebarHtml(venue) { var url = "/Venue/Details/" + venue.Id; // actually should bring up infowindow var html = "<li id='venue-" + venue.Id + "'>\n"; html = html + venue.Name + "\n"; //html = html + "<p class='description'>" + trunc(venue.Description, 200) + "</p>\n"; html = html + "</li>"; return html; } function getInfoWindowHtml(venue) { var url = "/Venue/Details/" + venue.Id; // actually should bring up infowindow var html = "<div id='info-" + venue.Id + "'><a href='" + url + "' class='url summary'>" + venue.Name + "</a></div>\n"; return html; } function addVenueMarker(venue) { var icon = new GIcon(G_DEFAULT_ICON); icon.image = "http://chart.apis.google.com/chart?cht=mm&amp;chs=24x32&amp;chco=FFFFFF,008CFF,000000&amp;ext=.png"; var latLng = new GLatLng(venue.Lat, venue.Lng); var marker = new GMarker(latLng, { icon: icon }); var fn = markerClickFn(venue, latLng); GEvent.addListener(marker, "click", fn); marker.event_ = venue; marker.click_ = fn; venue.marker_ = marker; markers.push(marker); return marker; } ```
Google Maps: Dynamically resize infowindow
[ "", "javascript", "google-maps", "" ]
I have a data set consisting of time-stamped values, and absolute (meter) values. Sometimes the meter values reset to zero, which means I have to iterate through and calculate a delta one-by-one, and then add it up to get the total for a given period. For example: ``` Timestamp Value 2009-01-01 100 2009-01-02 105 2009-01-03 120 2009-01-04 0 2009-01-05 9 ``` the total here is 29, calculated as: ``` (105 - 100) + (120 - 105) + (0) + (9 - 0) = 29 ``` I'm using MS-SQL server for this, and open to any suggestions. Right now, I'm using a cursor to do this, which checks that the delta isn't negative, and then totals it up: ``` DECLARE CURSOR curTest CURSOR FAST_FORWARD FOR SELECT value FROM table ORDER BY timestamp OPEN curTest DECLARE @delta bigint, @current bigint, @last bigint SET @delta = 0 FETCH curTest INTO @current WHILE @@FETCH_STATUS = 0 BEGIN IF (@current IS NOT NULL) AND (@current > 0) BEGIN IF (@last IS NOT NULL) AND (@current > @last) SET @delta = @delta + (@current - @last) SET @last = @current FETCH curTest INTO @current END END CLOSE curTest DEALLOCATE curTest ``` It would be nice to get a data set like: ``` Timestamp Value LastValue 2009-01-01 100 NULL 2009-01-02 105 100 2009-01-03 120 105 2009-01-04 0 120 2009-01-05 9 0 ``` as then it would be easy to grab the deltas, filter for (Value > LastValue), and do a SUM(). I tried: ``` SELECT m1.timestamp, m1.value, ( SELECT TOP 1 m2.value FROM table WHERE m2.timestamp < m1.timestamp ORDER BY m2.timestamp DESC ) as LastValue FROM table ``` but this actually turns out to be slower than the cursor: When I run these together in SQL studio with 'show execution plan' on, the relative cost of this is 100% (with 7 or 8 operations - the majority in a clustered index scan on timestamp), and the cursor is 0% (with 3 operations). (What I'm not showing here for simplicity is that I have several different sets of numbers, with a foreign key in this table as well - so there is also always a WHERE clause limiting to a specific set. I have several places where I calculate these totals for a given time period for several sets at once, and thus it becomes quite the performance bottleneck. The non-cursor method can also be easily modified to GROUP BY the key and return all the sets at once - but this actually is even slower in my testing than running the cursor multiple times, because there is the additional overhead of the GROUP BY and SUM() operation, aside from it being slower overall anyways.)
Much the same... ``` create table #temp ([timestamp] date,value int); insert into #temp (timestamp,value) values ('2009-01-01',100) insert into #temp (timestamp,value) values ('2009-01-02',105) insert into #temp (timestamp,value) values ('2009-01-03',120) insert into #temp (timestamp,value) values ('2009-01-04',0) insert into #temp (timestamp,value) values ('2009-01-05',9); with numbered as ( select ROW_NUMBER() over (order by timestamp) id,value from #temp ) select sum(n1.value-n2.value) from numbered n1 join numbered n2 on n1.id=n2.id+1 where n1.value!=0 drop table #temp; ``` Result is 29, as specified.
Start with row\_number, then join back to yourself. ``` with numbered as ( SELECT value, row_number() over (order by timestamp) as Rownum FROM table ) select sum(n1.value - n2.value) from numbered n1 join numbered n2 on n1.Rownum = n2.Rownum +1 ``` Actually... you only want to pick up increases... so put a WHERE clause in, saying "WHERE n1.value > n2.value". And... make sure I've put them the right way around... I've just changed it from -1 to +1, because I think I had it flipped. Easy! Rob
Efficient way to calculate sum of deltas between consecutive rows?
[ "", "sql", "t-sql", "" ]
I want to retrieve all case-insensitive duplicate entries from an array. Is this possible in PHP? ``` array( 1 => '1233', 2 => '12334', 3 => 'Hello', 4 => 'hello', 5 => 'U' ); ``` Desired output array: ``` array( 1 => 'Hello', 2 => 'hello' ); ```
You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method: ``` $arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U'); // Convert every value to uppercase, and remove duplicate values $withoutDuplicates = array_unique(array_map("strtoupper", $arr)); // The difference in the original array, and the $withoutDuplicates array // will be the duplicate values $duplicates = array_diff($arr, $withoutDuplicates); print_r($duplicates); ``` Output is: ``` Array ( [3] => Hello [4] => hello ) ``` --- **Edit by @AlixAxel:** This answer is very misleading. It only works in this specific condition. This counter-example: ``` $arr = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U'); ``` **[Fails miserably](http://codepad.org/9EJQgHhj)**. Also, this is not the way to keep duplicates: ``` array_diff($arr, array_unique($arr)); ``` Since one of the duplicated values will be in `array_unique`, and then chopped off by `array_diff`. **Edit by @RyanDay:** So look at @Srikanth's or @Bucabay's answer, which work for all cases (look for case insensitive in Bucabay's), not just the test data specified in the question.
``` function get_duplicates ($array) { return array_unique( array_diff_assoc( $array, array_unique( $array ) ) ); } ```
Return only duplicated entries from an array (case-insensitive)
[ "", "php", "arrays", "duplicates", "filtering", "case-insensitive", "" ]
I have a string user setting and want to select a particular variable with the same name during the startup of my C# Windows app. e.g. I have a user setting (string) called UserSelectedInt, which is currently set to 'MyTwo'. (Please note that my variables are actually a lot more complex types than integers, I've just used them as examples.) ``` public static int MyOne = 12345; public static int MyTwo = 54321; public static int MyThree = 33333; public int myInt = SelectMyVariableUsing(MyApp.Settings.Default.UserSelectedInt) ``` The user may have selected 'MyTwo' last time they closed the app, so that is the variable I want to select during startup. I hope I'm making sense. Please can some let me know how would I achieve this? Thanks
Use a `Dictionary<string, int>`. That allows you to assign an integer value to a number of strings. If the string is user input, you need to check that it is valid before trying to retrieve the corresponding integer.
Sounds like you are trying to implement the [provider pattern](http://msdn.microsoft.com/en-us/library/ms972319.aspx). You may find using this is a better mechanism for you to use, especially as you say it is more complex than using ints. In your code you would reference the particular provider using your `MyApp.Settings.Default.UserSelectedInt` setting. I would say architecturally this would be a better mechanism than some of the other suggested answers.
How do I select a C# variable using a string
[ "", "c#", ".net", "" ]
Is there any tool to send (mimic) a windows message like 'WM\_ENDSESSION' to a windows service? OR How can I send a windows message to a process using C#? (I know only C#) EDIT: Purpose: Basically I have to debug a windows service for fixing a bug that occurs only on system shut down.
Generally, services don't have windows (let alone message pumps) to receive a windows message. If the bug really does only happen on shutdown (as opposed to just stopping the service), it may be the case that something depends on a resource that is going away, which is not being handled gracefully (in which case, the bug fix *might* be to set up the service dependencies correctly). Have you tried using the remote debugging tools to attach to the process prior to shutdown? It's worth investigating if you can get the problem to occur without shutting down, perhaps when just stopping the service with the Service Control Manager (no need to do this programmatically, as this is a debugging scenario), in which case, you can breakpoint OnStop() in your service (I'm assuming C#) and watch what happens.
Services should be controlled using [ServiceController class](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx) > Represents a Windows service and allows you to connect to a running or stopped service, manipulate it, or get information about it. You can use it to start, stop and communicate with services using this class.
Send windows message to a Windows Service
[ "", "c#", ".net", "winapi", "windows-services", "shutdown", "" ]
Which Java blocking queue is best for multiple producer and single or multiple consumers scenarios? I am testing with LinkedBlockingQueue but I am getting OutOfMemoryError exception. I am trying to achieve following things. 1. producer creates a object & put in a queue. 2. consumer grabs the data from queue & insert into database. There would be 400 producers and I can adjust consumers as I wish. Let me know any idea. **Update** Producer : It should listen to Server Socket. It reads the data from socket & construct the object (Domain objects) and put in a queue. Consumer : Take the object from queue & insert into DB (Hiberante & connection pooling supported) This my real environment. Process should be able to process at least 200 records/sec.I am testing the scalability of process and how to improve that. I hope this will give better idea. Helpful links : [vmoptions](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) [Monitoring and Managing Java SE 6 Platform Applications](http://java.sun.com/developer/technicalArticles/J2SE/monitoring/) [BlockingQueue](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html)
The problem is not which `Queue` implementation you use but rather how to approach the problem of throttling your producers **if** your consumers *cannot keep up*. One possible solution is to create a `LinkedBlockingQueue` with a fixed capacity, and have your producers call `offer(E e)`, which will return `false` if the queue is full. Another possible solution is to tailor the number of producers and consumers accordiingly.
Is each producer a separate thread ? Don't forget that each thread will allocate (by default) 512k of memory for its stack (in your case requiring 200Mb of VM memory just for the threads). You can reduce this via `-Xss`. Alternatively, just how big are the objects you're queuing ? I don't think you have a *queue* problem so much as some sort of scaling issue - e.g. producers producing faster than consumers can consume.
Which Java blocking queue is best for multiple producer and single or multiple consumers scenarios?
[ "", "java", "multithreading", "queue", "" ]
Is it possible to invoke an exe on a remote computer, supposing we know the absolute path of the exe where it lies? I have written a client and a server program and am able to get both work as expected when both are running. But now, all I want to do is to invoke the server program from client if server is not running. Seems like defeating the purpose of server-client model but still. If that is possible without knowing the login credentials of the remote system, then it'd be cool. Eg: There are softwares like 'PsExec' that need login credentials. I understand that, such a feature may not be there, as it would mean a serious security threat, but, I am just wondering if there is some sort of a workaround.
> If that is possible without knowing > the login credentials of the remote > system, then it'd be cool. Eg: There > are softwares like 'PsExec' that need > login credentials. > > I understand that, such a feature may > not be there, as it would mean a > serious security threat, but, I am > just wondering if there is some sort > of a workaround. Those "inconvenient" security rules are there for a purpose. You simply **do not** want people to be able to run any old program on your machine without proper authentication and authorization. Not even if you are behind a firewall. Why? In one word - Viruses! If some machine on your network gets infected with a virus (or similar malware), then all machines that run a non-authenticated remote execute service would be at serious risk of infection.
The only way you can execute an exe is by executing a local application which you have access to. There **must** be a part of the software running on the computer you want to execute an application on. From there, you can do a remote call from a second program on a remote machine asking the local one to do his job : execute. As stephen C said, it would be a violent breach of security if I could run exe on your machine without your permision.
How to invoke a remote program in Java?
[ "", "java", "" ]
Is there any performance difference between an instance method and an extension method?
Don't forget extension methods are just static method calls wrapped in syntactic sugar. So what you're really asking is > Is there a performance difference between static and instance methods The answer is yes and there are various articles available on this subject Some links * <http://msdn.microsoft.com/en-us/magazine/cc507639.aspx> * <http://msdn.microsoft.com/en-us/magazine/cc500596.aspx>
I would doubt there would be any performance difference because it is all syntactic sugar. The compiler just compiles it just as any other method call, except it is to a static method on a different class. Some more details from my blog about the syntactic sugar: <http://colinmackay.co.uk/2007/06/18/method-extensions/>
Performance Extension Method vs. Instance Method
[ "", "c#", "asp.net", "" ]
I need to start developing using this technology servlets/jsp with tomcat. I need to get up to speed fairly quick. What would you recommend to get up there fairly quick? No 900+ pages manuals. A good tutorial (even a video lectures) with lots of examples would be perfect. Thanks
* Check out [simple.souther.us](http://simple.souther.us) * Hanging out at [JavaRanch](http://www.coderanch.com/forums) is a good idea * Getting a [Head First Servlet and JSP](https://rads.stackoverflow.com/amzn/click/com/0596516681) is worth it * [J2EE tutorial](http://java.sun.com/javaee/5/docs/tutorial/doc/) is good to go too
I would install Tomcat, and look at all of the included examples. Each example shows a different feature or way of using Tomcat. If you start tomcat up with the defaults, you should be able to go straight to <http://localhost:8080/examples> to view them.
where is the best place to start learning about servlet/tomcat?
[ "", "java", "jsp", "tomcat", "servlets", "" ]
I have in a GridView control a TemplateField like: ``` <asp:TemplateField ItemStyle-Width="150px"> <ItemTemplate> <asp:DropDownList ID="ddlFields" runat="server" DataSourceID="odsOperator" DataTextField="Text" DataValueField="Value" /> <asp:HiddenField ID="hfFieldType" runat="server" Value='<%# Eval("FieldType")%>' /> </ItemTemplate> </asp:TemplateField> ``` I have a dropdown that I want to populate from a ObjectDataSource, but for each line I want to pass a Select Parameter so it populates with the right values ``` <asp:ObjectDataSource ID="odsOperator" runat="server" TypeName="OperatorFieldsDAO" SelectMethod="FindByType"> <SelectParameters> <asp:ControlParameter ControlID="hfFieldType" Type="String" Name="Type" PropertyName="Value" /> </SelectParameters> </asp:ObjectDataSource> ``` --- my OperatorFieldsDAO class is: ``` public class OperatorFieldsDAO { private List<OperatorField> OperatorFields { get { List<OperatorField> operatorFields = HttpContext.Current.Session["OperatorFields"] as List<OperatorField>; if (operatorFields == null) { operatorFields = new List<OperatorField>(); operatorFields.Add(new OperatorField("string", "contains", "C")); operatorFields.Add(new OperatorField("string", "begins with", "BW")); operatorFields.Add(new OperatorField("string", "is equal to", "E")); operatorFields.Add(new OperatorField("string", "is not equal to", "NE")); operatorFields.Add(new OperatorField("string", "is less than", "L")); operatorFields.Add(new OperatorField("string", "is greater than", "G")); operatorFields.Add(new OperatorField("string", "is less than or equal to", "LE")); operatorFields.Add(new OperatorField("string", "is greater than or equal to", "GE")); operatorFields.Add(new OperatorField("string", "is from", "F")); operatorFields.Add(new OperatorField("string", "is between", "B")); operatorFields.Add(new OperatorField("string", "is nothing", "N")); operatorFields.Add(new OperatorField("string", "is something", "S")); operatorFields.Add(new OperatorField("number", "is the same as", "S")); operatorFields.Add(new OperatorField("number", "is not the same as", "S")); operatorFields.Add(new OperatorField("number", "is one of", "S")); operatorFields.Add(new OperatorField("number", "is not one of", "S")); operatorFields.Add(new OperatorField("number", "is nothing", "N")); operatorFields.Add(new OperatorField("number", "is something", "S")); } return operatorFields; } } public OperatorFieldsDAO() { } [DataObjectMethod(DataObjectMethodType.Select)] public IEnumerable<OperatorField> FindAll() { return this.OperatorFields; } [DataObjectMethod(DataObjectMethodType.Select)] public IEnumerable<OperatorField> FindByType(String type) { List<OperatorField> r = new List<OperatorField>(); foreach (OperatorField f in this.OperatorFields) if (f.Type == type) r.Add(f); return r; } } ``` all of this to tell you that I get an error: > Could not find control 'hfFieldType' in ControlParameter 'Type'. What am I doing wrong? Do I need to programatically pass that selected parameter using the **OnRowDataBound** method?
to get this working I add to create two methods (one for the GridView and other for the ObjectDataSource), as well change the Select Parameter from a ControlParameter to a normal Parameter. The idea is to set the Parameter every time the row it's created... ``` protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList d = (DropDownList)e.Row.FindControl("ddlFields"); string type = ((HiddenField)e.Row.FindControl("hfFieldType")).Value; _type = type; d.DataBind(); } } protected void odsOperator_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) { e.InputParameters["Type"] = _type; } private string _type = ""; ``` and the ObjectDataSource will be ``` <asp:ObjectDataSource ID="odsOperator" runat="server" TypeName="OperatorFieldsDAO" SelectMethod="FindByType" onselecting="odsOperator_Selecting"> <SelectParameters> <asp:Parameter Type="String" Name="Type" /> </SelectParameters> </asp:ObjectDataSource> ``` I hope it helps anyone ...
Since you have: ``` <asp:HiddenField ID="hfFieldType" runat="server" .../> ``` Within a `TemplateField` of your view, there may be none, one or many instances of that field on the page. Therefore `hfFieldType` would not be a unique ID, in fact the actual ID will be determined at runtime. Thus your control parameter cannot find it since it is looking for its value in a property of a control called `hfFieldType` somewhere on the page. I haven't worked with ObjectDataSource in a few years, but I suspect you might want to hook into the [Selecting](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.selecting.aspx) event.
Understanding ObjectDataSource and Select Parameters
[ "", "c#", "asp.net", "gridview", "objectdatasource", "" ]
I'm trying to convert the following XML into a Time: ``` <time hour="18" minute="05" timezone="Eastern" utc-hour="-4" utc-minute="00" /> ``` I'm parsing the XML using SimpleXML, and storing that in a class. I also tried printing out the following: ``` print strtotime($x->time->attributes()->hour . ":" . $x->time->attributes()->minute) . "<br>\n"; ``` The results I got from that print looked something like this: ``` 1249254300 ``` I guess the result I'm expecting would be either **18:05** or **6:05 PM** Is there any way I can get it to convert to the style I'm expecting? Also, if I were to add the timezone onto the end is there any way for it to figure that out?
I would advise against using strtotime here. Instead try [mktime](http://www.w3schools.com/php/func_date_mktime.asp). ``` $time=mktime($x->time->attributes()->hour,$x->time->attributes()->minute,0,0,0,0) ``` Also you need to format the time stamp (what you printed out was the unix representation). You can do this with the [date](http://www.w3schools.com/php/php_date.asp) function. ``` date("H:i", $time); ```
You can bring it into a form [strtotime()](http://php.net/strtotime) understands (including the timezone info) ``` <?php $x = new SimpleXMLElement('<x> <time hour="18" minute="05" timezone="Eastern" utc-hour="-4" utc-minute="00" /> </x>'); $ts = sprintf('%02d:%02d %+03d%02d', $x->time['hour'], $x->time['minute'], $x->time['utc-hour'], $x->time['utc-minute']); $ts = strtotime($ts); echo gmdate(DateTime::RFC1123, $ts), "\n", date(DateTime::RFC1123, $ts); ``` My local timezone is CET/CEST (utc+2 in this case), therefore the script prints ``` Mon, 03 Aug 2009 22:05:00 +0000 Tue, 04 Aug 2009 00:05:00 +0200 ```
Construct PHP strings to time from XML
[ "", "php", "xml", "string", "time", "" ]
Is there a way to monitor folders in java to see when they are updated, ie file created, deleted, renamed,etc. And also is there any way to set it that it only looks for files that begin with a certain prefix, ie img?
In Java 7 there is a [`WatchService` API](http://download.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html) as part of NIO2. For earlier Java versions there's no pure Java solution except for manual polling.
See [my answer](https://stackoverflow.com/questions/1256012/notify-a-button-if-the-number-of-files-in-a-directory-change/1256042#1256042) to a similar question. The mechanisms detailed won't filter on a file name/type. You'll have to do that alongside the suggested solutions.
Java Folder Monitor for creation/deletion/etc?
[ "", "java", "file", "directory", "" ]
Is there a jQuery equivalent to this prototype code? ``` Ajax.Responders.register({ onException: function(x,y) { if(y.message!="Syntax error") new Insertion.After("toperrorbox","<p style='color:red'>"+y.message+"</p>"); } }); ```
<http://docs.jquery.com/Ajax/ajaxError#examples> ``` $('#toperrorbox').ajaxError(function (event, request, settings) { $(this).after("<p style='color:red'>"+ request.responseText +"</p>"); } ``` Attach a function to be executed whenever an AJAX request fails.
Prototype's `Ajax.Responders` are global listeners that listen to ALL ajax events. jQuery does indeed have an equivalent. The global [Ajax Events](http://docs.jquery.com/Ajax_Events). The syntax is a little different, due to jQuery's nature, but something similar to this should do the trick: ``` $('#toperrorbox').bind('ajaxError', function (event, XMLHttpRequest, ajaxOptions, thrownError) { // thrownError only passed if an error was caught // this == dom element listening var message = thrownError === undefined? XMLHttpRequest.responseText : thrownError.message; $(this).after("<p style='color:red'>"+ message +"</p>"); } ``` In this case, `XMLHttpRequest.responseText` will contain the body (if any) returned from the server on the failed request. And `thrownError` will contain the actual exception, which I believe you are actually after. But, I'd recommend checking to see if an exception was indeed passed in before trying to print its message, which is what I've done in my example. If it has caught an exception, it'll use that message, but if not, it'll use the server response. It is worth noting that with jQuery, all events are always bound to something. Usually a DOM Node, but possibly the `window` or the `document`. If you wanted to do the same thing, without binding to the specific element to act on (like the above example), you could bind the event to the `window` and select the element(s) to work on in your callback like this: ``` $(window).bind('ajaxError', function (event, XMLHttpRequest, ajaxOptions, thrownError) { // thrownError only passed if an error was caught // this == dom element listening var message = thrownError === undefined? XMLHttpRequest.responseText : thrownError.message; $('#toperrorbox').after("<p style='color:red'>"+ message +"</p>"); } ``` This may afford you greater control over the events, as you do not have to remember which elements they were bound to, and if you didn't use anonymous functions, you could `unbind` specific callbacks at will.
What is jQuery's equivalent to Prototype's Ajax.Responders.register?
[ "", "javascript", "jquery", "prototypejs", "" ]
I have a bit of code that will open a Word 2007 (docx) document and update the appropriate CustomXmlPart (thus updating the Content Controls in the document itself as they are mapped to the CustomXmlPart) but can't work out how to save this as a new file.! Surely it can't be that hard! My current thinking is that I need to open the template and copy the content into a new, blank document - file by file, updating the CustomXmlPart when I encounter it. Call me old fashioned but that sounds a little bit clunky to me! Why can't I just do a WordprocessingDocument.SaveAs(filename); ...? Please tell me I am missing something simple here. Thanks in advance
Are you referring to the OpenXml SDK? Unfortunately, as of OpenXml SDK 2.0, there's no SaveAs method. You'll need to: 1. Make a temporary copy of your template file, naming it whatever you want. 2. Perform your OpenXml changes on the above file. 3. Save the appropriate sections (ie. using the .`myWordDocument.MainDocumentPart.Document.Save()` method for the main content or `someHeaderPart.Header.Save()` method for a particular header).
OpenXml 2.8.1 has a [SaveAs](https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.packaging.openxmlpackage.saveas?view=openxml-2.8.1) method that seems to do the trick. ``` var document = WordprocessingDocument.Open(specificationPath, true); document.SaveAs("filePath/documentCopy.docx"); ```
Saving an OpenXML Document (Word) generated from a template
[ "", "c#", "ms-word", "openxml", "" ]
How do I pass a method as an argument? I do this all the time in Javascript and need to use anonymous methods to pass params. How do I do it in c#? ``` protected void MyMethod(){ RunMethod(ParamMethod("World")); } protected void RunMethod(ArgMethod){ MessageBox.Show(ArgMethod()); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } ```
[Delegates](http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx) provide this mechanism. A quick way to do this in C# 3.0 for your example would be to use [`Func<TResult>`](http://msdn.microsoft.com/en-us/library/bb534960.aspx) where `TResult` is `string` and lambdas. Your code would then become: ``` protected void MyMethod(){ RunMethod(() => ParamMethod("World")); } protected void RunMethod(Func<string> method){ MessageBox.Show(method()); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } ``` However, if you are using C#2.0, you could use an anonymous delegate instead: ``` // Declare a delegate for the method we're passing. delegate string MyDelegateType(); protected void MyMethod(){ RunMethod(delegate { return ParamMethod("World"); }); } protected void RunMethod(MyDelegateType method){ MessageBox.Show(method()); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } ```
Your ParamMethod is of type Func<String,String> because it takes one string argument and returns a string (note that the last item in the angled brackets is the return type). So in this case, your code would become something like this: ``` protected void MyMethod(){ RunMethod(ParamMethod, "World"); } protected void RunMethod(Func<String,String> ArgMethod, String s){ MessageBox.Show(ArgMethod(s)); } protected String ParamMethod(String sWho){ return "Hello " + sWho; } ```
Pass a method as an argument
[ "", "c#", "asp.net", "" ]
I'm working with Zend 1.8. I've set the default timezone to Europe/Helsinki, and I'm parsing a string that looks like this: ``` 2009-08-06 ``` with a statement like this: ``` new Zend_Date($dateStr, 'YYYY-MM-dd'); ``` It produces a date like this: ``` object(Zend_Date)#53 (8) { ["_locale:private"]=> string(5) "en_US" ["_fractional:private"]=> int(0) ["_precision:private"]=> int(3) ["_unixTimestamp:private"]=> string(10) "1249502400" ["_timezone:private"]=> string(15) "Europe/Helsinki" ["_offset:private"]=> int(-7200) ["_syncronised:private"]=> int(0) ["_dst:protected"]=> bool(true) } ``` So it apparently knows the time zone. However, when I try to get a string representation of the date, what I get isn't 2009-08-06, but instead 2009-08-05 11:00:00 PM -- the UTC time. What gives? Edit: I added an answer as well, but the cliff notes versio is, Zend\_Date::getDate() is broken, not the parsing or printing bits.
Well, as per usual, my assumptions were faulty. I went back to check all the steps that might go wrong, and as it happens, the timezones work fine when parsing and printing. The trouble is Zend\_Date::getDate(). The documentation says the following: ``` Returns a clone of $this, with the time part set to 00:00:00. ``` However, when I actually use it: ``` $date = Zend_Date::now(); $date = $date->getDate(); ``` The result is ``` Aug 8, 2009 11:00:00 PM ``` Now, that's decidedly not 00:00:00. This looks like [Zend Bug 4490](http://framework.zend.com/issues/browse/ZF-4490), although it's supposedly resolved in 1.7.0 and I'm running 1.8.1. I guess I'll have to reopen the bug.
Did you trying setting a locale in the Registry ? Something like that : ``` $locale = new Zend_Locale('fr_FR'); Zend_Registry::set('Zend_Locale', $locale); ``` *(Adapted to your locale, of course)* Would it help ?
Why does Zend_Date only take timezones into account when parsing?
[ "", "php", "datetime", "zend-framework", "" ]
I have small application that is uploading pictures to another website via webservice. My current problem is, that Axis is logging the whole xml message (including the binary data of the picture!) via STDOUT and I can't seem to figure out, how to disable it. My log4j settings for jboss (jboss-log4j.xml) includes an appender for normal STDOUT Info loggings, and I tried to disable axis with different category settings: ``` <appender name="STDLOG" class="org.jboss.logging.appender.RollingFileAppender"> <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/> <param name="File" value="${jboss.server.log.dir}/myapplication.log"/> <param name="Append" value="true"/> <param name="MaxFileSize" value="5MB"/> <param name="MaxBackupIndex" value="10"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n"/> </layout> </appender> ``` using this setting for STDOUT: ``` <category name="STDOUT"> <priority value="DEBUG"/> <appender-ref ref="STDLOG"/> </category> ``` I tried these category settings without any change in the result: ``` <category name="log4j.logger.org.apache.axis" additivity="false"> <priority value="ERROR"/> </category> <category name="org.apache.axis"> <priority value="ERROR"/> </category> ``` Some sample log output looks like this: ``` 2009-08-07 10:29:43,911 INFO [STDOUT] (http-127.0.0.1-8080-1) ======================================================= = Elapsed: 2190 milliseconds = In message: <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <addVehicleImage xmlns="urn:VMgrWebService"> <id xmlns="">APP-T4QKR3U</id> <idType xmlns="">chiffre</idType> <data xmlns="">9j4AAQSkZJRgABAQAAAQABAAD2wBDAAUDBAQEAwUEBAQFB QUGBww0TDMnrXAfKlLjnNJZcciiAOtqk9NG99qhZJKuyYq5k3G 8P2bVSOpT7rVddRP2Z/yqidRuMMKaO2CXRQNWP2jfOo4S4Bo3W removed rest of image data... IBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGe1UqaZJJy0jSHPGQ 2009-08-07 10:29:43,927 INFO [STDOUT] (http-127.0.0.1-8080-1) Upload result: true for image mypicture.JPG ``` **Update** I checked the axis-1.4.jar and there is a file called *simplelog.properties*: ``` # Logging detail level, # Must be one of ("trace", "debug", "info", "warn", "error", or "fatal"). org.apache.commons.logging.simplelog.defaultlog=info ``` Setting this to error within the jar, or as a category in jboss-log4j.xml didn't help at all. Anyone any idea how I can turn off the Axis logging or at least set it to ERROR level? Cheers Frank
Ok, after trying to find a better solution, the only real way was to check the old legacy code and turn all System.out calls into real logging statements (much better anyway), and then simply filter the remaining STDOUT messages into a different log file. One of the main reasons seems to be Jboss itself. [This discussion](http://www.mail-archive.com/axis-user@ws.apache.org/msg23504.html) from the axis2 mailing list explains why: Ahh, but you didn't mention you are using jboss! It pretty much forces you to use their parent log4 config . Ignore the axis2 logging in this case, and see: ~/jboss/server/default/conf/log4j.xml There you have to limit the categories. For example, you have: ``` <category name="org.apache"> <priority value="INFO"/> </category> ``` You could leave that as is and just get your logs out of server.log . I tried setting the category, without success. I assume this is because of differences between axis and axis2. So the only solution left was to go the good coding way and just don't use STDOUT in your own code ;-)
This might be a bit late in the day, but the problem does not seem to be that logging itself is done in Axis (via System.out and Commons Logging), but rather that the [LogHandler](http://ws.apache.org/axis/java/apiDocs/org/apache/axis/handlers/LogHandler.html) is present in the handler chain. That is how the elapsed time is getting logged. You can disable this handler from the [Axis configuration file](http://ws.apache.org/axis/java/reference.html#DeploymentWSDDReference)(s) - server-config.wsdd and/or client-config.wsdd, depending on whether you are using Axis as a server or a client. The reason why you are seeing messages in your console is probably due to the LogHandler.writeToConsole property being set to true. If you set LogHandler.writeToConsole to false, it should write into a file as defined by the LogHandler.fileName property. By default, the file name is axis.log.
Disable Axis log4j logging in jboss
[ "", "java", "jboss", "log4j", "axis", "" ]
I'm running the Python CLI under Linux: ``` bla:visualization> python Python 2.1.1 (#18, Nov 1 2001, 11:15:13) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> ``` For some reason the arrow keys and the delete key don't work: **delete:** ``` >>> x^H^H^H ``` **up arrow:** ``` >>> x^[[A^[[A ``` etc... How can I make these work?
The basic problem is that your Python installation was likely not compiled with the `readline` library. You can confirm this by trying to import the `readline` module: ``` import readline ``` You should get an error when you import if `readline` is not present. If this is the case, there's not much you can do other than recompile Python with the `readline` library, if you can.
Install iPython ( <http://ipython.scipy.org/> but can be installed using easy\_install or pip), it is much much better than the default CLI.
can't edit line in python's command line in Linux
[ "", "python", "linux", "command-line", "" ]
I read some scripts and I cannot understand why they put a class name in a constructor of other class: ``` public function __construct(AclassName $foo){ $this->foo=$foo; } ```
Because they want `$foo` to be an instance of `AclassName` only. Not an array, number, string, or an instance of a class that is not `AclassName` nor extends `AclassName`. In PHP is called [**type hinting**](http://www.php.net/manual/en/language.oop5.typehinting.php), although they're not really hints, but enforcements. ``` function foo (array $bar) { // $bar must be an array, otherwise an E_RECOVERABLE_ERROR is thrown } function baz (ClassName $bar) { // $bar must be an instance of ClassName } baz(new ClassName); // works OK baz(new StdClass); // error class ExtendsFromClassName extends ClassName {} baz(new ExtendsFromClassName); // works OK ``` Hinting may be done on interfaces or abstract classes too: ``` interface SomeInterface {} function baz(SomeInterface $object) { // $object must be an instance of a class which implements SomeInterface } class Foo implements SomeInterface {} baz(new Foo); // works OK ```
This creates a reference in an instance of the class associated with the constructor to an instance of `AclassName`. Presumably, then, the instance of the class associated with the constructor will collaborate with the `AclassName` instance to fulfill one or more of its responsibilities.
What means a class name in constructor of other class?
[ "", "php", "oop", "" ]
I've been happily coding an opensource game for fun, but I just realized that `Graphics.setColor()` doesn't understand 0xAARRGGBB. I want to get a more and more transparent colour, in which I'd draw some arcs (discs). My goal was to make them shine though each other like in this image: <http://kenai.com/projects/xplode> (the logo there) I know that transparency manipulation is possible with images (getRGB etc) yet this proves very slow for a game with lots of size and transparency changes. Is there any way i could draw transparent scalable discs in J2ME, without using JSR 184 nor JSR-226? I fear that there is now "good" way to deal with it and I'll just go on without this effects, but why not ask when in need ?
Transparency stuff doesn't need to be slow as long as you keep it to a minimum and stay away from very old handsets. You should also note that alpha is sometimes ignored on some implementations and sometimes quantized to ugly levels (Some motorola phones snap alpha values to the nearest 2-bit value. Bleh). I'd be tempted to approach this as a single transparent layer superimposed onto the screen. Keep an int array the size of your screen into which you will plot your transparent pixels (int[width \* height]). On each frame, make a call to Image.createRGBImage and draw that image to the screen. As an experiment, you might first want to make sure that the alpha processing isn't going to slow you down by filling this array with a constant value and plotting that to the screen. E.g. 0x80FF0000 should blend a red tint onto the screen and you can see easily if this alpha business is going to be workable on your chosen handset, i.e you can measure how it impacts your frame rate. Next you need to plot circles into this array. Look for [Bresenham's circle drawing algorithm](http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/bresenham.html) and rework it to plot into an int array of pixels. You might want to maintain a lookup table that has a pre-calculated radius/sqrt(2) for each radius you want to be able to plot. Next is how to blend colours to get them to overlap. The simplest would be just to plot a colour value with alpha into the pixel. You wouldn't get colour blending with already plotted circles but it would be cheap and the circles would blend with the background. Another method would be to ignore the colour blend but to do a simple merge on the alpha. E.g. ``` newColour = ((destColour & 0xFF000000) + 0x20000000) | srcColour; /* Where source colour is of the form 0x00RRGGBB. Note: Adding 0x20 to alpha each * time will only work for 7 overlapping circles. */ ``` The colour of the overlapping circle would dominate the underlying one, but the alpha would become more opaque where they overlap which would at least allow the player to see all the circles properly. If you wanted to do an accurate colour blend then the calculations are a lot more complicated, especially if you're blending one value with alpha onto another with alpha since the colour contributions from each pixel vary with the proportion of alpha in each colour. It's not impossible but making it efficient is a pain. I'd be tempted to go for a cheaper option.
I am not sure if you can do such a thing in a reasonably efficient manner using the Graphics class alone. Why don't you try OpenGL ES Specification for MIDP JSR 239?
Draw transparent arcs, not images, in J2ME?
[ "", "java", "graphics", "java-me", "mobile", "transparency", "" ]
I am using sql server 2008 and I'm trying to build a query for displaying some overall results from a single sql table. I want to display count(fieldname) for each date, for example I want to know how often the name "izla" is repeated in the table for each date but it could be also "IZLA" or "Izla", so i must find a way to group this data together as one and find count for the three of them. The problem is that if i try using uppercase or lowercase so that they are considered automatically the same I have the problem: when izla is converted to upper it becomes İZLA or on the other hand when IZLA is converted to lowercase it is displayed ızla. The big question is how can i group this data together? Maybe the problem comes from using nvarchar but i need the column type to be like that (can't change it).
When you group, you should use an Accent Insensitive collation. You can add this directly to your group by clause. The following is an example: ``` Declare @Temp Table(Data nvarchar(100)) Insert Into @Temp Values(N'izla') Insert Into @Temp Values(N'İZLA') Insert Into @Temp Values(N'IZLA') Insert Into @Temp Values(N'Izla') Select Data, Count(*) From @Temp Group By Data Select Data Collate Latin1_General_CI_AI, Count(*) From @Temp Group By Data Collate Latin1_General_CI_AI ``` When you run this example, you will see that the first query creates two rows (with count 3 and count 1). The second example uses an accent insensitve collation for the grouping, so all 4 items are grouped together. I used **Latin1\_General\_CI\_AI** in my example. I suggest you examine the collation of the column you are using and then use a collation that most closely matches by changing the AS on the end to AI.
Try replacing ı and such with english equivalent after lowercasing
Sql trying to change case letter and group similar nvarchar values
[ "", "sql", "nvarchar", "" ]
I have a custom collection let's say ``` MyClass { prop Name; prop Address; prop isRequired; } MyCustomCollection : List<MyClass> { } ``` When I do ``` MyCustomCollection collection = new MyCustomCollection (); datagridView.DataSource = collection; ``` The datagridview is populated with three columns Name, address , isRequired.. I want to hide isRequired property from the datagrid view how can i do that... and also I want to use it as a property to check in another classes...
Or you can set the visible property of the column to false. For each set of business data I want to display, I keep track of the # of leftmost-columns I want hidden because they hold PK values. Here's a sample: ``` dgvDisplaySet.DataSource = _setSource gridColsToHide = _displaySet.hidePKFields For gridCol = 0 To dgvDisplaySet.Columns.Count - 1 dgvDisplaySet.Columns(gridCol).Visible = (gridCol >= gridColsToHide) Next ```
I used [Browsable(false)] MyClass { prop Name; prop Address; [Browsable(false)] prop isRequired; } to hide the column
How to hide a property of custom collection while using DataGridView DataSource?
[ "", "c#", ".net", "datagridview", "" ]
I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's [this post about using WMI](https://stackoverflow.com/questions/1081871/how-to-find-available-com-ports), but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET. I currently know of two other approaches: 1. Reading the information in the `HARDWARE\\DEVICEMAP\\SERIALCOMM` registry key. This looks like a great option, but is it **robust**? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports. 2. Tryint to call `CreateFile` on `COMN` with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method. Any other methods/ideas/experience to share? **Edit:** by the way, here's a simple Python implementation of reading the port names from registry: ``` import _winreg as winreg import itertools def enumerate_serial_ports(): """ Uses the Win32 registry to return a iterator of serial (COM) ports existing on this computer. """ path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) except WindowsError: raise IterationError for i in itertools.count(): try: val = winreg.EnumValue(key, i) yield (str(val[1]), str(val[0])) except EnvironmentError: break ```
Several options are available: 1. Call [QueryDosDevice](http://msdn.microsoft.com/en-us/library/aa365461(VS.85).aspx) with a NULL lpDeviceName to list all DOS devices. Then use CreateFile and [GetCommConfig](http://msdn.microsoft.com/en-us/library/aa363256(VS.85).aspx) with each device name in turn to figure out whether it's a serial port. 2. Call [SetupDiGetClassDevs](http://msdn.microsoft.com/en-us/library/ms792959.aspx) with a ClassGuid of GUID\_DEVINTERFACE\_COMPORT. 3. [WMI is also available to C/C++ programs](http://msdn.microsoft.com/en-us/library/aa389762(VS.85).aspx). There's some conversation on the [win32 newsgroup](http://groups.google.com/group/microsoft.public.win32.programmer.kernel/browse_thread/thread/9c1bb578bd9cb309) and a CodeProject, er, [project](http://www.codeproject.com/KB/system/setupdi.aspx).
Using pySerial with Python: ``` import serial.tools.list_ports ports = list(serial.tools.list_ports.comports()) for p in ports: print p ```
Listing serial (COM) ports on Windows?
[ "", "python", "c", "windows", "winapi", "serial-port", "" ]
I'm writing a unit test for file uploading feature of my web application. I mocked a test file, and save it in the "Test files" subdirectory of the directory that my test project resident in. As I don't want to hard coded the file path. How can I know the directory of my project by code? I used @"..\Test files\test1.xml", but it doesn't work. Thanks in advance!
Remember that your unit test project will be running relative from it's own bin directory, and not from the project directory. You can get the path to that bin directory using: ``` Assembly.GetExecutingAssembly().Location ``` However, the easiest thing to do is set your test files and folders to be copied to the output directory. Just click on your file in the solution explorer, hit F4, and change "Copy to Output Directory" to "Copy always" or "Copy if newer". The folder structure will automatically also be copied. Then your relative path statements will work correctly.
I beleive HttpContext.Current.Request.PhysicalApplicationPath will give you the physical directory of your application root. I would store the name of the sub directory in the web.config file, and then use System.IO.Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath,) to build the full path to the sub directory.
Visual studio project directory
[ "", "c#", "unit-testing", "" ]
A book as the following example and explains that you won't see the line "DoWork has ended": > ...because the thread was aborted > while DoWork was executing > Thread.Sleep That makes sense, but what is **odd** is that if you change the first sleep to 6000 to give the DoWork thread time to get done with its 5000 sleep, then the DoWork thread *will* print "DoWork has ended" but this is after the DoWork thread has been *aborted*, **so if the DoWork thread has been aborted at that point, what thread is the line that prints "DoWork has ended" running in?** (it seems to be running at that point in the *aborted* thread) ``` using System; using System.Threading; namespace TestThreading838 { class Program { static void Main(string[] args) { Console.WriteLine("MAIN THREAD started."); Thread DoWorkThread = new Thread(new ThreadStart(DoWork)); DoWorkThread.Start(); Thread.Sleep(1000); //if you change this to 6000 you see "DoWork has ended." DoWorkThread.Abort(); Console.WriteLine("MAIN THREAD ending..."); Thread.Sleep(6000); Console.WriteLine("MAIN THREAD ended."); Console.ReadLine(); } public static void DoWork() { Console.WriteLine("DoWork is running."); try { Thread.Sleep(5000); } catch (ThreadAbortException ex) { Console.WriteLine("DoWork was aborted."); } finally { Console.WriteLine("DoWork cleaning up after being aborted."); } Console.WriteLine("DoWork has ended."); //never shown } } } ```
If you change the first sleep to 6000, then the secondary thread finishes everything it needs to do before you abort it - it's not really aborted, because you've just called `Abort` on a thread which was already dead. Notice that "DoWork was aborted" won't be printed... Try printing out `DoWorkThread.ThreadState` before you call `Abort` - I'm pretty sure you'll see it's "Stopped".
"DoWork has ended" is running on the second Thread (DoWorkThread). ``` DoWorkThread.Start(); //Run the thread Thread.Sleep(6000); //Let the thread run for 6sec so "DoWork has ended" will be displayed DoWorkThread.Abort(); ```
How can you abort a thread and have code still executing in that thread?
[ "", "c#", "multithreading", "" ]
I want a version of `str_replace()` that only replaces the first occurrence of `$search` in the `$subject`. Is there an easy solution to this, or do I need a hacky solution?
Can be done with [preg\_replace](http://www.php.net/preg_replace): ``` function str_replace_first($search, $replace, $subject) { $search = '/'.preg_quote($search, '/').'/'; return preg_replace($search, $replace, $subject, 1); } echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); // outputs '123def abcdef abcdef' ``` The magic is in the optional fourth parameter [Limit]. From the documentation: > [Limit] - The maximum possible > replacements for each pattern in each > subject string. Defaults to -1 (no > limit). Though, see [zombat's answer](https://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on-the-first-match#1252710) for a more efficient method (roughly, 3-4x faster).
There's no version of it, but the solution isn't hacky at all. ``` $pos = strpos($haystack, $needle); if ($pos !== false) { $newstring = substr_replace($haystack, $replace, $pos, strlen($needle)); } ``` Pretty easy, and saves the performance penalty of regular expressions. Bonus: If you want to replace *last* occurrence, just use `strrpos` in place of `strpos`.
Using str_replace so that it only acts on the first match?
[ "", "php", "string", "" ]
I have an *editable* JComboBox where I want to take some action whenever the text is changed, either by typing or selection. In this case, the text is a pattern and I want to verify that the pattern is valid and show the matches that result in some test data. Having done the obvious, attach an ActionHandler, I have found that, for typing, the event seems to fire unreliably, at best (selection is fine). And when it *does* fire as a result of typing, the text retrieved (using getEditor().getItem(), since getSelectedItem() only gets the text when it was selected from the list) seems to be the text as it was when the last event was fired - that is, it's always missing the character was typed immediately before the action event was fired. I was expecting the action event to fire after some short delay (500ms to 1 second), but it seems immediately fired upon keying (if it is fired at all). The only workable alternative I can think of is to simply start a 1 second timer on focus-gained, killing it on focus-lost and doing the work as the timer action if the content is different from last time. Any thoughts or suggestions? The code snippets are not particularly interesting: ``` find.addActionListener(this); ... public void actionPerformed(ActionEvent evt) { System.out.println("Find: "+find.getEditor().getItem()); } ```
The action listener is typically only fired when you hit enter, or move focus away from the editor of the combobox. The correct way to intercept individual changes to the editor is to register a document listener: ``` final JTextComponent tc = (JTextComponent) combo.getEditor().getEditorComponent(); tc.getDocument().addDocumentListener(this); ``` The [DocumentListener interface](http://java.sun.com/docs/books/tutorial/uiswing/events/documentlistener.html) has methods that are called whenever the Document backing the editor is modified (insertUpdate, removeUpdate, changeUpdate). You can also use an anonymous class for finer-grained control of where events are coming from: ``` final JTextComponent tcA = (JTextComponent) comboA.getEditor().getEditorComponent(); tcA.getDocument().addDocumentListener(new DocumentListener() { ... code that uses comboA ... }); final JTextComponent tcB = (JTextComponent) comboB.getEditor().getEditorComponent(); tcB.getDocument().addDocumentListener(new DocumentListener() { ... code that uses comboB ... }); ```
You can use somthing like this: ``` JComboBox cbListText = new JComboBox(); cbListText.addItem("1"); cbListText.addItem("2"); cbListText.setEditable(true); final JTextField tfListText = (JTextField) cbListText.getEditor().getEditorComponent(); tfListText.addCaretListener(new CaretListener() { private String lastText; @Override public void caretUpdate(CaretEvent e) { String text = tfListText.getText(); if (!text.equals(lastText)) { lastText = text; // HERE YOU CAN WRITE YOUR CODE } } }); ```
How can I know when the text of an editable JComboBox has been changed?
[ "", "java", "swing", "jcombobox", "" ]
all threads have its priority,so what is the integer value for main thread?
This code shows you the priority of the main thread: ``` public class Main { public static void main( String [] args ) { System.out.println( Thread.currentThread().getPriority() ); } } ``` The output, and the answer to your question, is **5**.
If you still have any doubts, have a look at the JDK's API docs: From <http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#NORM_PRIORITY>: > `NORM_PRIORITY` > > `public static final int NORM_PRIORITY` > >     The default priority that is assigned to a thread. From <http://java.sun.com/j2se/1.5.0/docs/api/constant-values.html#java.lang.Thread.NORM_PRIORITY>: > `static final int NORM_PRIORITY 5`
what is the value for main thread priority?
[ "", "java", "multithreading", "" ]
I'm not much of a frontend guy, just learning jQuery, so any help is appreciated. What's the easiest, most stable jQuery zoom plugin? I have a regular size product image and a detailed image. I need to be able to zoom in somehow. Which would you recommend?
[jqzoom](http://www.mind-projects.it/projects/jqzoom/) [fancyzoom](http://www.dfc-e.com/metiers/multimedia/opensource/jquery-fancyzoom/)
See also: [Anything Zoomer](http://css-tricks.com/examples/AnythingZoomer/index.html) [Magnify](http://www.jnathanson.com/index.cfm?page=jquery/magnify/magnify#examples) [Mag View](http://www.uize.com/examples/mag-view.html) [Whole bunch of them](http://www.downloadjavascripts.com/Zoom%20And%20Magnifiers.aspx)
What's the best jQuery product zoom plugin?
[ "", "javascript", "jquery", "e-commerce", "zooming", "" ]
[SOLVED] So I decided to try and create a sorted doubly linked skip list... I'm pretty sure I have a good grasp of how it works. When you insert x the program searches the base list for the appropriate place to put x (since it is sorted), (conceptually) flips a coin, and if the "coin" lands on a then that element is added to the list above it(or a new list is created with element in it), linked to the element below it, and the coin is flipped again, etc. If the "coin" lands on b at anytime then the insertion is over. You must also have a -infinite stored in every list as the starting point so that it isn't possible to insert a value that is less than the starting point (meaning that it could never be found.) To search for x, you start at the "top-left" (highest list lowest value) and "move right" to the next element. If the value is less than x than you continue to the next element, etc. until you have "gone too far" and the value is greater than x. In this case you go back to the last element and move down a level, continuing this chain until you either find x or x is never found. To delete x you simply search x and delete it every time it comes up in the lists. For now, I'm simply going to make a skip list that stores numbers. I don't think there is anything in the STL that can assist me, so I will need to create a class List that holds an integer value and has member functions, search, delete, and insert. The problem I'm having is dealing with links. I'm pretty sure I could create a class to handle the "horizontal" links with a pointer to the previous element and the element in front, but I'm not sure how to deal with the "vertical" links (point to corresponding element in other list?) If any of my logic is flawed please tell me, but my main questions are: 1. How to deal with vertical links and whether my link idea is correct 2. Now that I read my class List idea I'm thinking that a List should hold a vector of integers rather than a single integer. In fact I'm pretty positive, but would just like some validation. 3. I'm assuming the coin flip would simply call int function where rand()%2 returns a value of 0 or 1 and if it's 0 then a the value "levels up" and if it's 0 then the insert is over. Is this incorrect? 4. How to store a value similar to -infinite? Edit: I've started writing some code and am considering how to handle the List constructor....I'm guessing that on its construction, the "-infinite" value should be stored in the vectorname[0] element and I can just call insert on it after its creation to put the x in the appropriate place.
1. Just store 2 pointers. One called above, and one called below in your node class. 2. Not sure what you mean. 3. According to [wikipedia](http://en.wikipedia.org/wiki/Skip_list) you can also do a geometric distribution. I'm not sure if the type of distribution matters for totally random access, but it obviously matters if you know your access pattern. 4. I am unsure of what you mean by this. You can represent something like that with floating point numbers.
<http://msdn.microsoft.com/en-us/library/ms379573(VS.80).aspx#datastructures20_4_topic4> <http://igoro.com/archive/skip-lists-are-fascinating/> The above skip lists are implemented in C#, but can work out a c++ implementation using that code.
Implementing Skip List in C++
[ "", "c++", "skip-lists", "" ]
Sometimes to make a variable/method/class name descriptive I need to make it longer. But I don't want to, I'd like to have short names that are easy to read. So I thought of a special addin to IDE like Visual Studio to be able to write short names for class, method, field but be able to attach long names. If you need to - you can make it all long or you can make single name long. If you want to reduce it - use reduction, like two views of the same code. I`d like to know what others thinking about it? Do you think it is usefull? Would anybody use the kind of addin?
I never worry about long names. If a method name becomes too long, it may also indicate that the method does too much (unless it happens to include a really long word). On the other hand, I also try to avoid repeating myself. I would not have `Account.AccountId` for instance, but rather `Account.Id`. I also lean back on the namespace; if the namespace is clear about what domain I am in, I usually try to not repeat that in class- or member names. Bottom line; I can't see myself using such an addin.
Why not just use the standard XML commenting system built into Visual Studio. If you type /// above the Class/Method/variable etc, it creates the comment stub. These comments popup through Intelisense/Code Completion with extra info. This way you keep your naming conventions short and descriptive whilst commenting your code. You can run a process to then create documentation for your code using these comments. See: <http://msdn.microsoft.com/en-us/magazine/cc302121.aspx>
Reductions in programming
[ "", "c#", ".net", "vb.net", "ide", "" ]
Helllo! I'm trying to build a program that calculates the best score from a various amount of items with bruteforce. And I believe that the speed to calculate this can be improved on systems with multicore CPUs with the help of threading. Correct me if I'm wrong. But how do I achieve this? Here's a part of my code, and it does the job well (no threading). ``` private double _bestScore = 0.0; private void BruteForce() { foreach (Stats head in _heads) foreach (Stats chest in _chests) foreach (Stats leg in _legs) foreach (Stats feet in _feets) { int stamina = head.sta + chest.sta + leg.sta + feet.sta; int power = head.power + chest.power + leg.power + feet.power; int armor = head.armor + chest.armor + leg.armor + feet.armor; int hit = head.hit + chest.hit + leg.hit + feet.hit; double total = stamina * _scaleSta + power * _scalePower + armor * _scaleArmor; if (total > _bestScore && hit >= 100) { _bestScore = total; // Store best setup for output when done with bruteforce _bestHead = head; _bestChest = chest; _bestLeg = leg; _bestFeet = feet; } } } ``` So, is there anyway to improve this with threading? Edit: Fixed typo and updated to include another stat, hit. Hit must reach 100 to be a possible part of "best score". This does so I can't check each individual slot first to try and find the best gear. Hit is a very important stat up to 100, but every point after 100 is useless. Also, this part of my code has a lot more of foreach-loops (28 instead of 4). So number of iterations are a LOT. However, each list (\_heads, \_chests etc) usually contains a maximum of 2 items.
If you want the simple way of adding multithreading, look into the [Parallel Extensions for .NET](http://blogs.msdn.com/pfxteam/). For performance reasons, you will only want to put a Parallel.For() call on the outermost loop.
I'm pretty sure this will do it, not having any test data or a compiler to hand makes me not 100% confident: ``` private void BestItems() { _bestHead = GetBestItem(_heads); _bestChest = GetBestItem(_chests); _bestLeg = GetBestItem(_legs); _bestFeet = GetBestItem(_feets); } private Stats GetBestItem(List<Stats> items) { double best = 0.0; Stats result = null; foreach stats item in items { double total = item.stamina * _scaleSta + item.power * _scalePower + item.armor * _scaleArmor; if (total > best) { result = item; } } return result; } ``` **Edit:** Steps: 1. Create a list for each slot in order of most important stat (smallest first) 2. Loop through using some kind of weighting to find the smallest values of hit that satisfy your hit rating. (yuo will need this per slot for my next step) 3. For each slot pick item with best stats that meets that slots min-hit rating. you will need a lot of loops one after the other, but its better than 2^28 i think :p **Edit2:** Again, still no compiler here... but this might work. You will end up with a bucket load of threads though... For thread joining and waiting [see here (msdn)](http://msdn.microsoft.com/en-us/library/system.threading.aspx) (look at mutex, monitor, ManualResetEvent, AutoResetEvent) ``` private void BruteForce() { var threads = new List<Thread>; foreach (Stats head in _heads) foreach (Stats chest in _chests) foreach (Stats leg in _legs) foreach (Stats feet in _feets) { if (threads.Count <= 2) thread worker = new thread(addressof Process, new object() {head, chest, leg, feet, ...}); worker.start(); threads.add(worker); } foreach (Thread t in threads) t.join(); //this might not be the best as it might make the main thread wait for each thread one after the other, not when all finished. A manual/auto reset is probably better here. } private void Process(params...) { int stamina = head.sta + chest.sta + leg.sta + feet.sta; int power = head.power + chest.power + leg.power + feet.power; int armor = head.armor + chest.armor + leg.armor + feet.armor; int hit = head.hit + chest.hit + leg.hit + feet.hit; double total = stamina * _scaleSta + power * _scalePower + armor * _scaleArmor; lock _bestscore { if (total > _bestScore && hit >= 100) { _bestScore = total; // Store best setup for output when done with bruteforce _bestHead = head; _bestChest = chest; _bestLeg = leg; _bestFeet = feet; } } } ``` **EDIT 4:** Guess who still doesnt have a compiler near him? Something along the lines of this should make sure you only have 2 threads alive at any point. ``` var threads = new Dictionary<Guid, Thread>; private void BruteForce() { foreach (Stats head in _heads) foreach (Stats chest in _chests) foreach (Stats leg in _legs) foreach (Stats feet in _feets) { while (threads.Count >= 2) {} //im sure thread.join or equivelent can do this instead of a nasty loop :p var guid = Guid.NewGuid(); thread worker = new thread(addressof Process, new object() {guid, head, chest, leg, feet, ...}); worker.start(); threads.add(guid, worker); } foreach (Thread t in threads) t.join(); //this might not be the best as it might make the main thread wait for each thread one after the other, not when all finished. A manual/auto reset is probably better here. } private void Process(params...) { int stamina = head.sta + chest.sta + leg.sta + feet.sta; int power = head.power + chest.power + leg.power + feet.power; int armor = head.armor + chest.armor + leg.armor + feet.armor; int hit = head.hit + chest.hit + leg.hit + feet.hit; double total = stamina * _scaleSta + power * _scalePower + armor * _scaleArmor; lock _bestscore { if (total > _bestScore && hit >= 100) { _bestScore = total; // Store best setup for output when done with bruteforce _bestHead = head; _bestChest = chest; _bestLeg = leg; _bestFeet = feet; } } _threads.remove(guid) } ```
Threading nested foreach-loops?
[ "", "c#", "multithreading", "foreach", "" ]
Very simple question but all the answer I read over the web doesn't apply. I try to do an update on a ASP.NET Gridview but when I click on update, I get this error: Incorrect Syntax near 'nvarchar'. The scalar variable @intID must be declare. Here is my datasource. I guess the problem come from here but I can't see where... ``` <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:connexionDev %>" DeleteCommand="DELETE FROM [tbl_Bug] WHERE intID = @intID" SelectCommand="SELECT [intID],[strTitre],[strDescription],[intStatus_FK],[intType_FK],[intSeriousness_FK] FROM [tbl_Bug]" UpdateCommand="UPDATE [tbl_Bug] SET [strTitre] = @strTitre ,[strDescription] = @strDescription ,[intStatus_FK] = @intStatus_FK ,[intType_FK] = @intType_FK ,[intSeriousness_FK] = @intSeriousness_FK WHERE [intID] = @intID"> <DeleteParameters> <asp:Parameter Name="intID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="intID" Type="Int32" /> <asp:Parameter Name="strTitre" Type="String" /> <asp:Parameter Name="strDescription" Type="String" /> <asp:Parameter Name="intStatus_FK" Type="Int32" /> <asp:Parameter Name="intType_FK" Type="Int32" /> <asp:Parameter Name="intSeriousness_FK" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource> ``` Thanks for your help in advance! EDIT - EDIT - EDIT Well, I wanted to use SQL Profiler but it seems that it's not in my version (SQL server 2008 Express) so I tried another sql profiler that is open source but I never understood how it worked and it was always crashing ... Is there any other way to know the query that are used so I can track my problem?
Hi everyone and thanks for your help My query was good, it was the binding in the `GridView` that was bad, for a very very simple detail This will work: `Text='<%# Bind("myValue") %>'` While this wont: `Text='<%# Bind("[myValue]") %>'` So watch out! :) Now everything is working! Thanks again!
In cases like this the answer is often to run SQL Profiler and see what SQL is being sent, it's often a mismatch in variable names or something equally simple once you see what being sent to your SQL Server.
Incorrect syntax near 'nvarchar' in update ASP.NET Gridview
[ "", "asp.net", "sql", "gridview", "" ]
It doesn't seem to do this by default, which is pretty shocking to me given all the other stuff they've set up to make development easy. Is there a way to enable this? If not, anybody know why it isn't supported?
This is an [open feature request](http://code.google.com/p/googleappengine/issues/detail?id=1787) on the App Engine Issue Tracker. You should vote on it there. FWIW, it does work with JSP as expected (they get invalidated and recompiled when you update them).
There is JRebel that can help you with this <http://englove.blogspot.com/2010/09/appengine-hot-deploy-on-mac.html> But using JRebel i had troubles with GWT in Development Mode. BUt, there is a simplier way to do it. You can have hot deploy of your server clases if you debug your application in Eclipse. Debug As -> Web Application That's all! :)
Does Google App Engine Java support Hot Deployment in Eclipse?
[ "", "java", "eclipse", "google-app-engine", "hotdeploy", "" ]
Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world? I know the concept has already been underlined but I did not find a simple answer to the previous question.
`virtual` means the method called will be chosen at run-time, depending on the dynamic type of the object. `static` means no object is necessary to call the method. How do you propose to do both in the same method?
Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth: <https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one> > “virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”
C# virtual static method
[ "", "c#", "generics", "static", "methods", "virtual", "" ]
I'm trying to create a regex to **recognize** [English numerals](http://en.wikipedia.org/wiki/Names_of_numbers_in_English), such as **one**, **nineteen**, **twenty**, **one hundred and twenty two**, *et cetera*, all the way to the millions. I want to **reuse** some parts of the regular expression, so the regex is being constructed by parts, like so: ``` // replace <TAG> with the content of the variable ONE_DIGIT = (?:one|two|three|four|five|six|seven|eight|nine) TEEN = (?:ten|eleven|twelve|(?:thir|for|fif|six|seven|eigh|nine)teen) TWO_DIGITS = (?:(?:twen|thir|for|fif|six|seven|eigh|nine)ty(?:\s+<ONE_DIGIT>)?|<TEEN>) // HUNDREDS, et cetera ``` I was wondering if anyone has already done the same (and would like to share), as these regexes are quite long and it's possible that they have something that they shouldn't, or something that I may be missing. Also, I want them to be as **efficient** as possible so I'm looking forward for any **optimization tips**. I'm using the Java regex engine, but any regex flavour is acceptable.
See Perl's [Lingua::EN::Words2Nums](http://search.cpan.org/perldoc/Lingua::EN::Words2Nums) and [Lingua::EN::FindNumber](http://search.cpan.org/perldoc/Lingua::EN::FindNumber). In particular, the [source code for `Lingua::EN::FindNumber`](http://cpansearch.perl.org/src/TMTM/Lingua-EN-FindNumber-1.2/lib/Lingua/EN/FindNumber.pm) contains: ``` # This is from Lingua::EN::Words2Nums, after being thrown through # Regex::PreSuf my $numbers = qr/((?:b(?:akers?dozen|illi(?:ard|on))|centillion|d(?:ecilli(?:ard|on)|ozen|u(?:o(?:decilli(?:ard|on)|vigintillion)|vigintillion))|e(?:ight(?:een|ieth|[yh])?|leven(?:ty(?:first|one))?|s)|f(?:i(?:ft(?:een|ieth|[yh])|rst|ve)|o(?:rt(?:ieth|y)|ur(?:t(?:ieth|[yh]))?))|g(?:oogol(?:plex)?|ross)|hundred|mi(?:l(?:ion|li(?:ard|on))|nus)|n(?:aught|egative|in(?:et(?:ieth|y)|t(?:een|[yh])|e)|o(?:nilli(?:ard|on)|ught|vem(?:dec|vigint)illion))|o(?:ct(?:illi(?:ard|on)|o(?:dec|vigint)illion)|ne)|qu(?:a(?:drilli(?:ard|on)|ttuor(?:decilli(?:ard|on)|vigintillion))|in(?:decilli(?:ard|on)|tilli(?:ard|on)|vigintillion))|s(?:core|e(?:cond|pt(?:en(?:dec|vigint)illion|illi(?:ard|on))|ven(?:t(?:ieth|y))?|x(?:decillion|tilli(?:ard|on)|vigintillion))|ix(?:t(?:ieth|y))?)|t(?:ee?n|h(?:ir(?:t(?:een|ieth|y)|d)|ousand|ree)|r(?:e(?:decilli(?:ard|on)|vigintillion)|i(?:gintillion|lli(?:ard|on)))|w(?:e(?:l(?:fth|ve)|nt(?:ieth|y))|o)|h)|un(?:decilli(?:ard|on)|vigintillion)|vigintillion|zero|s))/i; ``` subject to [Perl's Artistic License](http://dev.perl.org/licenses/artistic.html). You can use [Regex::PreSuf](http://search.cpan.org/perldoc/Regex::PreSuf) to automatically factor out common pre- and suffixes: ``` #!/usr/bin/perl use strict; use warnings; use Regex::PreSuf; my %singledigit = ( one => 1, two => 2, three => 3, four => 4, five => 5, six => 6, seven => 7, eight => 8, nine => 9, ); my $singledigit = presuf(keys %singledigit); print $singledigit, "\n"; my $text = "one two three four five six seven eight nine"; $text =~ s/($singledigit)/$singledigit{$1}/g; print $text, "\n"; ``` **Output:** ``` C:\Temp> cvb (?:eight|f(?:ive|our)|nine|one|s(?:even|ix)|t(?:hree|wo)) 1 2 3 4 5 6 7 8 9 ``` I am afraid it gets harder after this ;-)
Perl has a number of modules that produce optimized regexes (which mostly only use standard features, so should be usable in Java) using different techniques. You can see examples of Regexp::Assemble, Regexp::List, Regexp::Optimizer, and Regex::PreSuf output in <http://groups.google.com/group/perl.perl5.porters/msg/132877aee7542015>. Starting in perl 5.10, perl itself usually optimizes lists of `|`'d exact strings into a trie.
Scalable Regex for English Numerals
[ "", "java", "regex", "perl", "" ]
Can we write an argument constructor in a Servlet? If yes, how can you call?
> *Can we write an argument constructor in a Servlet?* Yes, you can but it is useless since the servlet container won't invoke it. The proper way to do it is to use the [`init()`](http://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#init--) method: ``` @Override public void init() throws ServletException { String foo = getInitParameter("foo"); String bar = getServletContext().getInitParameter("bar"); // ... } ``` In this example, [`getInitParameter("foo")`](http://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getInitParameter-java.lang.String-) returns the value of the `<init-param>` of the specific `<servlet>` entry in `web.xml`, and [`getServletContext().getInitParameter("bar")`](http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html#getInitParameter-java.lang.String-) returns the value of the independent `<context-param>` in `web.xml`.
The problem can be state more generically: > "According to the servlets (2.3) > specification, the servlets are > instantiated by the servlet engine by > invoking the no-arg constructor. How > can I initialize a servlet properly > given that correct initialization > depends on the > central/global/unique/application > configuration?" Actually, you can use serlvets with constructor and/or initialize them as you like. However, it requires a little bit of plumbing. Assuming you have a servlet with a constructor having arguments: ``` package org.gawi.example.servlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SampleServlet extends HttpServlet { private final String mMessage; public SampleServlet(String message) { mMessage = message; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.getWriter().write(mMessage); } } ``` The first thing you need is a unique servlet whithin your application, let's call it InitializationServlet, to create all the required instances. Those instances must then be exported in the servlet context to be retrieve by another servlet (explained later). The InitializationServlet may look like this: ``` package org.gawi.example.servlets; import javax.servlet.*; import javax.servlet.http.*; public class InitializationServlet extends HttpServlet { public void init() throws ServletException { SampleServlet servletA = new SampleServlet("this is servlet A"); SampleServlet servletB = new SampleServlet("this is servlet B"); SampleServlet servletC = new SampleServlet("this is servlet C"); getServletContext().setAttribute("servletA", servletA); getServletContext().setAttribute("servletB", servletB); getServletContext().setAttribute("servletC", servletC); } } ``` You see that only the `init()` method has been provided. This servlet is not servicing any HTTP request. Its only purpose is to store the servlet in the ServletContext. Note that you could have also use this servlet to load your application configuration. So this can act as the web-application entry point, like the `main(String[] args)` method of a program. This might remind you of the ContextLoaderServlet of SpringSource. The last piece is the DelegateServlet that will effectively be instantiated by the servlet container, only this servlet will forward all the pertinent method calls to the wrapped servlet instance: ``` package org.gawi.example.servlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DelegateHttpServlet extends HttpServlet { private static final String SERVLET_CONTEXT_KEY_INIT_PARAMETER = "servletContextKey"; private HttpServlet mServlet; public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); locateServlet(servletConfig); mServlet.init(servletConfig); } private void locateServlet(ServletConfig servletConfig) throws ServletException { String servletContextAttributeName = servletConfig.getInitParameter(SERVLET_CONTEXT_KEY_INIT_PARAMETER); if (servletContextAttributeName == null) { throw new ServletException("Unable to find init parameter '" + SERVLET_CONTEXT_KEY_INIT_PARAMETER + "'"); } Object object = servletConfig.getServletContext().getAttribute(servletContextAttributeName); if (object == null) { throw new ServletException("Unable to find " + servletContextAttributeName + " in servlet context."); } if (!(object instanceof HttpServlet)) { throw new ServletException("Object is not an instance of" + HttpServlet.class.getName() + ". Class is " + object.getClass().getName() + "."); } mServlet = (HttpServlet) object; } public void destroy() { mServlet.destroy(); } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { mServlet.service(req, res); } } ``` During its initialization, the DelegateServlet will look-up the target servlet in the servlet context using the `servletContextKey` servlet initial argument. The web.xml for such an application might look like that: ``` <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Example</display-name> <description>Example web showing handling of servlets w/ constructors.</description> <servlet> <servlet-name>Initialization</servlet-name> <servlet-class>org.gawi.example.servlets.InitializationServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>A</servlet-name> <servlet-class>org.gawi.example.servlets.DelegateHttpServlet</servlet-class> <init-param> <param-name>servletContextKey</param-name> <param-value>servletA</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet> <servlet-name>B</servlet-name> <servlet-class>org.gawi.example.servlets.DelegateHttpServlet</servlet-class> <init-param> <param-name>servletContextKey</param-name> <param-value>servletB</param-value> </init-param> <load-on-startup>3</load-on-startup> </servlet> <servlet> <servlet-name>C</servlet-name> <servlet-class>org.gawi.example.servlets.DelegateHttpServlet</servlet-class> <init-param> <param-name>servletContextKey</param-name> <param-value>servletC</param-value> </init-param> <load-on-startup>4</load-on-startup> </servlet> <servlet-mapping> <servlet-name>A</servlet-name> <url-pattern>/servlet/a</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>B</servlet-name> <url-pattern>/servlet/b</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>C</servlet-name> <url-pattern>/servlet/c</url-pattern> </servlet-mapping> <session-config> <session-timeout>5</session-timeout> </session-config> </web-app> ``` Be sure to load the InitializationServlet first, using a low `<load-on-startup>` value. The benefit of this approach is that `HttpServlet` objects can be handled like any other regular Java object or bean. Hence, it provides a better control over initialization: no more tricky stuff to do in the `init()` method, nor messy servlet init-arg handling.
How to initialize a Servlet during startup with parameters?
[ "", "java", "servlets", "initialization", "" ]
Is there a simple way via CSS or javascript or anything really to take a div and make it not inherit any styles? I'm creating a bookmarklet which adds a header to a website. It modifies the DOM as follows: ``` var bodycontent = document.body.innerHTML; document.body.innerHTML = ''; var header = document.createElement('div'); var bodycontainer = document.createElement('div'); header.setAttribute('id', 'newdiv-header'); bodycontainer.setAttribute('id','newdiv-bodycontainer'); header.innerHTML = "MY STUFF"; bodycontainer.innerHTML = bodycontent; document.body.appendChild(header); document.body.appendChild(bodycontainer); ``` so effectively what we end up with is this: ``` <html> <head> ...original head stuff... </head> <body> <div id="newdiv-header"> MY CONTENT </div> <div id="newdiv-bodycontainer"> ...original content of document.body.innerHTML... </div> </body> </html> ``` all styled appropriately so that everything is visible, etc. The problem is that the original page's stylesheet affect the look of my header. I'd use frames and/or iframes but this breaks on sites which implement framebusting. Thank you very much for any ideas!
Let me preface this by saying that all of the following is pure air-code :) What if you attacked it from the other direction? Instead of resetting all of the styles in your div, modify the existing stylesheet so that all of the selectors target children of #newdiv-bodycontainer. This site talks about the relevant API: <http://www.javascriptkit.com/domref/stylesheet.shtml> Edit: Iterating on this idea, I put together some test code to make sure it works. I've included it below. I also found the following site useful: <http://www.javascriptkit.com/dhtmltutors/externalcss2.shtml> **WARNING: This is not production code. It does not handle cross-browser incompatibilities (of which there are many), nor does it deal with compound selectors, nor does it deal with multiple stylesheets.** ``` for (var i = 0; i < document.styleSheets[0].cssRules.length; ++i) { var selector = document.styleSheets[0].cssRules[i].selectorText; var declaration = document.styleSheets[0].cssRules[i].style.cssText; document.styleSheets[0].deleteRule(i); document.styleSheets[0].insertRule('.test ' + selector + '{' + declaration + '}', i); alert(document.styleSheets[0].cssRules[i].selectorText); } ``` This is the HTML used to test it. It runs in Firefox and Chrome, but will require modifications to run in IE: ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" > <html> <head> <title>Test</title> <style type="text/css"> .test { background-color:red; border: black solid 1px; } </style> </head> <body> <div class="test" style="width: 10em;"> This is some text that is probably long enough to wrap. <div class="test test2">Test2</div> </div> <script language="javascript"> for (var i = 0; i < document.styleSheets[0].cssRules.length; ++i) { var selector = document.styleSheets[0].cssRules[i].selectorText; var declaration = document.styleSheets[0].cssRules[i].style.cssText; document.styleSheets[0].deleteRule(i); document.styleSheets[0].insertRule('.test ' + selector + '{' + declaration + '}', i); alert(document.styleSheets[0].cssRules[i].selectorText); } </script> </body> </html> ```
My only idea is to set every relevant CSS property to the default (or whatever you need). I don't think there's a way of preventing styles from being applied on a single div.
how can one "unstyle" a div html element?
[ "", "javascript", "html", "css", "stylesheet", "" ]
I have a table that records a history of child items linked to a parent, with two columns: * ParentId * ChildId Some example data looks like this: ParentId -- ChildId 001 -- 001 001 -- 001 001 -- 001 001 -- 002 001 -- 002 001 -- 002 001 -- 003 001 -- 003 001 -- 003 001 -- 003 001 -- 004 001 -- 004 001 -- 005 001 -- 005 001 -- 005 001 -- 005 I need to select all the rows with the highest value ChildId for a given ParentId. So in the above example, I need the query to return the following rows, given an input parameter of '@parentId = 001': 001 -- 005 001 -- 005 001 -- 005 001 -- 005 Thanks for any help!
This aught to do it: ``` SELECT * FROM MyTable WHERE parentId = '001' AND childId = (SELECT MAX(childId) FROM MyTable WHERE parentId = '001') ```
How about this? ``` SELECT ParentID, MAX(ChildID) AS ChildID FROM TableName GROUP BY ParentID ``` **Updated to edit missed requirement to return all rows:** ***Test Data*** ``` -- Populate Test Data CREATE TABLE #table ( ParentID varchar(3) NOT NULL, ChildID varchar(3) NOT NULL ) INSERT INTO #table VALUES ('001','001') INSERT INTO #table VALUES ('001','001') INSERT INTO #table VALUES ('001','001') INSERT INTO #table VALUES ('001','002') INSERT INTO #table VALUES ('001','002') INSERT INTO #table VALUES ('001','002') INSERT INTO #table VALUES ('001','003') INSERT INTO #table VALUES ('001','003') INSERT INTO #table VALUES ('001','003') INSERT INTO #table VALUES ('001','003') INSERT INTO #table VALUES ('001','004') INSERT INTO #table VALUES ('001','004') INSERT INTO #table VALUES ('001','005') INSERT INTO #table VALUES ('001','005') INSERT INTO #table VALUES ('001','005') INSERT INTO #table VALUES ('001','005') ``` ***Results*** ``` -- Return Results DECLARE @ParentID varchar(8) SET @ParentID = '001' SELECT T1.ParentID, T1.ChildID FROM #table T1 JOIN ( SELECT Q1.ParentID, MAX(Q1.ChildID) AS ChildID FROM #table Q1 GROUP BY ParentID ) ParentChildMax ON ParentChildMax.ParentID = T1.ParentID AND ParentChildMax.ChildID = T1.ChildID WHERE T1.ParentID = @ParentID ``` Note: The performance of this solution is identical to the accepted solution (according to SQL Server profiler) using the following statement in the WHERE clause. But I like my solution better as it seems cleaner to me and can be easily extended to include other ParentIDs is required. (For example, reporting purposes.) ``` (SELECT MAX(childId) FROM #table WHERE parentId = @ParentID) ```
How do I write this SQL query?
[ "", "sql", "" ]
I'm looking for a free cross-platform installer generator that is fully Java-driven (meaning workflow and plugins are written in Java). Ideally the installer should download the JRE on-demand instead of bundling it directly into the installer. Does something like this already exist? Please note that InstallAnywhere no longer offers a free edition.
* [IzPack](http://izpack.org/) * [Antigen](http://antigen.sourceforge.net/) * [Launch4J](http://launch4j.sourceforge.net) * [Antstaller](http://antinstaller.sourceforge.net) * [Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/introduction.html) * [Lift Off Java Installer](http://liftoff.sourceforge.net/index.en.html) * [JSmooth](http://jsmooth.sourceforge.net/) * [VAInstall](http://vainstall.sourceforge.net/) * [Packlet](http://packlet.sourceforge.net/) * [Mini Installer](http://www.yagga.net/java/miniinstaller/index.shtml)
[lzPack](http://izpack.org/) is a good one
Installer generator written in Java?
[ "", "java", "installation", "cross-platform", "" ]
Is there a reason to prefer using [map()](https://docs.python.org/3.8/library/functions.html#map) over list comprehension or vice versa? Is either of them generally more efficient or considered generally more Pythonic than the other?
*map* may be microscopically faster in some cases (when you're *not* making a lambda for the purpose, but using the same function in map and a [list comprehension](https://en.wikipedia.org/wiki/List_comprehension#Python)). List comprehensions may be faster in other cases and most (not all) Pythonistas consider them more direct and clearer. An example of the tiny speed advantage of *map* when using exactly the same function: ``` $ python -m timeit -s'xs=range(10)' 'map(hex, xs)' 100000 loops, best of 3: 4.86 usec per loop $ python -m timeit -s'xs=range(10)' '[hex(x) for x in xs]' 100000 loops, best of 3: 5.58 usec per loop ``` An example of how performance comparison gets completely reversed when map needs a lambda: ``` $ python -m timeit -s'xs=range(10)' 'map(lambda x: x+2, xs)' 100000 loops, best of 3: 4.24 usec per loop $ python -m timeit -s'xs=range(10)' '[x+2 for x in xs]' 100000 loops, best of 3: 2.32 usec per loop ```
**Cases** * **Common case**: Almost always, you will want to use a list comprehension in *python* because it will be more obvious what you're doing to novice programmers reading your code. (This does not apply to other languages, where other idioms may apply.) It will even be more obvious what you're doing to python programmers, since list comprehensions are the de-facto standard in python for iteration; they are *expected*. * **Less-common case**: However if you *already have a function defined*, it is often reasonable to use `map`, though it is considered 'unpythonic'. For example, `map(sum, myLists)` is more elegant/terse than `[sum(x) for x in myLists]`. You gain the elegance of not having to make up a dummy variable (e.g. `sum(x) for x...` or `sum(_) for _...` or `sum(readableName) for readableName...`) which you have to type twice, just to iterate. The same argument holds for `filter` and `reduce` and anything from the `itertools` module: if you already have a function handy, you could go ahead and do some functional programming. This gains readability in some situations, and loses it in others (e.g. novice programmers, multiple arguments)... but the readability of your code highly depends on your comments anyway. * **Almost never**: You may want to use the `map` function as a pure abstract function while doing functional programming, where you're mapping `map`, or currying `map`, or otherwise benefit from talking about `map` as a function. In Haskell for example, a functor interface called `fmap` generalizes mapping over any data structure. This is very uncommon in python because the python grammar compels you to use generator-style to talk about iteration; you can't generalize it easily. (This is sometimes good and sometimes bad.) You can probably come up with rare python examples where `map(f, *lists)` is a reasonable thing to do. The closest example I can come up with would be `sumEach = partial(map,sum)`, which is a one-liner that is very roughly equivalent to: ``` def sumEach(myLists): return [sum(_) for _ in myLists] ``` * **Just using a `for`-loop**: You can also of course just use a for-loop. While not as elegant from a functional-programming viewpoint, sometimes non-local variables make code clearer in imperative programming languages such as python, because people are very used to reading code that way. For-loops are also, generally, the most efficient when you are merely doing any complex operation that is not building a list like list-comprehensions and map are optimized for (e.g. summing, or making a tree, etc.) -- at least efficient in terms of memory (not necessarily in terms of time, where I'd expect at worst a constant factor, barring some rare pathological garbage-collection hiccuping). **"Pythonism"** I dislike the word "pythonic" because I don't find that pythonic is always elegant in my eyes. Nevertheless, `map` and `filter` and similar functions (like the very useful `itertools` module) are probably considered unpythonic in terms of style. **Laziness** In terms of efficiency, like most functional programming constructs, **MAP CAN BE LAZY**, and in fact is lazy in python. That means you can do this (in *python3*) and your computer will not run out of memory and lose all your unsaved data: ``` >>> map(str, range(10**100)) <map object at 0x2201d50> ``` Try doing that with a list comprehension: ``` >>> [str(n) for n in range(10**100)] # DO NOT TRY THIS AT HOME OR YOU WILL BE SAD # ``` Do note that list comprehensions are also inherently lazy, but *python has chosen to implement them as non-lazy*. Nevertheless, python does support lazy list comprehensions in the form of generator expressions, as follows: ``` >>> (str(n) for n in range(10**100)) <generator object <genexpr> at 0xacbdef> ``` You can basically think of the `[...]` syntax as passing in a generator expression to the list constructor, like `list(x for x in range(5))`. **Brief contrived example** ``` from operator import neg print({x:x**2 for x in map(neg,range(5))}) print({x:x**2 for x in [-y for y in range(5)]}) print({x:x**2 for x in (-y for y in range(5))}) ``` List comprehensions are non-lazy, so may require more memory (unless you use generator comprehensions). The square brackets `[...]` often make things obvious, especially when in a mess of parentheses. On the other hand, sometimes you end up being verbose like typing `[x for x in...`. As long as you keep your iterator variables short, list comprehensions are usually clearer if you don't indent your code. But you could always indent your code. ``` print( {x:x**2 for x in (-y for y in range(5))} ) ``` or break things up: ``` rangeNeg5 = (-y for y in range(5)) print( {x:x**2 for x in rangeNeg5} ) ``` **Efficiency comparison for python3** `map` is now lazy: ``` % python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=map(f,xs)' 1000000 loops, best of 3: 0.336 usec per loop ^^^^^^^^^ ``` *Therefore if you will not be using all your data, or do not know ahead of time how much data you need, `map` in python3 (and generator expressions in python2 or python3) will avoid calculating their values until the last moment necessary. Usually this will usually outweigh any overhead from using `map`. The downside is that this is very limited in python as opposed to most functional languages: you only get this benefit if you access your data left-to-right "in order", because python generator expressions can only be evaluated the order `x[0], x[1], x[2], ...`.* However let's say that we have a pre-made function `f` we'd like to `map`, and we ignore the laziness of `map` by immediately forcing evaluation with `list(...)`. We get some very interesting results: ``` % python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=list(map(f,xs))' 10000 loops, best of 3: 165/124/135 usec per loop ^^^^^^^^^^^^^^^ for list(<map object>) % python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=[f(x) for x in xs]' 10000 loops, best of 3: 181/118/123 usec per loop ^^^^^^^^^^^^^^^^^^ for list(<generator>), probably optimized % python3 -mtimeit -s 'xs=range(1000)' 'f=lambda x:x' 'z=list(f(x) for x in xs)' 1000 loops, best of 3: 215/150/150 usec per loop ^^^^^^^^^^^^^^^^^^^^^^ for list(<generator>) ``` In results are in the form AAA/BBB/CCC where A was performed with on a circa-2010 Intel workstation with python 3.?.?, and B and C were performed with a circa-2013 AMD workstation with python 3.2.1, with extremely different hardware. The result seems to be that map and list comprehensions are comparable in performance, which is most strongly affected by other random factors. The only thing we can tell seems to be that, oddly, while we expect list comprehensions `[...]` to perform better than generator expressions `(...)`, `map` is ALSO more efficient that generator expressions (again assuming that all values are evaluated/used). It is important to realize that these tests assume a very simple function (the identity function); however this is fine because if the function were complicated, then performance overhead would be negligible compared to other factors in the program. (It may still be interesting to test with other simple things like `f=lambda x:x+x`) If you're skilled at reading python assembly, you can use the `dis` module to see if that's actually what's going on behind the scenes: ``` >>> listComp = compile('[f(x) for x in xs]', 'listComp', 'eval') >>> dis.dis(listComp) 1 0 LOAD_CONST 0 (<code object <listcomp> at 0x2511a48, file "listComp", line 1>) 3 MAKE_FUNCTION 0 6 LOAD_NAME 0 (xs) 9 GET_ITER 10 CALL_FUNCTION 1 13 RETURN_VALUE >>> listComp.co_consts (<code object <listcomp> at 0x2511a48, file "listComp", line 1>,) >>> dis.dis(listComp.co_consts[0]) 1 0 BUILD_LIST 0 3 LOAD_FAST 0 (.0) >> 6 FOR_ITER 18 (to 27) 9 STORE_FAST 1 (x) 12 LOAD_GLOBAL 0 (f) 15 LOAD_FAST 1 (x) 18 CALL_FUNCTION 1 21 LIST_APPEND 2 24 JUMP_ABSOLUTE 6 >> 27 RETURN_VALUE ``` ``` >>> listComp2 = compile('list(f(x) for x in xs)', 'listComp2', 'eval') >>> dis.dis(listComp2) 1 0 LOAD_NAME 0 (list) 3 LOAD_CONST 0 (<code object <genexpr> at 0x255bc68, file "listComp2", line 1>) 6 MAKE_FUNCTION 0 9 LOAD_NAME 1 (xs) 12 GET_ITER 13 CALL_FUNCTION 1 16 CALL_FUNCTION 1 19 RETURN_VALUE >>> listComp2.co_consts (<code object <genexpr> at 0x255bc68, file "listComp2", line 1>,) >>> dis.dis(listComp2.co_consts[0]) 1 0 LOAD_FAST 0 (.0) >> 3 FOR_ITER 17 (to 23) 6 STORE_FAST 1 (x) 9 LOAD_GLOBAL 0 (f) 12 LOAD_FAST 1 (x) 15 CALL_FUNCTION 1 18 YIELD_VALUE 19 POP_TOP 20 JUMP_ABSOLUTE 3 >> 23 LOAD_CONST 0 (None) 26 RETURN_VALUE ``` ``` >>> evalledMap = compile('list(map(f,xs))', 'evalledMap', 'eval') >>> dis.dis(evalledMap) 1 0 LOAD_NAME 0 (list) 3 LOAD_NAME 1 (map) 6 LOAD_NAME 2 (f) 9 LOAD_NAME 3 (xs) 12 CALL_FUNCTION 2 15 CALL_FUNCTION 1 18 RETURN_VALUE ``` It seems it is better to use `[...]` syntax than `list(...)`. Sadly the `map` class is a bit opaque to disassembly, but we can make due with our speed test.
List comprehension vs map
[ "", "python", "list-comprehension", "map-function", "" ]
I can see that almost all modern APIs are developed in the C language. There are reasons for that: processing speed, low level language, cross platform and so on. Nowadays, I program in C++ because of its Object Orientation, the use of string, the STL but, mainly because it is a better C. However when my C++ programs need to interact with C APIs I really get upset when I need to convert char[] types to C++ strings, then operate on these strings using its powerful methods, and finally convert from theses strings to char[] again (because the API needs to receive char[]). If I repeat these operations for millions of records the processing times are higher because of the conversion task. For that simple reason, I feel that char[] is an obstacle in the moment to assume the C++ as a better c. I would like to know if you feel the same, if not (I hope so!) I really would like to know which is the best way for C++ to coexist with char[] types without doing those awful conversions. Thanks for your attention.
The C++ string class has a lot of problems, and yes, what you're describing is one of them. More specifically, there is no way to do string processing without creating a *copy* of the string, which may be expensive. And because virtually all string processing algorithms are implemented as class members, they can *only* be used on the string class. A solution you might want to experiment with is the combination of Boost.Range and Boost.StringAlgo. Range allows you to create sequences out of a pair of iterators. They don't take ownership of the data, so they don't copy the string. they just point to the beginning and end of your char\* string. And Boost.StringAlgo implements all the common string operations as non-member functions, that can be applied to *any* sequence of characters. Such as, for example, a Boost range. The combination of these two libraries pretty much solve the problem. They let you avoid having to copy your strings to process them. Another solution might be to store your string data as `std::string`'s *all the time*. When you need to pass a `char*` to some API functoin, simply pass it the address of the first character. (&str[0]). The problem with this second approach is that std::string doesn't guarantee that its string buffer is null-terminated, so you either have to rely on implementation details, or manually add a null byte as *part of* the string.
If you use `std::vector<char>` instead of `std::string`, the underlying storage will be a C array that can be accessed with `&someVec[0]`. However, you do lose a lot of `std::string` conveniences such as `operator+`. That said, I'd suggest just avoiding C APIs that mutate strings as much as possible. If you need to pass an immutable string to a C function, you can use `c_str()`, which is fast and non-copying on most `std::string` implementations.
char[] (c lang) to string (c++ lang) conversion
[ "", "c++", "c", "string", "" ]
In a desktop application, I need to store a 'database' of patient names with simple information, which can later be searched through. I'd expect on average around 1,000 patients total. Each patient will have to be linked to test results as well, although these can/will be stored seperately from the patients themselves. **Is a database the best solution for this, or overkill?** In general, we'll only be searching based on a patient's first/last name, or ID numbers. All data will be stored with the application, and not shared outside of it. Any suggestions on the best method for keeping all such data organized? The method for storing the separate test data is what seems to stump me when not using databases, while keeping it linked to the patient. Off the top of my head, given a `List<Patient>`, I can imagine several LINQ commands to make searching a breeze, although with a list of 1,000 - 10,000 patients, I'm unsure if there's any performance concerns.
**Use a database.** Mainly because what you expect and what you get (especially over the long term) tend be two totally different things.
This is completely unrelated to your question on a technical level, but are you doing this for a company in the United States? What kind of patient data are you storing? Have you looked into [HIPAA](http://www.hhs.gov/ocr/privacy/hipaa/understanding/index.html) requirements and checked to see if you're a [covered entity](http://www.cms.hhs.gov/HIPAAGenInfo/06_AreYouaCoveredEntity.asp)? Be sure that you're complying with all legal regulations and requirements!
Methods for storing searchable data in C#
[ "", "c#", "database", "data-structures", "storage", "" ]
I'm in the process of internationalising some JSF files so am externalising strings (and the concatenation of strings using placeholders). I have very little experience with JSF (today and yesterday) so excuse me if there is an obviuos answer to my question! I have been using the h:outputFormat tag (and the f:param tag) successfully for simple placeholders but now I'm looking to replace a placeholder with a commandLink component. i.e. ``` <h:outputFormat value="#{adminMsgs.scheduleUpdateLink} "> <h:commandLink value="#{adminMsgs.update}" action="refresh" /> </h:outputFormat> ``` Properties file: ``` scheduleUpdateLink = After waiting a few seconds, please {0} the page. update = update ``` And output along these lines: ``` After waiting a few seconds, please <a href="#" class="..." onclick="...;return false;">update</a> the page. ``` This *doesn't* work (the update link appears before the 'scheduleUpdateLink' text), does anyone know how I might do it? Thanks in advance. **EDIT / UPDATE** Thanks for your reply McDowell - very useful, but still haven't completely solved my problem. I will also be needing to do the same with input boxes (h:inputText), and there may also be instances where there are multiple placeholders in one resource string. Hence I cannot guarantee the order in, say, Arabic, will be the same. If I went with a Java function; do you know if there is a way I can pass, as a string, the JSF tags, e.g. `<h:outputFormat value=..`. and use the faces context to obtain the rendered HTML which I can then insert into respective placeholders and return as plain HTML? Or any other ideas along these lines? Cheers.
The [h:outputFormat](http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/h/outputFormat.html) tag will (as far as I know) only use [f:param](http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/f/param.html) children as parameters. If the message was a link (instead of a [h:commandLink](http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/h/commandLink.html)), you could use HTML literals: ``` <h:outputFormat escape="false" value="...seconds, please &lt;a href='etc..." />. ``` I would not recommend trying to emulate h:commandLink by doing this. It might be possible to find a richer version of h:commandLink in a [third party library](http://www.jsfmatrix.net/) that does exactly what you want. Just splitting the string into two is possible, but makes life difficult for translators and the quality of translation may suffer (especially if you're doing this a lot). I'd look at using a custom function like this: ``` <f:loadBundle basename="i18n.I18n" var="bundle" /> <h:outputText value="#{i18n:fragment(bundle.scheduleUpdateLink, 0)}" /> <h:commandLink> <h:outputText value="#{bundle.update}" /> </h:commandLink> <h:outputText value="#{i18n:fragment(bundle.scheduleUpdateLink, 1)}" /> ``` The rendered output is of the form: ``` After waiting a few seconds, please <script type="text/javascript"><!-- /*JavaScript elided*/ //--> </script><a href="#" onclick="return oamSubmitForm('someClientId');">update</a> the page. ``` The function is backed by a static method that splits the string and returns the requested fragment: ``` public static String fragment(String string, int index) { // TODO: regex probably not complete; ask stackoverflow! // see http://java.sun.com/javase/6/docs/api/java/text/MessageFormat.html final String regex = "\\{\\d.*?\\}"; String[] fragments = string.split(regex, index + 2); return fragments[index]; // TODO: error handling } ``` Depending on your view technology (Facelets or JSP), the function declaration is slightly different: * [Facelets tag library documentation](https://facelets.dev.java.net/nonav/docs/dev/docbook.html#taglib-create) * [Java EE 5 tutorial on JSP tag libraries](http://java.sun.com/javaee/5/docs/tutorial/doc/bnahq.html#bnaio) --- EDIT: based on more info JSF takes a declarative approach to building interfaces. You want a dynamic UI with children ordered according to the order they appear in a translated string. These two things are at odds, but all is not lost. There are a few ways to approach this. * Redesign the UI to use text above, input/control table below (the popular form approach). This is the simplest solution, but might not make your UI designer happy. * Use the [binding attribute on a panel](http://java.sun.com/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/h/panelGroup.html) to create and programmatically order everything. This might mean a lot of repetitive code in your backing beans. * Write a reusable custom control which might look like this: . ``` <ed:formatPane string="click {0} after filling in forename {1} and surname {2}"> <h:commandLink value="#{bundle.linkMsg}" /> <h:inputText value="#{bean.prop1}" /> <h:inputText value="#{bean.prop2}" /> </ed:formatPane> ``` It is probably possible (and less work) to just replace the renderer for h:outputFormat to support arbitrary children instead of creating a full custom control, but I'd argue against it because it may lead to confusion during long-term maintenance. Someone may have already written a custom control that does what I suggest (it can hardly be an original idea).
In order for plain texts to be rendered correctly by JSF, it must be generated by <html:outputText ... > (there is some obscure technical reason). I would do this with an outputText, a commandLink and an outputText. In general, when dealing with JSF *everything* must be a tag, no plain text. A handy reference: <http://exadel.com/tutorial/jsf/jsftags-guide.html>
JSFs: commandLink as a parameter for outputFormat
[ "", "java", "jsf", "properties", "internationalization", "" ]
I need to display options present in a select region (allowing multiple select) in form of tree. This tree needs to be collapsible/expandable. I have implemented it such that it looks and works as intended in FF. ``` - 1 - 1.1 + 1.1.1 - 1.1.2 - 1.1.2.1 - 1.1.2.2 - 1.1.2.3 + 1.1.3 ``` I have achieved this by styling `<option>` tag with left padding and a google-like '+' '-' background. The JS for collapsing et al in done using jQuery. But in IE things look as if no changes had been made and the JS does not work either :| ``` 1 1.1 1.1.1 1.1.2 1.1.2.1 1.1.2.2 1.1.2.3 1.1.3 ``` Does IE not allow attaching padding, backgound etc to `<option>` tags? How can I do this differently? It is not possible to not support this work on IE6. Saving the debate on that for later ;)
Styling [<option>s in IE is quite limited](http://webbugtrack.blogspot.com/2007/11/bug-291-no-styling-options-in-ie.html). I'm afraid you won't find any solution using the <select> element as your container. In brief: * no padding * no background images * no event handlers (onclick, onkeypress, etc.) IE (5,6,7,8) only support changing the text color, background color and font of the option elements. There is a [jQueryUI Tree](http://jqueryui.pbworks.com/Tree) in development and various implementations out there for jQuery already. I would highly recommend using one of them. (PS most of them use the UL, LI tags to form the structure) I quite like this one. "[jQuery File Tree](http://abeautifulsite.net/notebook/58)"
You can use a rich combobox widget. ExtJS ([You can find it here](http://extjs.com)) is a very good widget library and they have great support on their forums.
HTML and CSS possibilities when wrappeded inside 'select' tags
[ "", "javascript", "html", "css", "internet-explorer", "xhtml", "" ]
I just wanna learn how to read Iframe content in onLoad event of iframe and write it's content to the main page ? Thanks..
I have struggled with same this past day. It seems to matter how you access the iframe. If you use `document.getElementById()` you get an Iframe object, which has no `onload` event. However, if you access through `window.frames[]` array, for example ``` var iframeWindow = top.frames['iframeID'], ``` you get a window object, which does have onload event. *(ie uses the frame id attribute , but ff uses name attribute. So use both and make the same)* You can then assign ``` iframeWindow.onload=function(){iframeContent=iframeWindow.document.body.innerHTML;}; ``` Notice, since iframeWindow is a window object, you use window syntax to access content.
You can use this jquery function in parent page and it also supports many other function to add and remove stuffs: ``` <script type="text/javascript"> function myFunction() { var $currIFrame = $('#Frame1'); $currIFrame.contents().find("body #idofElement").val('Value i want to set'); } </script> ``` In above code: `#idofElement` is the element from HTML page in iframe whose value you want to set. I Hope it helps You..
Reading Iframe Content in Iframe Load
[ "", "javascript", "html", "iframe", "" ]
I just saw this in a script ``` mysql_free_result($rawdb); ``` I saw it on a script somewhere, it ran a mysql query and saved the results to an array, right after adding to the array, it ran that which I assume free's the memory used from the mysql query. I am just asking to verify, is it a good idea to do this? I have a couple mysql queries which return a large result which is saved to an array, should I run that code after it? Also in a performance conscious environment is it good practice to unset large sessions and variables when finished with them?
From the [manual](http://us.php.net/manual/en/function.mysql-free-result.php): > `mysql_free_result()` only needs to be > called if you are concerned about how > much memory is being used for queries > that return large result sets. All > associated result memory is > automatically freed at the end of the > script's execution.
I would think it good practice to put into your data abstraction layer, as it makes it a good citizen with memory handling. Especially as a lot of PHP code is not. :-/ The issue of memory usage was a whole lot worse in PHP 4 than in 5, but it can still be an issue. If you have to keep raising the maximum memory allowed to your PHP script (the default is 8Mb, but most environments I use have this up at 64Mb), then you probably should be thinking about how your script is using and over-using memory. Using `mysql_free_result()` is one piece in this arsenal, but on its own is rather pointless. Processing huge datasets can be done much more memory efficiently if you use `mysql_unbuffered_query()` and process each row as you retrieve it with `mysql_fetch()`. I've seen the capacity of scripts to process data go up enormously when re-written to use this approach.
Question about freeing memory in a php script
[ "", "php", "mysql", "performance", "memory", "" ]
Which STL container would fit my needs best? I basically have a 10 elements wide container in which I continually `push_back` new elements while `pop_front` ing the oldest element (about a million time). I am currently using a `std::deque` for the task but was wondering if a `std::list` would be more efficient since I wouldn't need to reallocate itself (or maybe I'm mistaking a `std::deque` for a `std::vector`?). Or is there an even more efficient container for my need? P.S. I don't need random access
Since there are a myriad of answers, you might be confused, but to summarize: Use a [`std::queue`](http://en.cppreference.com/w/cpp/container/queue). The reason for this is simple: it is a FIFO structure. You want FIFO, you use a `std::queue`. It makes your intent clear to anybody else, and even yourself. A [`std::list`](http://en.cppreference.com/w/cpp/container/list) or [`std::deque`](http://en.cppreference.com/w/cpp/container/deque) does not. A list can insert and remove anywhere, which is not what a FIFO structure is suppose to do, and a `deque` can add and remove from either end, which is also something a FIFO structure cannot do. This is why you should use a `queue`. Now, you asked about performance. Firstly, always remember this important rule of thumb: **Good code first, performance last.** The reason for this is simple: people who strive for performance before cleanliness and elegance almost always finish last. Their code becomes a slop of mush, because they've abandoned all that is good in order to really get nothing out of it. By writing good, readable code first, most of you performance problems will solve themselves. And if later you find your performance is lacking, it's now easy to add a profiler to your nice, clean code, and find out where the problem is. That all said, `std::queue` is only an adapter. It provides the safe interface, but uses a different container on the inside. You can choose this underlying container, and this allows a good deal of flexibility. So, which underlying container should you use? We know that `std::list` and `std::deque` both provide the necessary functions (`push_back()`, `pop_front()`, and `front()`), so how do we decide? First, understand that allocating (and deallocating) memory is not a quick thing to do, generally, because it involves going out to the OS and asking it to do something. A `list` has to allocate memory every single time something is added, and deallocate it when it goes away. A `deque`, on the other hand, allocates in chunks. It will allocate less often than a `list`. Think of it as a list, but each memory chunk can hold multiple nodes. (Of course, I'd suggest that you [really learn how it works](http://en.wikipedia.org/wiki/Double-ended_queue).) So, with that alone a `deque` should perform better, because it doesn't deal with memory as often. Mixed with the fact you're handling data of constant size, it probably won't have to allocate after the first pass through the data, whereas a list will be constantly allocating and deallocating. A second thing to understand is [cache performance](https://homes.cs.washington.edu/~lamarca/pubs/ladner-fix-lamarca-soda99.pdf). Going out to RAM is slow, so when the CPU really needs to, it makes the best out of this time by taking a chunk of memory back with it, into cache. Because a `deque` allocates in memory chunks, it's likely that accessing an element in this container will cause the CPU to bring back the rest of the container as well. Now any further accesses to the `deque` will be speedy, because the data is in cache. This is unlike a list, where the data is allocated one at a time. This means that data could be spread out all over the place in memory, and cache performance will be bad. So, considering that, a `deque` should be a better choice. This is why it is the default container when using a `queue`. That all said, this is still only a (very) educated guess: you'll have to profile this code, using a `deque` in one test and `list` in the other to really know for certain. But remember: get the code working with a clean interface, then worry about performance. John raises the concern that wrapping a `list` or `deque` will cause a performance decrease. Once again, he nor I can say for certain without profiling it ourselves, but chances are that the compiler will inline the calls that the `queue` makes. That is, when you say `queue.push()`, it will really just say `queue.container.push_back()`, skipping the function call completely. Once again, this is only an educated guess, but using a `queue` will not degrade performance, when compared to using the underlying container raw. Like I've said before, use the `queue`, because it's clean, easy to use, and safe, and if it really becomes a problem profile and test.
Check out `std::queue`. It wraps an underlying container type, and the default container is `std::deque`.
Which STL container should I use for a FIFO?
[ "", "c++", "stl", "fifo", "" ]
From inside a PHP program I want to know the location of the binary executing it. Perl has `$^X` for this purpose. Is there an equivalent in PHP? This is so it can execute a child PHP process using itself (rather than hard code a path or assume "php" is correct). **UPDATE** 1. I'm using lighttpd + FastCGI, not Apache + mod\_php. So yes, there is a PHP binary. 2. eval/include is not a solution because I'm spawning a server which has to live on beyond the request. *Things I've tried and don't work:* * `$_SERVER['_']` looks like what I want from the command line but its actually from an environment variable set by the shell of the last executed program. When run from a web server this is the web server binary. * `which php` will not work because the PHP binary is not guaranteed to be the same one as is in the web server's `PATH`. Thanks in advance.
The PHP\_BINDIR constant gives you the directory where the php binary is
Yeah, `$_SERVER['_']` is what you're talking about, or as near as exists. The reason you're getting a Web server binary when it's run from the web is that `/usr/bin/php` has nothing to do with the Web server's execution; what it's running is a separate SAPI. There's nothing from the web PHP instance to point to `/usr/bin/php` because there's no reason for there to be.
How do I find out the currently running PHP executable?
[ "", "php", "fastcgi", "" ]
I have a requirement to implement a single VB.NET instance of an application on a terminal server. To do this I am using code from the [Flawless Code](http://www.flawlesscode.com/post/2008/02/Enforcing-single-instance-with-argument-passing.aspx) blog. It works well, except in the code is written in C# and uses an anonymous method which is not supported in VB.NET. I need to rewrite the following so that I can use it as an event in VB.NET. ``` static Form1 form; static void singleInstance_ArgumentsReceived(object sender, ArgumentsReceivedEventArgs e) { if (form == null) return; Action<String[]> updateForm = arguments => { form.WindowState = FormWindowState.Normal; form.OpenFiles(arguments); }; form.Invoke(updateForm, (Object)e.Args); //Execute our delegate on the forms thread! } } ```
You can use this code: ``` Private Shared form As Form1 Private Shared Sub singleInstance_ArgumentsReceived(ByVal sender As Object, ByVal e As ArgumentsReceivedEventArgs) If form Is Nothing Then Return form.Invoke(New Action(Of String())(AddressOf updateFormMethod), e.Args) End Sub Private Shared Sub updateFormMethod(ByVal arguments As String()) form.WindowState = FormWindowState.Normal form.OpenFiles(arguments) End Sub ```
In VB.NET in VS 2010 you can do the following: ``` Shared form As Form1 Shared Sub singleInstance_ArgumentsReceived(ByVal sender As Object, ByVal e As ArgumentsReceivedEventArgs) If form Is Nothing Then Return Dim updateForm As Action(Of String()) = Sub(arguments) form.WindowState = FormWindowState.Normal form.OpenFiles(arguments) End Sub form.Invoke(updateForm, e.args) End Sub ```
Anonymous methods - C# to VB.NET
[ "", "c#", "vb.net", "event-handling", "anonymous-methods", "" ]
What is the most impressive "rich internet application" - which is usually Javascript/Flash/Silverlight - that you have experienced? I find [Google maps](http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=area+51+america&sll=51.500969,-0.124583&sspn=0.016082,0.042787&ie=UTF8&z=8) is like Javascript/Flash voodoo and more specifically [Google Streeview](http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=houses+of+parliament&sll=51.514285,-0.127845&sspn=0.004186,0.010697&ie=UTF8&ll=51.500969,-0.125098&spn=0,359.957213&z=15&layer=c&cbll=51.500959,-0.124598&panoid=rcPWOI59rSm91p2SwDb32g&cbp=12,170.17,,0,-38.45) wins hands down. But I'm interested to know others.
Some of the [Chrome Experiments](http://www.chromeexperiments.com/) are pretty impressive
<http://windows4all.com/>
What's the most impressive Javascript/Flash/Silverlight example you've seen?
[ "", "javascript", "flash", "silverlight", "rich-internet-application", "" ]
I have a case where using a JOIN or an IN will give me the correct results... Which typically has better performance and why? How much does it depend on what database server you are running? (FYI I am using MSSQL)
Generally speaking, `IN` and `JOIN` are different queries that can yield different results. ``` SELECT a.* FROM a JOIN b ON a.col = b.col ``` is not the same as ``` SELECT a.* FROM a WHERE col IN ( SELECT col FROM b ) ``` , unless `b.col` is unique. However, this is the synonym for the first query: ``` SELECT a.* FROM a JOIN ( SELECT DISTINCT col FROM b ) ON b.col = a.col ``` If the joining column is `UNIQUE` and marked as such, both these queries yield the same plan in `SQL Server`. If it's not, then `IN` is faster than `JOIN` on `DISTINCT`. See this article in my blog for performance details: * [**`IN` vs. `JOIN` vs. `EXISTS`**](http://explainextended.com/2009/06/16/in-vs-join-vs-exists/)
This Thread is pretty old but still mentioned often. For my personal taste it is a bit incomplete, because there is another way to ask the database with the EXISTS keyword which I found to be faster more often than not. So if you are only interested in values from table a you can use this query: ``` SELECT a.* FROM a WHERE EXISTS ( SELECT * FROM b WHERE b.col = a.col ) ``` The difference might be huge if col is not indexed, because the db does not have to find all records in b which have the same value in col, it only has to find the very first one. If there is no index on b.col and a lot of records in b a table scan might be the consequence. With IN or a JOIN this would be a full table scan, with EXISTS this would be only a partial table scan (until the first matching record is found). If there a lots of records in b which have the same col value you will also waste a lot of memory for reading all these records into a temporary space just to find that your condition is satisfied. With exists this can be usually avoided. I have often found EXISTS faster then IN even if there is an index. It depends on the database system (the optimizer), the data and last not least on the type of index which is used.
SQL JOIN vs IN performance?
[ "", "sql", "sql-server", "performance", "t-sql", "" ]
I'd like to know how does .maxstack really work. I know it doesn't have to do with the actual size of the types you are declaring but with the number of them. My questions are: 1. does this apply just for the function, or to all the functions that we are calling for? 2. even if it's just for the function were .maxstack is being declared, how do you know what maxstack is if you have branching? You go and see all the "paths" and return the maximum value possible? 3. What happens if I set it to 16 and actually there are 17 variables? 4. Is there a too big of a penalty if I set it to 256?
`.maxstack` is part of the IL verification. Basically `.maxstack` tells the JIT the max stack size it needs to reserve for the method. For example, `x = y + (a - b)` translates to *(Pseudo IL:)* ``` 1. Push y on the stack 2. Push a on the stack 3. Push b on the stack 4. Pop the last two items from the stack, substract them and push the result on the stack 5. Pop the last two items from the stack, add them and push the result on the stack 6. Store the last item on the stack in x and pop the last item from the stack ``` As you can see, there are at most 3 items on the stack at each time. If you'd set `.maxstack` to 2 (or less) for this method, the code wouldn't run. Also, you cannot have something like this as it would require an infinite stack size: ``` 1. Push x on the stack 2. Jump to step 1 ``` To answer your questions: > 1. does this apply just for the function, or to all the functions that we are calling for? Just for the function > 2. even if it's just for the function were .maxstack is being declared, how do you know what maxstack is if you have branching? You go and see all the "paths" and return the maximum value possible? You go and see all the paths and return the maximum value possible > 3. What happens if I set it to 16 and actually there are 17 variables? It's unrelated to the number of variables, see *Lasse V. Karlsen*'s answer > 4. Is there a too big of a penalty if I set it to 256? Doesn't seem like a good idea, but I don't know. Do you really have to calculate the `.maxstack` yourself? `System.Reflection.Emit` calculates it for you IIRC.
It has nothing to do with the *number* of variables declared, but instead everything to do with how many values you need to push on a stack at any given time in order to compute some expression. For instance, in the following expression, I would assume 2 values needs to be pushed onto the stack: ``` x = y + z; ``` This is unrelated to the fact that there are at least 3 variables present, x, y, and z, and possibly others as well. Unfortunately I don't know the answer to your other questions, and I would guess experimentation would be one way to find some answers.
How does the .NET IL .maxstack directive work?
[ "", "c#", ".net", "vb.net", "reflection", "intermediate-language", "" ]
I was going through the wonderful book *[Programming in Scala](http://booksites.artima.com/programming_in_scala)* when I came across a piece of code that just doesn't make sense to me: ``` def above(that: Element): Element = { val this1 = this widen that.width val that1 = that widen this.width elem(this1.contents ++ that1.contents) } ``` Note line 2 and 3: ``` val this1 = this widen that.width ``` It seems like I should be able to replace this with: ``` val this1 = this.widen that.width ``` However, when I try to compile this change, it gives the following error: > error: ';' expected but '.' found. > val this1 = this.widen that.width > ^ Why is this syntax unacceptable?
Line 2 uses the method `widen` as an operator, instead of using it as a method in the Java way: ``` val this1 = this.widen(that.width) ``` The error occurs because you've left out the parentheses, which you can only do when you use a method in operator notation. You **can't** do this for example: ``` "a".+ "b" // error: ';' expected but string literal found. ``` Instead you should write ``` "a".+ ("b") ``` Actually you can do this with integers, but that's beyond the scope of this question. Read more: * Chapter 5 section 3 of your book is about the operator notation, at least in the first edition, version 5 * [A Tour of Scala: Operators](http://www.scala-lang.org/node/118 "A Tour of Scala: Operators")
I haven't tried it but maybe this works: `val this1 = this.widen(that.width)` `widen` is probably a method taking one parameter (plus the `this` reference), such methods can be used like operators as in your first sample code.
Scala dot syntax (or lack thereof)
[ "", "java", "syntax", "scala", "" ]
Looking to convert this to a string value of 2.68. I have a way to parse it out but was wondering if there was some built in functionality in the framework to do this.
Untested, uing the builtin function Int32.Parse: ``` string convert_so_1272865_v1(string s){ return ((Int32.Parse(s)/1000)/100.0).ToString(); } ``` And a version without any parsing: ``` string convert_so_1272865_v2(string s){ return s.SubString(0,1) + "." + s.SubString(1,2); } ```
Why not turn it into a number, divide by 100,000 like Dominic suggested and then format the number back into a string with the appropriate number of decimal places?
Given the string "268179", is there any built in methods that could change this to 2.68 in C#
[ "", "c#", "string", "" ]
I've been working with C# for many years now, but just come across this issue that's stumping me, and I really don't even know how to ask the question, so, to the example! ``` public interface IAddress { string Address1 { get; set; } string Address2 { get; set; } string City { get; set; } ... } public class Home : IAddress { // IAddress members } public class Work : IAddress { // IAddress members } ``` My question is, I want to copy the value of the IAddress properties from one class to another. Is this possible in a simple one-line statement or do I still have to do a property-to-property assignment of each one? I'm actually quite surprised that this seemingly simple thing has stumped me like it has... If it's not possible in a concise way, does anyone have any shortcuts they use to do this sort of thing? Thanks!
There's no one-liner for this. If you do it a lot, you could look into some form of code generation, perhaps using T4 templates and Reflection. BTW COBOL has a statement for this: MOVE CORRESPONDING HOME TO WORK.
Here's one way to do it that has nothing to do with interfaces: ``` public static class ExtensionMethods { public static void CopyPropertiesTo<T>(this T source, T dest) { var plist = from prop in typeof(T).GetProperties() where prop.CanRead && prop.CanWrite select prop; foreach (PropertyInfo prop in plist) { prop.SetValue(dest, prop.GetValue(source, null), null); } } } class Foo { public int Age { get; set; } public float Weight { get; set; } public string Name { get; set; } public override string ToString() { return string.Format("Name {0}, Age {1}, Weight {2}", Name, Age, Weight); } } static void Main(string[] args) { Foo a = new Foo(); a.Age = 10; a.Weight = 20.3f; a.Name = "Ralph"; Foo b = new Foo(); a.CopyPropertiesTo<Foo>(b); Console.WriteLine(b); } ``` In your case, if you only want one set of interface properties to copy you can do this: ``` ((IAddress)home).CopyPropertiesTo<IAddress>(b); ```
interface property copy in c#
[ "", "c#", "interface", "" ]
I have tried switching from a previous Post request to a Get request. Which assumes its a Get but eventually does a post. I tried the following in PHP : ``` curl_setopt($curl_handle, CURLOPT_POSTFIELDS, null); curl_setopt($curl_handle, CURLOPT_POST, FALSE); curl_setopt($curl_handle, CURLOPT_HTTPGET, TRUE); ``` What am I missing? Additional information: I already have a connection that's setup to do a POST request. That completes successfully but later on when I try to reuse the connection and switch back to GET using the setopts above it still ends up doing a POST internally with incomplete POST headers. The problem is it believes its doing a GET but ends up putting a POST header without the content-length parameter and the connection fails witha 411 ERROR.
Solved: The problem lies here: I set `POST` via both `_CUSTOMREQUEST` and `_POST` and the `_CUSTOMREQUEST` persisted as `POST` while `_POST` switched to `_HTTPGET`. The Server assumed the header from `_CUSTOMREQUEST` to be the right one and came back with a 411. ``` curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST'); ```
Make sure that you're putting your query string at the end of your URL when doing a GET request. ``` $qry_str = "?x=10&y=20"; $ch = curl_init(); // Set query data here with the URL curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); $content = trim(curl_exec($ch)); curl_close($ch); print $content; ``` With a POST you pass the data via the CURLOPT\_POSTFIELDS option instead of passing it in the CURLOPT\_\_URL. ``` $qry_str = "x=10&y=20"; curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); // Set request method to POST curl_setopt($ch, CURLOPT_POST, 1); // Set query data here with CURLOPT_POSTFIELDS curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str); $content = trim(curl_exec($ch)); curl_close($ch); print $content; ``` Note from the [`curl_setopt()` docs](http://php.net/curl_setopt) for `CURLOPT_HTTPGET` (emphasis added): > [Set CURLOPT\_HTTPGET equal to] `TRUE` to *reset* the HTTP request method to GET. > Since GET is the default, this is only necessary if the request method has been changed.
How to switch from POST to GET in PHP CURL
[ "", "php", "post", "curl", "get", "" ]
Does boost have one? Where A, y and x is a matrix (sparse and can be very large) and vectors respectively. Either y or x can be unknown. I can't seem to find it here: <http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/index.htm>
Linear solvers are generally part of the LAPACK library which is a higher level extension of the BLAS library. If you are on Linux, the Intel MKL has some good solvers, optimized both for dense and sparse matrices. If you are on windows, MKL has a one month trial for free... and to be honest I haven't tried any of the other ones out there. I know the Atlas package has a free LAPACK implementation but not sure how hard it is to get running on windows. Anyways, search around for a LAPACK library which works on your system.
yes, you can solve linear equations with boost's ublas library. Here is one short way using LU-factorize and back-substituting to get the inverse: ``` using namespace boost::ublas; Ainv = identity_matrix<float>(A.size1()); permutation_matrix<size_t> pm(A.size1()); lu_factorize(A,pm) lu_substitute(A, pm, Ainv); ``` So to solve a linear system Ax=y, you would solve the equation trans(A)Ax=trans(A)y by taking the inverse of (trans(A)A)^-1 to get x: x = (trans(A)A)^-1Ay.
Boost's Linear Algebra Solution for y=Ax
[ "", "c++", "math", "boost", "linear-algebra", "" ]
I am currently writing a CMS and remember someone (it might have been on here) criticise the existing CMS for not having a robust enough user permissions system. I've got a method planned out but it I feel it has fallen into the usual trap of being a bit too fine-grained which makes understanding and implementing it a horror for end users. I think having a range of default user roles with permissions would be the answer to this, so I suppose my question is this: What are the default roles you would like to see in a CMS and what sort of permissions would be associated with these? Thanks in advance!
This is the "best practice" I have ended up with in most projects and am very happy with: **1. Roles** When it comes to roles, I recommend great flexibility, i.e. the ability to create and define user accounts and groups freely **(roles like "contributor", "manager" etc. are not hard-coded, but put into a configuration file that can be changed per application)**. The role configuration is unaccessible to the user, but the engine itself should be free from hard-coded roles. **2. Rights** *Rights* is where things need to be **easy to understand and implement**. I have made very good experiences working with, and checking against, **very fine-grained rights on the code / API level**: * see * view * edit * change name * rename * delete * move * change rights * etc. but **the user never sees those**. For them, they are **grouped** into a very small number of "right groups": * Read Only * Edit * Administer = Move, rename.... The user never sees the "move" right, but only the "Administer" rights group. That way, you **retain the full power of fine-grained rights** in your code for the future - you can, for example, easily accommodate for a rule like "interns must be able to edit pages, but not be able to change their titles, nor to delete them", adding a valuable asset to the CMS. For the end user, this functionality remains invisible, and the rights system easy to use.
I [asked this question](https://stackoverflow.com/questions/1598411/standard-website-user-role-names) a little bit ago and got the following response. ``` admin //Manage everything manager //Manage most aspects of the site editor //Scheduling and managing content author //Write important content contributors //Authors with limited rights moderator //Moderate user content member //Special user access subscriber //Paying Average Joe user //Average Joe ```
Common CMS roles and access levels
[ "", "php", "permissions", "content-management-system", "roles", "access-levels", "" ]
I have simple form posting to another file. The problem I'm having is with TEXTAREA field. In the form TEXTAREA, I enter this: ``` <h1 class="padlock">Member Login</h1> ``` and the Output is on the other page when echo with PHP: ``` <h1 class=\"padlock\">Member Login</h1> ``` It's automatically escaping characters. I'm displaying the output in another TEXTAREA box. How can I make it be exactly the same?
[Magic Quotes](https://www.php.net/magic_quotes) is on. This is a deprecated feature of PHP. It was used to escape all incoming user data. You can use `stripslashes()` to get the original data back: ``` if (get_magic_quotes_gpc()) { $_POST['textareaname'] =stripslashes($_POST['textareaname']); } ``` or to apply this to the entire $\_POST array: ``` function stripslashes_recursive($data){ if(is_array($data){ $new_data = array(); foreach($new_data as $key => $entry){ $new_data[$key] = stripslashes_recursive($entry); } return $new_data; } else { return stripslashes($data); } } if (get_magic_quotes_gpc()) { $stripped_postdata = stripslashes_recursive($_POST); } ``` Note: the recursive function is used to support arrays in your post data.
Ups... stripslashes !
Added Characters on POST
[ "", "php", "html", "forms", "xhtml", "" ]
I am using a class that I cannot edit, it has a property (a boolean) of which it would be nice to be informed when it changes, I can't edit the properties get or set as I am importing the class from a .dll (which I don't have the code for). How do I create an event/function that is fired when the property is changed? **Additional** It is only changed within its own class, directly to the underlying private variable. E.g. ``` private bool m_MyValue = false; public bool MyValue { get { return m_MyValue; } } private void SomeFunction() { m_MyValue = true; } ```
You can't, basically... not without using something like the debugger API to inject code at execution time and modifying the IL of the original library (and I'm not recommending either of those solutions; aside from anything else it may violate the licence of the library). Basically if a property doesn't support notification, it doesn't support notification. You should look for a different way of approaching your problem. (Would polling work, for example?)
You cant do this directly [as Jon Skeet said], unless it's virtual, you're in a position to intercept all instance creations of the class and there are no changes to a backing field that influences the real 'value' of the propget. The only way to brute force this is to use Mono.Cecil or MS CCI to instrument the prop setter a la [this DimeCast on Cecil](http://dimecasts.net/Casts/CastDetails/59). (Or PostSharp) However this wouldn't trap internal changes to the backing field (if there even is one). (Which is why wrapping probably wont work). UPDATE: Given your update that you're definitely trying to trap the underlying field change, the only way to do that is to use PS / CCI / Cecil and analyse the flow to intercept all field updates. In short, not very feasible.
Firing an event / function on a property? (C#)
[ "", "c#", ".net", "custom-event", "" ]
I've got a client that requires that an article be displayed in two, sometimes three, columns in Joomla. I am fairly sure they won't be happy with having to edit 3 articles for 3 columns so the splitting would have to be done automatically. I've done something similar before where it'll split a chunk of HTML into n columns, but have no real idea how to accomplish this within Joomla itself. Any ideas gratefully recieved!
An alternative approach: Use Javascript to split up the Article in several column in the browser. Here I could imagine a full-automated approach could work. Advantages (over the first approach): * As Javascript can know, which height the paragraphs actually have in the browser (unlinke PHP), you could find the optimum split more accurately.* This can be implemented in the template php-File: you tell the template to include the js-File. So it could be made context-dependent, E.g.: If the left column is collapsed (because there are no modules in it), tell the JavaScript-File to initialize to 3 columns, else 2 columns. However, have in mind that it should rest usable for those who have Javascript disabled.
This doesn't seem to be easy. At first thought this should be an CSS attribute, but if it exists, it is part of CSS 3.0 and as such only understood by modern browsers (if at all). But I didn't find any way to do this in CSS. So you actually have to modify your HTML code. I would propose the following: * A Button (editor-xtd plugin) that splits the article into several parts, each one for one column, showing a dotted line in the editor box (similar to the "read-more"-Button). E.g. it inserts in the article: (you will have to define hr.column in /templates/system/css/editor.css).* A (content) plugin that creates the multiple colum-style, E.g. replacing the hr-Tag with table or floating divs. This way, it is half-automized, without mangeling in the Joomla! files but only adding to extensions to it.
Multiple column articles in Joomla
[ "", "php", "content-management-system", "joomla", "" ]
I enabled gzip compression on my website, and tested with the following tools: * <http://www.whatsmyip.org/http_compression/> * <http://www.gidnetwork.com/tools/gzip-test.php> * <http://web-sniffer.net/> Though, Firefox and all its extensions (Firebug, Yslow and Google Page Speed) say they receive noncompressed content. text/html is compressed by php's ob\_gzhandler, which cares about headers as well. I don't use proxy. What am I doing wrong?
That's not really the answer you might expect, but did you try not compressing out data with PHP, but with Apache ? This can be done use [`mod_deflate`](http://httpd.apache.org/docs/2.2/mod/mod_deflate.html). Couple of things : * it would mean less calculations for PHP * it would also mean *(and that's the nicest part **;-)** )* that your CSS/JS files could be compresses to ; considering the size of those, nowadays, it might not be a bad thing to compress them... As a sidenote : to help us figure out what's going wrong with the compression by PHP, could you give more informations ? Like the URL of your site *(if it's public)*, and some code ? --- **EDIT now that we have the URL** : <http://ego.pestaa.hu/> When I go to that page, the response's headers are as follow : ``` HTTP/1.x 200 OK Date: Sat, 01 Aug 2009 21:53:37 GMT Server: Apache X-Powered-By: PHP/5.2.6 **Content-Encoding: gzip** Vary: Accept-Encoding Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html ``` *(using firefox 3.5 with LiveHTTPHeaders extension)* The three testing sites you indicated also say that your page is gzipped. Did you find what the problem was ? Are you sure this is not something coming from your browser, that would not send the following header in the request : ``` Accept-Encoding: gzip,deflate ``` --- **EDIT after other answer** Quote from the comments : > the source of problem probably isn't > my website but my isp/browser/router. > One of them may decompress every > component before it reaches internal > processes. Oh, if the problem is not your website, I think I totally mis-understood the question -- sorry about that :-( I thought you didn't know how to server gzipped content from your website. *And I think I'm not the only one, btw* If the problem has nothing to do with your website's configuration, then, two possibilities : * maybe a mis-configuration of firefox ? If you go to `about:config`, what does the `network.http.accept-encoding` say ? For me, it's `gzip,deflate` * if the problem is coming from your ISP or something like that, there's nothing anyone can do...
Try the [Live Http Headers](https://addons.mozilla.org/en-US/firefox/addon/3829?src=api) firefox plugin in addition to the others. It opens a window showing the exact request/response headers as they go back and forward, so you know without doubt what the accept-encoding and response-encoding is.
Gzipped content expected
[ "", "php", "firefox", "compression", "gzip", "" ]
I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated. This is what I have so far. Just the SubStr... ``` echo substr("$body",0,260); ``` Cheers
It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary: ``` $line=$body; if (preg_match('/^.{1,260}\b/s', $body, $match)) { $line=$match[0]; } ``` Alternatively, you could maybe use the [wordwrap](http://php.net/wordwrap) function to break your $body into lines, then just extract the first line.
``` substr($body, 0, strpos($body, ' ', 260)) ```
Making sure PHP substr finishes on a word not a character
[ "", "php", "substring", "" ]
I have a method that gets a number of objects of this class ``` class Range<T> { public T Start; public T End; } ``` In my case `T` is `DateTime`, but lets use `int` for simplicity. I would like a method that collapses those ranges into ones that cover the same "area" but that do not overlap. So if I had the following ranges * 1 to 5 * 3 to 9 * 11 to 15 * 12 to 14 * 13 to 20 The method should give me * 1 to 9 * 11 to 20 Guess it would be called a union? I imagine the method signature could look something like this: ``` public static IEnumerable<Range<T>> Collapse<T>( this IEnumerable<Range<T>>, IComparable<T> comparer) { ... } ``` I have looked at some other questions here that are kind of similar, but I haven't found an implementation of this yet. [This answer](https://stackoverflow.com/questions/149577/need-an-algorithm-for-collapsing-netblock-ranges-into-lists-of-superset-ranges/149829#149829) and some other answers to the same question describes algorithms, but I am not quite sure if I understand the algorithms. Not especially good at implementing algorithms either, so I was hoping someone here could help me out.
This seems to works and is easy to understand. ``` public static IEnumerable<Range<T>> Collapse<T>(this IEnumerable<Range<T>> me, IComparer<T> comparer) { List<Range<T>> orderdList = me.OrderBy(r => r.Start).ToList(); List<Range<T>> newList = new List<Range<T>>(); T max = orderdList[0].End; T min = orderdList[0].Start; foreach (var item in orderdList.Skip(1)) { if (comparer.Compare(item.End, max) > 0 && comparer.Compare(item.Start, max) > 0) { newList.Add(new Range<T> { Start = min, End = max }); min = item.Start; } max = comparer.Compare(max, item.End) > 0 ? max : item.End; } newList.Add(new Range<T>{Start=min,End=max}); return newList; } ``` --- Here is the variation which I mentioned in the comments. It's basically the same thing, but with some checking and yielding of the results instead of collecting in a list before returning. ``` public static IEnumerable<Range<T>> Collapse<T>(this IEnumerable<Range<T>> ranges, IComparer<T> comparer) { if(ranges == null || !ranges.Any()) yield break; if (comparer == null) comparer = Comparer<T>.Default; var orderdList = ranges.OrderBy(r => r.Start); var firstRange = orderdList.First(); T min = firstRange.Start; T max = firstRange.End; foreach (var current in orderdList.Skip(1)) { if (comparer.Compare(current.End, max) > 0 && comparer.Compare(current.Start, max) > 0) { yield return Create(min, max); min = current.Start; } max = comparer.Compare(max, current.End) > 0 ? max : current.End; } yield return Create(min, max); } ```
A Python solution for the non-verbosephile: ``` ranges = [ (11, 15), (3, 9), (12, 14), (13, 20), (1, 5)] result = [] cur = None for start, stop in sorted(ranges): # sorts by start if cur is None: cur = (start, stop) continue cStart, cStop = cur if start <= cStop: cur = (cStart, max(stop, cStop)) else: result.append(cur) cur = (start, stop) result.append(cur) print result ```
What's a good, generic algorithm for collapsing a set of potentially-overlapping ranges?
[ "", "c#", "algorithm", "generics", "range", "union", "" ]
I have this program in C++ that forks two new processes: ``` #include <pthread.h> #include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdlib> using namespace std; int shared; void func(){ extern int shared; for (int i=0; i<10;i++) shared++; cout<<"Process "<<getpid()<<", shared " <<shared<<", &shared " <<&shared<<endl; } int main(){ extern int shared; pid_t p1,p2; int status; shared=0; if ((p1=fork())==0) {func();exit(0);}; if ((p2=fork())==0) {func();exit(0);}; for(int i=0;i<10;i++) shared++; waitpid(p1,&status,0); waitpid(p2,&status,0);; cout<<"shared variable is: "<<shared<<endl; cout<<"Process "<<getpid()<<", shared " <<shared<<", &shared " <<&shared<<endl; } ``` The two forked processes make an increment on the shared variables and the parent process does the same. As the variable belongs to the data segment of each process, the final value is 10 because the increment is independent. However, the memory address of the shared variables is the same, you can try compiling and watching the output of the program. How can that be explained ? I cannot understand that, I thought I knew how the fork() works, but this seems very odd.. I need an explanation on why the address is the same, although they are separate variables.
The OS is using [virtual memory](http://en.wikipedia.org/wiki/Virtual_memory) and similar techniques to ensure that each process sees different memory cells (virtual or read) at the same addresses; only memory that's explicitly shared (e.g. via shm) is shared, all memory by default is separate among separate processes.
This is called "virtual address". Each process has its own address space, and each address means something different, depending on the process. fork() creates a copy, instead of sharing data (technically, they may get shared copy-on-write, but this is has the same effect as upfront copying would). IOW, the variable "shared" is not shared between processes.
About fork system call and global variables
[ "", "c++", "unix", "linux-kernel", "fork", "" ]
Consider the following method signature: ``` public static bool TryGetPolls(out List<Poll> polls, out string errorMessage) ``` This method performs the following: * accesses the database to generate a list of Poll objects. * returns true if it was success and errorMessage will be an empty string * returns false if it was not successful and errorMessage will contain an exception message. Is this good style? Update: Lets say i do use the following method signature: ``` public static List<Poll> GetPolls() ``` and in that method, it doesn't catch any exceptions (so i depend the caller to catch exceptions). How do i dispose and close all the objects that is in the scope of that method? As soon as an exception is thrown, the code that closes and disposes objects in the method is no longer reachable.
That method is trying to do three different things: 1. Retrieve and return a list of polls 2. Return a boolean value indicating success 3. Return an error message That's pretty messy from a design standpoint. A better approach would be to declare simply: ``` public static List<Poll> GetPolls() ``` Then let this method throw an `Exception` if anything goes wrong.
I believe ``` public static bool TryGetPolls(out List<Poll> polls) ``` would be more appropriate. If the method is a `TryGet` then my initial assumption would be there is reason to expect it to fail, and onus is on the caller to determine what to do next. If they caller is not handling the error, or wants error information, I would expect them to call a corresponding `Get` method.
Is this good C# style?
[ "", "c#", "coding-style", "" ]
Here's a question where my real world programming inexperience shines through. I have a function which makes a call to three other functions: ``` Public Sub StartService() RunSearch() SaveMessages() DeleteMessages() End Sub ``` within each of the methods `RunSearch(), SaveMessages() and DeleteMessages()` I am using Try Catch statements to catch errors. Right now I catch the error and write to an error log when `RunSearch()` errors out, but I'm also get two errors from `SaveMessages()` and `DeleteMessages()` because these functions are dependent upon `RunSearch()` not returning an error. I am trying to build good a error catching foundation so I don't just want to kill the app when there's an error. My question is this: How can I gracefully stop execution if an error occurs in `RunSearch()`.
Why does `RunSearch` not rethrow the exception after logging the problem? If you don't want to call `SaveMessages()` if `RunSearch()` fails then don't code it that way. My general thought is that each method's interface is specifying a "protocol". It must state its behaviour in the event of problems. Approaches include: 1. If I get an error I will terminate the process. This is pretty extreme, limits the reusability of your method. 2. I will return a count or status code or somesuch. It's up to you to decide whether to check that and whether any particular status code means it's safe to call some other method. I prefer not to rely on the client to remember to check status codes. 3. If I fail I will leave things so that subsequent processing will be sane. For example, if my job is to create a linked list then in the event of errors I will not leave a dangling pointer or an initialized list. You may get an empty list, but at least well formed subsequent processing will work. This tends to imply some degree of agreement (ie. coupling) with the other methods. This is often the nicest approach, especially when coupled with good logging of the problems. 4. I will throw an exception if I couldn't do the work. The exception will indicate whether there's some chance of things working later if you call be again (I use TransientException and InvalidRequestException quite a lot). Exceptions are useful because the client cannot (for Java checked exceptions) accidentally ignore them. When dealing with problems such as "could not open database" this seems reasonable. We really do not want folks mistaking "couldn't even get to the database" with "this person has no criminal record".
One possible option would be to change the RunSearch method to return a Boolean - True if successful, and False if an error occurred that would block the other two functions. Then you could do this: ``` Public Sub StartService() If RunSearch() Then SaveMessages() DeleteMessages() End If End Sub ```
How can I gracefully exit my application on an error?
[ "", "c#", "asp.net", "vb.net", "error-handling", "" ]
Just read on an internal university thread: ``` #include <iostream> using namespace std; union zt { bool b; int i; }; int main() { zt w; bool a,b; a=1; b=2; cerr<<(bool)2<<static_cast<bool>(2)<<endl; //11 cerr<<a<<b<<(a==b)<<endl; //111 w.i=2; int q=w.b; cerr<<(bool)q<<q<<w.b<<((bool)((int)w.b))<<w.i<<(w.b==a)<<endl; //122220 cerr<<((w.b==a)?'T':'F')<<endl; //F } ``` So `a`,`b` and `w.b` are all declared as `bool`. `a` is assigned `1`, `b` is assigned `2`, and the internal representation of `w.b` is changed to `2` (using a `union`). This way all of `a`,`b` and `w.b` will be `true`, but `a` and `w.b` won't be equal, so this might mean that the universe is broken (`true!=true`) I know this problem is more theoretical than practical (a sake programmer doesn't want to change the internal representation of a `bool`), but here are the questions: 1. Is this okay? (this was tested with g++ 4.3.3) I mean, should the compiler be aware that during boolean comparison *any* non-zero value might mean true? 2. Do you know any case where this corner case might become a real issue? (For example while loading binary data from a stream) EDIT: Three things: 1. `bool` and `int` have different sizes, that's okay. But what if I use `char` instead of `int`. Or when `sizeof(bool)==sizeof(int)`? 2. Please give answer to the two questions I asked if possible. I'm actually interested in answers to the second questions too, because in my honest opinion, in embedded systems (which might be 8bit systems) this might be a real problem (or not). 3. New question: Is this *really* undefined behavior? If yes, why? If not, why? Aren't there any assumptions on the boolean comparison operators in the specs?
> 1. Is this okay? (this was tested with g++ 4.3.3) I mean, should the compiler be aware that during boolean comparison any non-zero value might mean true? Any integer value that is non zero (or pointer that is non NULL) represents true. But when comparing integers and bool the bool is converted to int before comparison. > 2. Do you know any case where this corner case might become a real issue? (For example while binary loading of data from a stream) It is always a real issue. > 1. Is this okay? > > I don't know whether the specs specify anything about this. A compiler might always create a code like this: ((a!=0) && (b!=0)) || ((a==0) && (b==0)) when comparing two booleans, although this might decrease performance. > > In my opinion this is not a bug, but an undefined behaviour. Although I think that every implementor should tell the users how boolean comparisons are made in their implementation. If we go by your last code sample both a and b are bool and set to true by assigning 1 and 2 respectfully (Noe the 1 and 2 disappear they are now just true). So breaking down your expression: ``` a!=0 // true (a converted to 1 because of auto-type conversion) b!=0 // true (b converted to 1 because of auto-type conversion) ((a!=0) && (b!=0)) => (true && true) // true ( no conversion done) a==0 // false (a converted to 1 because of auto-type conversion) b==0 // false (b converted to 1 because of auto-type conversion) ((a==0) && (b==0)) => (false && false) // false ( no conversion done) ((a!=0) && (b!=0)) || ((a==0) && (b==0)) => (true || false) => true ``` So I would always expect the above expression to be well defined and always true. But I am not sure how this applies to your original question. When assigning an integer to a bool the integer is converted to bool (as described several times). The actual representation of true is not defined by the standard and could be any bit pattern that fits in an bool (You may not assume any particular bit pattern). When comparing the bool to int the bool is converted into an int first then compared. > 2. Any real-world case > > The only thing that pops in my mind, if someone reads binary data from a file into a struct, that have bool members. The problem might rise, if the file was made with an other program that has written 2 instead of 1 into the place of the bool (maybe because it was written in another programming language). > > But this might mean bad programming practice. Writing data in a binary format is non portable without knowledge. There are problems with the size of each object. There are problems with representation: * Integers (have endianess) * Float (Representation undefined ((usually depends on the underlying hardware)) * Bool (Binary representation is undefined by the standard) * Struct (Padding between members may differ) With all these you need to know the underlying hardware and the compiler. Different compilers or different versions of the compiler or even a compiler with different optimization flags may have different behaviors for all the above. The problem with Union ``` struct X { int a; bool b; }; ``` As people mention writing to 'a' and then reading from 'b' is undefined. Why: because we do not know how 'a' or 'b' is represented on this hardware. Writing to 'a' will fill out the bits in 'a' but how does that reflect on the bits in 'b'. If your system used 1 byte bool and 4 byte int with lowest byte in low memory highest byte in the high memory then writing 1 to 'a' will put 1 in 'b'. But then how does your implementation represent a bool? Is true represented by 1 or 255? What happens if you put a 1 in 'b' and for all other uses of true it is using 255? So unless you understand both your hardware and your compiler the behavior will be unexpected. Thus these uses are undefined but not disallowed by the standard. The reason they are allowed is that you may have done the research and found that on your system with this particular compiler you can do some freeky optimization by making these assumptions. But be warned any changes in the assumptions will break your code. Also when comparing two types the compiler will do some auto-conversions before comparison, remember the two types are converted into the same type before comparison. For comparison between integers and bool the bool is converted into an integer and then compared against the other integer (the conversion converts false to 0 and true to 1). If the objects being converted are both bool then no conversion is required and the comparison is done using boolean logic.
If you read a member of a union that is a different member than the last member which was written then you get undefined behaviour. Writing an int member and then reading the union's bool member could cause anything to happen at any subsequent point in the program. The only exception is where the unions is a union of structs and all the structs contain a common initial sequence, in which case the common sequence may be read.
Strange C++ boolean casting behaviour (true!=true)
[ "", "c++", "casting", "boolean", "unions", "" ]
I designed a query in SQL View using MS Access: ``` select floor(num1) from t1; ``` When I run it, I get "undefined function floor". I get similar errors for `Ceil`, `Mod`,`Power`, `Sign`, `Sqrt`, `Trunc`, and `initcap` functions. Does the Access database engine's SQL syntax have equivalent functions?
Replace Floor() with Int(). I learned this by searching in the Access help files, in this case, hitting F1 while in the query designer, and searching for "functions." That took me to a help topic comparing VBA and T-SQL functions. You should probably have a look at the [Access database engine SQL Reference](http://msdn.microsoft.com/en-us/library/office/jj583214.aspx). I can't find a good online reference for functions that are supported through the Jet/ACE and Access expression services. For some unknown reason, the Access Help has not included Jet/ACE expressions since Jet 3.0 and this aged resource was finally removed from MSDN a year or two ago :( Keep in mind that the Jet/ACE expression service for use outside Access supports a much smaller subset of functions that is possible using the Access Expression Service when running your SQL inside Access 2007. Broadly speaking, the VBA5 functions (as distinct from methods) that involve simple data types (as distinct from, say, arrays or objects) are supported outside of the Access user interface; for an approximate list of function names see the 'Use Sandbox mode operations with Jet 4.0 Service Pack 3 and later' section of [this MSDN article](http://support.microsoft.com/kb/294698). Also, the functions reference in the VBE help should be a starting place. The help files are not perfect, but a little searching ought to get you what you need.
``` Public Function Floor(ByVal x As Double) As Double 'Be Because VBA does not have a Floor function. 'Works for positive numbers 'Turns 3.9 -> 3 'Note: Round(3.9) = 4 Dim s As String, dPos As Integer s = CStr(x) dPos = InStr(s, ".") Floor = CLng(Left(s, dPos - 1)) End Function ```
Using math functions in Sql with MS Access
[ "", "sql", "ms-access", "ms-access-2007", "ms-jet-ace", "" ]
I'm in PHP working on an Euler problem. I have this function so far: ``` <?php $biggest = 0; $counter = 1; function test($i){ global $biggest; global $counter; if ($i == 1) { echo "I'm done! Took me $biggest steps"; } else { if ($i%2 == 0) { $counter = $counter + 1; if ($counter>$biggest) { $biggest = $counter; } test($i/2); } else { $counter = $counter + 1; if ($counter>$biggest) { $biggest = $counter; } test(3*$i+1); } } } test(13); ?> ``` I have the problem mostly licked, but I can't seem to get back at the original input. The question is "When you have a number, if odd get 3n+1, when even, get n/2, do until returns 1. What starting value yields the most "steps" before you get to one?" I currently am returning the number of steps, but I keep resetting $i as I recurse, so I can't record what starting # yielded my $biggest number of steps. How can I keep track of that number, but also not have it destroyed at the next instance of the loop? (I'll eventually wrap this in a for ($i=1, $i<1000000, $i++) loop) Thanks!
A common approach is to pass the original argument through each time, so that when eventually you get to your base case, you still have it available. A primitive (and almost entirely unrelated example): ``` <?php function fact($n) { if($n == 1) return 1; else return $n * fact($n - 1); } ?> ``` This is an extremely basic implementation of the factorial function in PHP. Now say you wanted for whatever reason to have the initial value available in the final step: you'd build a wrapper function `fact($n)` that would call something like `memory_fact($n, $initial)`: ``` <?php function fact($n) { return memory_fact($n, $n); } function memory_fact($n, $initial) { if($n == 1) return 1; else return $n * memory_fact($n - 1, $initial); } ?> ``` This way, `memory_fact` always knows where it started.
It's easy, just pass it around as a parameter! Here's some python-ish pseudocode: ``` def func(start, arg): if foo(arg): return func(start, arg+1) else: return [start, arg] ```
How do I save the original argument in a recursive function in PHP?
[ "", "php", "recursion", "" ]
I have a content placeholder containing a link: ``` <asp:Content ID="Content5" runat="server" contentplaceholderid="ContentPlaceHolder3"> <a href= "../WOPages/WO_Main.aspx?WONum=12345">WorkOrder</a> ``` and I would like to change the href querystring from code. How do I find it to change it?
If you add an `id` and a `runat="server"` attribute to your link... ``` <a id="YourLink" runat="server" href="../WOPages/WO_Main.aspx?WONum=12345"> WorkOrder </a> ``` ...then you can access/change the [`HRef`](http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlanchor.href.aspx) property programmatically... ``` YourLink.HRef = "http://stackoverflow.com/"; ```
You could clear all controls from the ContentPlaceholder and then add a new hyperlink control like this: ``` // Create your hyperlink control HyperLink lnk = new HyperLink(); lnk.NavigateUrl = "http://domain.com"; lnk.Text = "Click here"; ContentPlaceHolder3.Controls.Clear(); ContentPlaceHolder3.Controls.Add(lnk); ``` or give the hyperlink an Id and update the hyperlink by finding the control in the ContentPlaceholder: ``` HyperLink lnk = ContentPlaceHolder3.FindControl("MyLink") as HyperLink; lnk.NavigateUrl = "http://domain.com/update/"; lnk.Text = "Click here too"; ```
Change href link in content place holder from C# code
[ "", "c#", "asp.net", "" ]
On <http://www.justinshattuck.com/2007/01/18/mysql-injection-cheat-sheet/?akst_action=share-this> , there is a section that claims you can bypass mysql\_real\_escape\_string with certain Asian character encodings > Bypassing mysql\_real\_escape\_string() with BIG5 or GBK > > "injection string" > に関する追加情報: > > the above chars are Chinese Big5 Is this really true? And if so, how would you protect your website against this, if you had no access to prepared statements?
According to Stefan Esser, *"`mysql_real_escape_string()` [is] not safe when `SET NAMES` is used."* His explanation, [from his blog](http://www.suspekt.org/2008/09/18/slides-from-my-lesser-known-security-problems-in-php-applications-talk-at-zendcon/): > SET NAMES is usually used to switch the encoding from what is default to what the application needs. > This is done in a way that `mysql_real_escape_string` doesn’t know about this. This means if you switch to some multi byte encoding that allows backslash as 2nd 3rd 4th… byte you run into trouble, because `mysql_real_escape_string` doesn’t escape correctly. UTF-8 is safe… > > Safe way to change encoding is `mysql_set_charset`, but that is only available in new PHP versions He does mention that UTF-8 is safe, though.
This is a MySQL server bug that was reportedly fixed way back in May 2006. See: * [MySQL bug #8303](http://bugs.mysql.com/bug.php?id=8303): String literals with multi-byte characters containing \ are lexed incorrectly * [MySQL Bug #8317](http://bugs.mysql.com/bug.php?id=8317): Character set introducer in query fails to override connection character set * [MySQL Bug #8378](http://bugs.mysql.com/bug.php?id=8378): String escaped incorrectly with client character set 'gbk' * MySQL 5.1.11 [changelog](http://dev.mysql.com/doc/refman/5.1/en/news-5-1-11.html). The bug was reported fixed in MySQL 4.1.20, 5.0.22, 5.1.11. If you use 4.1.x, 5.0.x, or 5.1.x, make sure you have upgraded at least to the minor revision numbers. As a workaround, you can also enable the SQL mode [`NO_BACKSLASH_ESCAPES`](http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html#sqlmode_no_backslash_escapes) which disables backslash as a quote-escape character.
Does mysql_real_escape_string() FULLY protect against SQL injection?
[ "", "php", "mysql", "sql-injection", "" ]
If you go to <http://profile.microsoft.com> and edit your personal information, you will select your country. When a country is selected the city and/or state information changes based on what is expected for that country. Does anyone have any examples on how to accomplish this? Is there any service (free service) that provides this information?
Regarding the data: [Country, State, Province WebService?](https://stackoverflow.com/questions/121117/country-state-province-webservice)
Because you tagged your question with "jquery", [here](http://plugins.jquery.com/project/DependentSelect) is an example of a "Depending / Cascading Selectbox" (which you are searching) [Demo](http://www.ajaxray.com/Examples/depend.html)
Country/State Dynamic Drop Down List
[ "", "javascript", "jquery", "html", "ajax", "dhtml", "" ]
in my dao, in each method, when i call jdbctemplate, i should call with new jdbctemplate(). right? or get one static instant of jdbctemplate and reuse ? how about jpatemplate?
> in my dao, in each method, when i call jdbctemplate, i should call with new jdbctemplate(). right? no, you don't. the `JdbcTemplace` should be injected in your DAO by configuration. Ditto for `JpaTemplate`.
To add to the other answers, `JdbcTemplate` is very lightweight, and its cost of construction is near-zero. So if you *were* to create a new one on every operation, there likely wouldn't be any side-effects or meaningful performance degradation. The class is merely a behavioural wrapper around the JDBC API. By the same logic, there's no reason to be careful about making sure you only have one `JdbcTemplate` object. It should fit whichever design you choose to use. Most DAOs do dot instantiate `JdbcTemplate` directly. Instead, they subclass `JdbcDaoSupport`, which manage a `JdbcTemplate` instance for you. Your subclass then calls `getJdbcTemplate()` to fetch the instance. If you're not subclassing JdbcDaoSupport, then create an instance of `JdbcTemplate` when your DAO bean is initialized, and re-use it. The same applies to the other DAO template classes (Hibernate, JPA, etc).
jdbctemplate, jpatemplate
[ "", "java", "spring", "spring-mvc", "" ]