instruction
stringlengths
0
30k
JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? **Please look up HttpOnly before answering this question.** *Edit:* I'm sorry, I guess a lot of people don't understand the question, as evidenced by the edit to my question & the answers. Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option? *Edit 2:* Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, **what is the point of HttpOnly**? *Edit 3:* Here is a quote from Wikipedia: >When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The `HttpOnly` flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33]. I understand that `document.cookie` is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? In your example, I cannot write to your `document.cookie`, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object. <script type="text/javascript"> var req = null; try { req = new XMLHttpRequest(); } catch(e) {} if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} req.open('GET', 'http://stackoverflow.com/', false); req.send(null); alert(req.getAllResponseHeaders()); </script> _Edit 4:_ Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? **Please look up HttpOnly before answering this question.** *Edit:* I'm sorry, I guess a lot of people don't understand the question, as evidenced by the edit to my question & the answers. Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option? *Edit 2:* Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, **what is the point of HttpOnly**? *Edit 3:* Here is a quote from Wikipedia: >When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The `HttpOnly` flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33]. I understand that `document.cookie` is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? In your example, I cannot write to your `document.cookie`, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object. <script type="text/javascript"> var req = null; try { req = new XMLHttpRequest(); } catch(e) {} if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} req.open('GET', 'http://stackoverflow.com/', false); req.send(null); alert(req.getAllResponseHeaders()); </script> _Edit 4:_ Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated... _Final Edit:_ Ahh, apparently both sites are wrong, this is actually a [bug in FireFox][1]. IE6 & 7 are actually the only browsers that currently fully support HttpOnly. To reiterate everything I've learned: * HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers) * HttpOnly removes in the cookie from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7. * XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies. [1]: https://bugzilla.mozilla.org/show_bug.cgi?id=380418
How do you write the syntax for a While loop? ## C`#` int i = 0; while (i != 10) { Console.WriteLine(i); i++; } ## VB.Net Dim i As Integer = 0 While i <> 10 Console.WriteLine(i) i += 1 End While ## PHP <?php while(CONDITION) { //Do something here. } ?> <?php //MySQL query stuff here $result = mysql_query($sql, $link) or die("Opps"); while($row = mysql_fetch_assoc($result)) { $_SESSION['fName'] = $row['fName']; $_SESSION['lName'] = $row['lName']; //... } ?> ## Python i = 0 while i != 10: print i i += 1 Edit: I searched on this site for how to do a while loop. The answer was not here, so I created the question and answered it for when this site goes public and Google indexes it. I know this was a easy question, but I saw a knowledge gap and decided to fill it. Feel free to edit or add more languages in the question. Edit: @Rob, Thank you for closing it. I was not looking for a Rep builder, I just want the next new programmer who searches for while loops to find this page and learn not only basic programming skills, but also introduced to all of your knowledge and be able to expand past while loops.
I personally would not try to re-invent the wheel here. If you already have an Excel sheet that has the formatting you want, just export the data from Access into Excel for the report. Now, if you didn't have the original Excel sheet to begin with, that would be a completely different story. As for breaking lines with non-monospaced fonts, have you tried setting the cell format to wrap?
The following selector should also work in jQuery: `'input:checkbox'`. You can then string the `:gt(index)` and `:lt(index)` filters together, so if you want the 5th to 7th checkboxes, you'd use `'input:checkbox:gt(4):lt(2)'`.
The following selector should also work in jQuery: `'input:checkbox'`. You can then string the `:gt(index)` and `:lt(index)` filters together, so if you want the 5th to 7th checkboxes, you'd use `'input:checkbox:gt(4):lt(2)'`. To get the index of the currently clicked checkbox, just use `$("input:checkbox").index($(this))`.
The likely reason they're using `blockquote` is that many people dabbling in HTML don't know enough about CSS to know that a `div` can be given the same left-margin as `blockquote` renders with by default.
As far as I know, not all the crawlers support Allow tag. One possible solution might be putting everything except the home page into another folder and disallowing that folder.
I'm not sure there's any easy way to parse a date and work out its pattern, but I would have thought that the pattern for the one you posted would be: EEE MMM dd HH:mm:ss zzz yyyy
Are you just asking for the pattern for that given date? If so, I think this should do it: "EEE MMM d HH:mm:ss z yyyy" Or are you trying to take any formatted date, and infer the format, and parse it?
The format to pass to SimpleDateFormat could be looked up at http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy") As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in advance what the format is.
|asp.net|asp.net-mvc|mvc|
Using preview 4 of [ASP.NET MVC][1] Code like: <%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %> only outputs: <input type="checkbox" value="True" name="myCheckBox" /> There is a `name` there for the form post back but no `id` for javascript or labels :-( I was hoping that changing it to: Html.CheckBox( "myCheckBox", "Click Here", "True", false, new { id="myCheckBox" } ) would work - but instead I get an exception: System.ArgumentException: An item with the same key has already been added. As if there was already an id somewhere in a collection somewhere - I'm stumped! The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here): System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Web.Routing.RouteValueDictionary.Add(String key, Object value) at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes) at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108 at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Control.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Page.Render(HtmlTextWriter writer) at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) [1]: http://asp.net/mvc
Using [preview 4][1] of [ASP.NET MVC][2] Code like: <%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %> only outputs: <input type="checkbox" value="True" name="myCheckBox" /> There is a `name` there for the form post back but no `id` for javascript or labels :-( I was hoping that changing it to: Html.CheckBox( "myCheckBox", "Click Here", "True", false, new { id="myCheckBox" } ) would work - but instead I get an exception: System.ArgumentException: An item with the same key has already been added. As if there was already an id somewhere in a collection somewhere - I'm stumped! The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here): System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Web.Routing.RouteValueDictionary.Add(String key, Object value) at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes) at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108 at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Control.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) at System.Web.UI.Page.Render(HtmlTextWriter writer) at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) at System.Web.UI.Control.RenderControl(HtmlTextWriter writer) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) [1]: http://www.codeplex.com/aspnet [2]: http://asp.net/mvc
Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it. Originally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune to rename them, but I guess that keeping Popen makes it easier to find in the docs for those who have a long history with python or even to the venerable posix functions. From it's earliest posix incarnation, `Popen` has always been meant to open a Process and allow you to read and write from it's stdio like a file. Thus the mnemonic for `Popen` is that it is short for `ProccesOpen` in an attempt to kind of, sorta, look like open.
Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it. Originally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune time to rename them, but I guess that keeping Popen makes it easier to find in the docs for those who have a long history with python or even to the venerable posix functions. From it's earliest posix incarnation, `Popen` has always been meant to open a Process and allow you to read and write from it's stdio like a file. Thus the mnemonic for `Popen` is that it is short for `ProccesOpen` in an attempt to kind of, sorta, look like open.
If you're using Visual Studio, there's the option to break whenever an exception is thrown, regardless of whether it's unhandled or not. When the exception is thrown, the exception helper (maybe only VS 2005 and later) will tell you what kind of exception it is. Hit Ctrl+Alt+E to bring up the exception options dialog and turn this on.
@sectrean That doesn't work because the compiler ignores the Exception ex value if there is nothing using it.
How to download a live MySQL db into a local test db on demand, without SSH?
|php|ruby|database|mysql|
I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this? Some points to note: - Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1 - Local server is running the same (so using PHP is an option), but the OS is Windows - Local server has Ruby on it (so using Ruby is a valid option) - The live MySQL db *can* accept remote connections from different IPs
I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this? Some points to note: - Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1 - Local server is running the same (so using PHP is an option), but the OS is Windows - Local server has Ruby on it (so using Ruby is a valid option) - The live MySQL db *can* accept remote connections from different IPs - I cannot enable replication on the remote server
JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site? *Edit:* Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option? *Edit 2:* Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, **what is the point of HttpOnly**? *Edit 3:* Here is a quote from Wikipedia: >When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The `HttpOnly` flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33]. I understand that `document.cookie` is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only? In your example, I cannot write to your `document.cookie`, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object. <script type="text/javascript"> var req = null; try { req = new XMLHttpRequest(); } catch(e) {} if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} req.open('GET', 'http://stackoverflow.com/', false); req.send(null); alert(req.getAllResponseHeaders()); </script> _Edit 4:_ Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated... _Final Edit:_ Ahh, apparently both sites are wrong, this is actually a [bug in FireFox][1]. IE6 & 7 are actually the only browsers that currently fully support HttpOnly. To reiterate everything I've learned: * HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers) * HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7. * XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies. [1]: https://bugzilla.mozilla.org/show_bug.cgi?id=380418
You want a[0,1] instead of a[0].
Here's my solution, but even more importantly my approach to solving the problem. I approached the problem by - drawing the memory cells and drawing arrows from the destination to the source. - made a table showing the above drawing. - labeling each row in the table with the relative byte address. This showed me the pattern: - let iL be the low nybble (half byte) of a[i] - let iH be the high nybble of a[i] - iH = (i+1)L - iL = (i+2)H This pattern holds for all bytes. Translating into C, this means: a[i] = (iH << 4) OR iL a[i] = ((a[i+1] & 0x0f) << 4) | ((a[i+2] & 0xf0) >> 4) We now make three more observations: - since we carry out the assignments left to right, we don't need to store any values in temporary variables. - we will have a special case for the tail: all 12 bits at the end will be zero. - we must avoid reading undefined memory past the array. since we never read more than a[i+2], this only affects the last two bytes So, we - handle the general case by looping for N-2 bytes and performing the general calculation above - handle the next to last byte by it by setting iH = (i+1)L - handle the last byte by setting it to 0 given a with length N, we get: for (i = 0; i < N - 2; ++i) { a[i] = ((a[i+1] & 0x0f) << 4) | ((a[i+2] & 0xf0) >> 4); } a[N-2] = (a[N-1) & 0x0f) << 4; a[N-1] = 0; And there you have it... the array is shifted left by 12 bits. It could easily be generalized to shifting N bits, noting that there will be M assignment statements where M = number of bits modulo 8, I believe. (I've just typed this in, so now would be a good time for somebody to review the code, especially since bit twiddling is notoriously easy to get wrong.)
So, you intend to modify the data being dropped based on the drop target? I don't think this is possible; after all, you populate the data when the drag is initiated.
FLVPlayback component memory issues
|actionscript-3|memory|video|flash|
My website is entirely flash based, it moves around a 3D model which was given to me as chunks of video that I've converted to FLV files. I'm using the FLVPlayback component to control the video inside of my program. While running memory checks using System.totalMemory I've noticed that whenever a video is loaded, it will eat up a chunk of memory and even when I remove all the event listeners from it(they are all weakly referenced), remove the component from its parent, stop the video and null the component instance, it still will not give that memory back. This has been bothering me since I started working on this project because of the huge amount of video a user can potentially instantiate and load. Currently every video is loaded into a new FLVPlayback instance whenever it is required, but I have read that perhaps the best way to go about this problem is to simply have a global FLVPlayback instance and just reload the new video into the old instance, that way there would only be one FLVPlayback component in the application's memory. Has anyone else run into this problem as well? Have you found a better solution than using a global instance that you just re-use for every new video?
How Best to Compare Two Collections in Java and Act on Them?
|java|collections|
I have two collections of the same object, `Collection<Foo> oldSet` and `Collection<Foo> newSet`. The required logic is as follow: - if `foo` is in(*) `oldSet` but not `newSet`, call `doRemove(foo)` - else if `foo` is not in `oldSet` but in `newSet`, call `doAdd(foo)` - else if `foo` is in both collections but modified, call `doUpdate(oldFoo, newFoo)` - else if `!foo.activated && foo.startDate >= now`, call `doStart(foo)` - else if `foo.activated && foo.endDate <= now`, call `doEnd(foo)` (*) "in" means the unique identifier matches, not necessarily the content. The current (legacy) code does many comparisons to figure out `removeSet`, `addSet`, `updateSet`, `startSet` and `endSet`, and then loop to act on each item. The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info: - As far as I know, the `oldSet` and `newSet` are actually backed by `ArrayList` - Each set contains less than 100 items, most likely max out at 20 - This code is called frequently (measured in millions/day), although the sets seldom differ My questions: - If I convert `oldSet` and `newSet` into `HashMap<Foo>` (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? - Would iterating the two sets and perform the appropriate operation be more efficient and concise?
DSL in Finance
|dsl|finance|
does anyone here have ever worked with [DSLs (Domain Specific Languages)](http://www.google.com.br/url?sa=t&ct=res&cd=1&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FDomain-specific_programming_language&ei=QyWvSIXcC4foebjSlHs&usg=AFQjCNFsZOnJm-AGmi5sxai8YI-0Al6wfA&sig2=6nX5EkUmNkEwiSKAkUeyZQ) in the finance domain ? I am planning to introduce some kind of DSL support in the application i'm working on and would like to share some ideas. I am in a stage of identifying which are the most stable domain elements and selecting the feature which would be better implemented with the dsl. I haven't yet defined the syntax for this first feature. I appreciate any advices Gustavo
mockRepository.Expect( r => r.Query() ).Returns( myEnumerable.AsQueriable() );
In Moq it would be: mockRepository.Expect( r => r.Query() ).Returns( myEnumerable.AsQueriable() );
In Moq it would be: mockRepository.Expect( r => r.Query() ).Returns( myEnumerable.AsQueriable() ); In RhinoMocks it would be: Expect.Call( repository.Query() ).Return( myEnumerable.AsQueriable() );
@MrBrutal I love Notepad2 as well. The only problem is it's lame with large files. :(
Depends on the implementation. What language/library/class? There may be a best case, but it would be very specific to the number of features in the implementation.
One huge difference would be the move from Matz's interpreter to [YARV][1], a bytecode virtual machine that helps significantly with performance. [1]: http://en.wikipedia.org/wiki/YARV
Do you write your own specific Exceptions?
|java|exception|
I have some code that gives a user id to a utility that then send email to that user. emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } `MailException` could be thrown for a number of reasons, problems with the email address, problems with the mail template etc. My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.
Do you write exceptions for specific issues or general exceptions?
|java|c#|exception|
|c#|java|exception|
I have some code that gives a user id to a utility that then send email to that user. emailUtil.sendEmail(userId, "foo"); public void sendEmail(String userId, String message) throws MailException { /* ... logic that could throw a MailException */ } `MailException` could be thrown for a number of reasons, problems with the email address, problems with the mail template etc. My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened. **Edit:** As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a **valid** email address, or it could fail.. etc. My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well). Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
> The answer above doesn't account for decompressors. There is no CLSID_VideoDecompressorCategory. Is the are a way to ask a filter if it is a video decompressor? **Not that I know of.** Most filters in this list are codecs, so contain both a encoder and decoder. The filters in the CLSID_ActiveMovieCategories are wrappers around the VfW filters installed. (Some software companies create their own categories, so there may be 'non official' categories on some machines) If you want to see all installed categories, use GraphEdit which is supplied with the DirectShow SDK. GraphEdit itself is a great tool to see what DirectShow does under the hood. So maybe that may be a source of more information about the filters (and their interactions) on your system.
I cannot recommend this as *the way*, but you could create a COM-callable wrapper for your C# library, then create a VB6 ActiveX exe project that delegates calls to your C# library.
This [post][1] suggests that there is one line that needs to be added to the crossdomain.xml file. <allow-http-request-headers-from domain="*" headers="*"/> [1]: http://willperone.net/Code/as3error.php
[**JAXB**][1]. The Java Architecture for XML Binding. Basically you create an xsd defining your XML layout (I believe you could also use a DTD). Then you pass the XSD to the JAXB compiler and the compiler creates Java classes to marshal and unmarshal your XML document into Java objects. It's really simple. BTW, there are command line options to jaxb to specify the package name you want to place the resulting classes in, etc. [1]: http://java.sun.com/developer/technicalArticles/WebServices/jaxb/
Seems like my installation of Visio is the problem. I've tried on another computer here and it allow me to open 2 instances of the software.
Another point I forgot. The Windows Media Foundation is a toolkit for using WMV/WMA. It does not provide all things that DirectShow supports. It is really only a SDK for Windows Media. There are bindings in WMV/WMA to DirectShow, so that you can use WM* files/streams in DirectShow applications.
You've done a good job of explaining what you want to do but not why. There are several XML frameworks that simplify marshalling and unmarshalling Java objects to/from XML. The simplest is [Commons Digester][1] which I typically use to parse configuration files. But if you are want to deal with Java objects then you should look at [Castor][2], [JiBX][3], [JAXB][4], [XMLBeans][5], [XStream][6], or something similar. Castor or JiBX are my two favourites. [1]: http://commons.apache.org/digester/ [2]: http://castor.org/ [3]: http://jibx.sourceforge.net/ [4]: https://jaxb.dev.java.net/ [5]: http://xmlbeans.apache.org/ [6]: http://xstream.codehaus.org/
@Matt Dillard - Did setting these to nothing fix your memory leak? VB6 doesn't have a formal garbage collector, more along the lines of what @Konrad Rudolph said. Actually calling unload on your forms seems to me to be the best way to ensure that the main form is cleaned up and that each subform cleans up their actions. I tested this with a blank project and two blank forms. Private Sub Form_Load() Dim frm As Form2 Set frm = New Form2 frm.Show Set frm = Nothing End Sub After running both forms are left visible. setting frm to nothing did well... nothing. After settign frm to nothing, the only handle open to this form is via the reference. Unload Forms(1) Am I seeing the problem correctly? - Josh
Here's my solution, but even more importantly my approach to solving the problem. I approached the problem by - drawing the memory cells and drawing arrows from the destination to the source. - made a table showing the above drawing. - labeling each row in the table with the relative byte address. This showed me the pattern: - let iL be the low nybble (half byte) of a[i] - let iH be the high nybble of a[i] - iH = (i+1)L - iL = (i+2)H This pattern holds for all bytes. Translating into C, this means: a[i] = (iH << 4) OR iL a[i] = ((a[i+1] & 0x0f) << 4) | ((a[i+2] & 0xf0) >> 4) We now make three more observations: - since we carry out the assignments left to right, we don't need to store any values in temporary variables. - we will have a special case for the tail: all 12 bits at the end will be zero. - we must avoid reading undefined memory past the array. since we never read more than a[i+2], this only affects the last two bytes So, we - handle the general case by looping for N-2 bytes and performing the general calculation above - handle the next to last byte by it by setting iH = (i+1)L - handle the last byte by setting it to 0 given a with length N, we get: for (i = 0; i < N - 2; ++i) { a[i] = ((a[i+1] & 0x0f) << 4) | ((a[i+2] & 0xf0) >> 4); } a[N-2] = (a[N-1) & 0x0f) << 4; a[N-1] = 0; And there you have it... the array is shifted left by 12 bits. It could easily be generalized to shifting N bits, noting that there will be M assignment statements where M = number of bits modulo 8, I believe. The loop could be made more efficient on some machines by translating to pointers for (p = a, p2=a+N-2; p != p2; ++p) { *p = ((*(p+1) & 0x0f) << 4) | (((*(p+2) & 0xf0) >> 4); } and by using the largest integer data type supported by the CPU. (I've just typed this in, so now would be a good time for somebody to review the code, especially since bit twiddling is notoriously easy to get wrong.)
Firstly, "ugly no-char boxes" might not be an encoding problem, they might just be a sign you don't have a font installed that can display the glyphs in the page. Most character encoding problems happen when strings are being passed from one system to another. For webapps, this is usually between the browser and the application, between the application and the filesystem and between the application and the database. So you need to check where the mis-encoded data is coming from, what character encoding it has at the source, and what encoding it is being received as. The best way is to send through characters you know the system is having problems with, and examine them at each level of the app. What do they look like inside the app? In the database? When you get them back from the database? When they're displayed in the browser? Sorry to be so general, but the question doesn't give much more to work with.
grep a file, but show several surrounding lines?
|linux|search|logging|grep|
I would like to grep for a string, but show the preceding 5 lines and following 5 lines as well as the matched line. I'm scanning for errors in a logfile, and want to see the context. Any clues for the clueless?
I believe this is changing in Ruby 1.9 such that "asdf"[2] yields "d" rather than the character code
|php|database|ruby|mysql|
I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing this? Some points to note: - Live server is running Linux, Apache 2.2, PHP 5.2 and MySQL 4.1 - Local server is running the same (so using PHP is an option), but the OS is Windows - Local server has Ruby on it (so using Ruby is a valid option) - The live MySQL db *can* accept remote connections from different IPs - I cannot enable replication on the remote server ***Update:*** I've accepted BlaM's answer; it is beautifully simple. Can't believe I didn't think of that. There was one problem, though: I wanted to automate the process, but the proposed solution prompts the user for a password. Here is a slightly modified version of the mysqldump command that passes in the password: <code>mysqldump -u USER --password=MYPASSWORD DATABASE_TO_DUMP -h HOST > backup.sql</code>
Encrypt data from users in web applications
|web-applications|privacy|encryption|
Some web applications, like Google Docs, store data generated by the users. Data that can only be read by its owner. Or maybe not? As far as I know, this data is stored as is in a remote database. So, if anybody with enough privileges in the remote system (a sysadmin, for instance) can lurk my data, my privacy could get compromised. What could be the best solution to store this data encrypted in a remote database and that only the data's owner could decrypt it? How to make this process transparent to the user? (You can't use the user's password as the key to encrypt his data, because you shouldn't know his password).
|encryption|web-applications|privacy|
have you tried to print (Console.WriteLine()) the exception inside the catch clause, and not use visual studio and run your application on console?
I suppose you're using mod_php, right? When a PHP file finishes executing all it's state is killed so there's no way (in PHP code) to do connection pooling. Instead you have to rely on extensions. You can [mysql_pconnect][1] so that your connections won't get closed after the page finishes, that way they get reused in the next request. This might be all that you need but this isn't the same as connection pooling as there's no way to specify the number of connections to maintain opened. Cheers. [1]: http://www.php.net/manual/en/function.mysql-pconnect.php
Hopefully it will be standards compliant and erase a little midget of Internet Explorer's market share - Firefox has ease of use and plugins going for it, but "security" is something non-technical people can understand... which one could hope would make development easier. That's assuming it stays standards compliant and innovates well, of course.
Embed Powerpoint into HTML
This is a quick solution, but I would give each checkbox a unique ID, perhaps with an index hint, like so: <input id="checkbox-0" type="checkbox" /> <input id="checkbox-1" type="checkbox" /> <input id="checkbox-2" type="checkbox" /> <input id="checkbox-3" type="checkbox" /> <input id="checkbox-4" type="checkbox" /> You can then easily obtain the index: $(document).ready(function() { $("input:checkbox").click(function() { index = /checkbox-(\d+)/.exec(this.id)[1]; alert(index); }); });
> here's ya problem: >> 3.2GHz P4 Hyperthreaded, 2GB RAM > Hypertheaded means "doesn't actually have two CPU's, but it fakes it". If you have a process with just one thread running, then you get bad performance. It was a good short-term measure, but compared to having two REAL CPU's, it's a slow hack. I don't think that's the problem at all. The machine is plenty high spec enough to be professional C++ development machine for large projects. I can run Eclipse (which is Java, which is memory hungry and slower than native code) and this is still way faster than VS 2005. I doubled the amount of RAM from 1GB to 2GB. This helps a lot with linking large applications. We also use Incredibuild to accelerate compilation. But it's the VS app that is slow. And if you think I'm a grumpy anti-MS zealot, ask yourself why people aren't buying Vista! :)
> One of the biggest culprits for Visual Studio 2005 slowness is Intellisense. This has been brought up on the MSDN forums again and again and again. What I frequently experience is that Intellisense is working nearly non-stop to "re-index" symbols [...] I agree. I use Visual Assist. It is much better. There is no real way to turn "Intellisense" off either. The only way I have found is to rename the DLL so when you restart VS it is not found. This works and makes VS faster.
As explained in other answers, there are many choices for a modulo operation with negative values. In general different languages (and different machine architectures) will give a different result. According to the [Python reference manual][1], >The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand. is the choice taken by Python. Basically modulo is defined so that this always holds: x == (x/y)*y + (x%y) so it makes sense that (-2)%5 = -2 - (-2/5)*5 = 3 [1]: http://docs.python.org/ref/binary.html
How Would You Create a Pattern from a Date that is Stored in a String?
|java|date|
I have a string that contains the representation of a date. It looks like: **Thu Nov 30 19:00:00 EST 2006** I'm trying to create a Date object using SimpleDateFormat and have 2 problems. 1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor 2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output If anyone knows a solution using API or a custom solution I would greatly appreciate it.
What's the purpose (if any) of "javascript:" in event handler tags?
|javascript|
I'm a self-proclaimed javascript dunce. I can usually "make it work" when needed, but I'm sure I end up doing things less than optimally 99% of the time. I hope to pick a javascript lirbrary/framework and stick with it (i.e. jQuery), but that's not the topic of this question. This is probably due in large part to the fact that anything I know about javascript has come from right-click -> "view source" and quick google searches. In doing this I've sometimes seen the "javascript:" prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)" ?
I'm a self-proclaimed javascript dunce. I can usually "make it work" when needed, but I'm sure I end up doing things less than optimally 99% of the time. I hope to pick a javascript library/framework and stick with it (i.e. jQuery), but that's not the topic of this question. This is probably due in large part to the fact that anything I know about javascript has come from right-click -> "view source" and quick google searches. In doing this I've sometimes seen the "javascript:" prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)" ?
@ Michael DSL=[Domain Specific Language][1] As for what you should learn, that depends on what you're interested in. Are you looking to challenge yourself while staying in the same medium (web-centric applications)? I would suggest learning about Apache and the LAMP (Linux, Apache, MySQL, PHP) architecture and challenge yourself to build a web application that you could readily build with ASP .NET using it. Want to learn something completely different? Try [Prolog][2] or [LISP][3] and see what you can do with those. Maybe you'd like to get into embedded software? Learn C to start. You have a wide variety of ways to improve your skills, and each one has career paths attached to them. (Well, maybe not Prolog, but it's fun!) [1]: http://en.wikipedia.org/wiki/Domain-specific_programming_language [2]: http://www.swi-prolog.org/ [3]: http://common-lisp.net/project/lispbox/
The more languages you know, the more marketable you are. Look and see what the more popular (market for, not fan base) languages are, then add on some cutting edge tech that is not in much use yet, rounded out by general programming skill. With your skill set I would recommend (as far as languages): - Java as a starting point - For .Net add in the .Net MVC (you have LINQ or that would be here also) Language agnostic skills: - Design Patterns (includes the MVC) - Domain Driven Design - Test Driven Design
>>Basically, is there any appreciable difference between: `onchange="javascript: myFunction(this)"` and `onchange="myFunction(this)"` ? Assuming you meant `href="javascript: myFunction(this)"`, yes there is, especially when loading content using the javascript. Using the javascript: pseudo protocol makes the content inaccessible to some humans and all search engines, whereas using a real href and then changing the behaviour of the link using javascript makes the content accessible if javascript is turned off or not available in the particular client.
Why won't .NET deserialize my primitive array from a web service?!
|.net|java|service|primitive|
Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrows of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.
Help! I have an Axis web service that is being consumed by a C# application. Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized. I have tried with other primitives (ints, doubles) and the same thing happens. What do I do? I don't want to change the semantics of my service.
What you probably want is a combination of a queue that contains updates for the linked server and a process that reads data from the queue and updates the remote server. The trigger will then insert a message into the queue as part of the normal transaction. This data will be read by the separate process and used to update the remote server. Logic will needed in the process handle errors (and possibly retries). The queue can be implemented with one or more tables.
We develop a 32-bit application using VS 2005 (2008 soon) and have just purchased some new machines with XP Pro x64 or Vista Business 64-bit on them so that we can take advantage of the extra RAM whilst holding a watching brief on the possibility of doing a 64-bit port if it becomes commercially necessary to do so. We haven't had any problems with doing this other than tweaking some scripts in our development environment etc. Those developers who weren't included in this upgrade cycle still use 32-bit machines, so these should pick up problems when the unit tests and the application test suite are run as a matter of course before a check-in. What we also do is to make sure that we have a set of "test build" machines made up of "typical" configurations (XP/Vista, 2/4/8 cores, etc.) that build and test sets of check-ins - we have various different test suites for stability, performance, etc. - before they are added to the integration area proper. Again, these haven't picked up any problems with running a 32-bit application built on a 64-bit OS. Anyway, as others have already said, I wouldn't expect it to be a problem because it's the compiler that generates the appropriate code for the target OS regardless of the OS that the compiler is actually running on.
If there's no requirement on preserving file type after scaling I'd recommend the following approach. Image src = Image.FromFile("main.gif"); Bitmap b = new Bitmap(100, 129); using (Graphics g = Graphics.FromImage(b)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, 100, 129); } b.Save("scale.png", ImageFormat.Png); The result will have really nice anti aliased edges ![Hosted by imageshack][1] [1]: http://img398.imageshack.us/img398/8110/scalezy6.png
If there's no requirement on preserving file type after scaling I'd recommend the following approach. Image src = Image.FromFile("main.gif"); Bitmap dst = new Bitmap(100, 129); using (Graphics g = Graphics.FromImage(dst)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, 100, 129); } dst.Save("scale.png", ImageFormat.Png); The result will have really nice anti aliased edges ![Hosted by imageshack][1] [1]: http://img398.imageshack.us/img398/8110/scalezy6.png
[@Chris][1], That's just how [] and [,] are defined for the String class. Check out the [String API][2]. [1]: http://stackoverflow.com/questions/29511/ruby-convert-integer-to-string#29513 [2]: http://ruby-doc.org/core/classes/String.html#M000786
Or you can convert the integer to its character value: a[0].chr
Even with rep, there should still be SOME type of capcha, to prevent a malicious script attack.
Here a working solution, using temporary variables: <pre><code> void shift_4bits_left(uint8_t* array, uint16_t size) { int i; uint8_t shifted = 0x00; uint8_t overflow = (0xF0 & array[0]) >> 4; for (i = (size - 1); i >= 0; i--) { shifted = (array[i] << 4) | overflow; overflow = (0xF0 & array[i]) >> 4; array[i] = shifted; } } </code></pre> Call this function 3 times for a 12-bit shift. Mark's solution maybe faster, due to the use of temporary variables.
Here a working solution, using temporary variables: <pre> void shift_4bits_left(uint8_t* array, uint16_t size) { int i; uint8_t shifted = 0x00; uint8_t overflow = (0xF0 & array[0]) >> 4; for (i = (size - 1); i >= 0; i--) { shifted = (array[i] << 4) | overflow; overflow = (0xF0 & array[i]) >> 4; array[i] = shifted; } } </pre> Call this function 3 times for a 12-bit shift. Mark's solution maybe faster, due to the use of temporary variables.
Here a working solution, using temporary variables: void shift_4bits_left(uint8_t* array, uint16_t size) { int i; uint8_t shifted = 0x00; uint8_t overflow = (0xF0 & array[0]) >> 4; for (i = (size - 1); i >= 0; i--) { shifted = (array[i] << 4) | overflow; overflow = (0xF0 & array[i]) >> 4; array[i] = shifted; } } Call this function 3 times for a 12-bit shift. Mike's solution maybe faster, due to the use of temporary variables.