text
stringlengths
8
267k
meta
dict
Q: sudo echo "something" >> /etc/privilegedFile doesn't work This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux. There are a lot of times when I just want to append something to /etc/hosts or a similar file but end up not being able to because both > and >> are not allowed, even with root. Is there someway to make this work without having to su or sudo su into root? A: In bash you can use tee in combination with > /dev/null to keep stdout clean. echo "# comment" | sudo tee -a /etc/hosts > /dev/null A: Some user not know solution when using multiples lines. sudo tee -a /path/file/to/create_with_text > /dev/null <<EOT line 1 line 2 line 3 EOT A: Using Yoo's answer, put this in your ~/.bashrc: sudoe() { [[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1 echo "$1" | sudo tee --append "$2" > /dev/null } Now you can run sudoe 'deb blah # blah' /etc/apt/sources.list Edit: A more complete version which allows you to pipe input in or redirect from a file and includes a -a switch to turn off appending (which is on by default): sudoe() { if ([[ "$1" == "-a" ]] || [[ "$1" == "--no-append" ]]); then shift &>/dev/null || local failed=1 else local append="--append" fi while [[ $failed -ne 1 ]]; do if [[ -t 0 ]]; then text="$1"; shift &>/dev/null || break else text="$(cat <&0)" fi [[ -z "$1" ]] && break echo "$text" | sudo tee $append "$1" >/dev/null; return $? done echo "Usage: $0 [-a|--no-append] [text] <file>"; return 1 } A: The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo. Use something like this, perhaps: sudo sh -c "echo 'something' >> /etc/privilegedFile" A: The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user. Try the following code snippet: sudo sh -c "echo 'something' >> /etc/privilegedfile" A: You can also use sponge from the moreutils package and not need to redirect the output (i.e., no tee noise to hide): echo 'Add this line' | sudo sponge -a privfile A: sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts" A: By using sed -i with $ a , you can append text, containing both variables and special characters, after the last line. For example, adding $NEW_HOST with $NEW_IP to /etc/hosts: sudo sed -i "\$ a $NEW_IP\t\t$NEW_HOST.domain.local\t$NEW_HOST" /etc/hosts sed options explained: * *-i for in-place *$ for last line *a for append A: Doing sudo sh -c "echo >> somefile" should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into. A: I would note, for the curious, that you can also quote a heredoc (for large blocks): sudo bash -c "cat <<EOIPFW >> /etc/ipfw.conf <?xml version=\"1.0\" encoding=\"UTF-8\"?> <plist version=\"1.0\"> <dict> <key>Label</key> <string>com.company.ipfw</string> <key>Program</key> <string>/sbin/ipfw</string> <key>ProgramArguments</key> <array> <string>/sbin/ipfw</string> <string>-q</string> <string>/etc/ipfw.conf</string> </array> <key>RunAtLoad</key> <true></true> </dict> </plist> EOIPFW" A: Use tee --append or tee -a. echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list Make sure to avoid quotes inside quotes. To avoid printing data back to the console, redirect the output to /dev/null. echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null Remember about the (-a/--append) flag! Just tee works like > and will overwrite your file. tee -a works like >> and will write at the end of the file. A: echo 'Hello World' | (sudo tee -a /etc/apt/sources.list) A: How about: echo text | sudo dd status=none of=privilegedfile I want to change /proc/sys/net/ipv4/tcp_rmem. I did: sudo dd status=none of=/proc/sys/net/ipv4/tcp_rmem <<<"4096 131072 1024000" eliminates the echo with a single line document A: Can you change the ownership of the file then change it back after using cat >> to append? sudo chown youruser /etc/hosts sudo cat /downloaded/hostsadditions >> /etc/hosts sudo chown root /etc/hosts Something like this work for you? A: This worked for me: original command echo "export CATALINA_HOME="/opt/tomcat9"" >> /etc/environment Working command echo "export CATALINA_HOME="/opt/tomcat9"" |sudo tee /etc/environment
{ "language": "en", "url": "https://stackoverflow.com/questions/84882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "694" }
Q: JMS (esp Tibco EMS) can I have an environment with in a message broker I have a message broker with some topics, and some set of applications running on it. Now I want to run a new set of the same applications (say for QA environment) on the same topics (on the same broker, if I could). What is the best way to do this. Creating a new broker and or creating a new set of topics is cumbersome, as our environments are under tight bureaucracy. A: AFAIK EMS does not support anything like what you suggest. There are a few options to get what you are looking for. Having independent EMS servers would be the ideal solution. This would allow your non-production environment to have some hickups without causing problems in your production environment. Using the same server you can have an environment-specific prefix tacked onto all the queue/topic names. There would need to be some application level setting for which prefix to use (qa, dev, test, prod, ...). This would make for pretty good isolation of the environments, but would probably not work too well if any of the environments are really heavily loaded. For topics you can use some JMS header property and messages subscriptions to determine which environment to route them to. I would not recommend this as it would be pretty easy to screw it up and corrupt both environments. A: I'd recommend against using the same middleware servers for both production and QA at the same time (particularly message brokers) as in QA you will probably want to do load & soak tests which you don't want affecting production. As John mentions, using a separate server would be the simplest approach. Its kinda bizarre why there's such tight bureaucracy over replicating the same set of topics in a QA environment; can't you just take a dump of the production installation of EMS? FWIW with some message brokers, the creation of topics and queues is kinda trivial. e.g. in Apache ActiveMQ application developers choose what queue and topic names they want to use - then you connect to a broker for the right environment and it just works (though you can add security to disable certain users from creating topics/queues if you want added bureaucracy :). As an aside; I've always found it quite comical how in enterprise environments there are quite draconian policies about what queue/topic names you are allowed to use - yet in web applications developers are free to use whatever URIs they want in their applications. After all in both cases they are just logical names - the middleware should be able to just work and support auditing either way :) A: this requirement can be achieved by having as a qualifier in the message topics/queues or "subjects", so you can segregate the environment mode from DEV to TEST on the same server.Keep in mind that, flow of messages across environments are not recommended by using same EMS Server. This particular requirement should be addressed in "Subject Naming Conventions", which is a classic task in SOA Architecture defining message formats, message excahange patterns and design of subjects etc. For eg, your subject can be ..... where would be DEV or TEST or UAT etc A: I would not use the same servers for Multiple environments for the same app, you could have cross talk where messages for one environment end up in the other. Duplicating Queues/Topics are not the complicated and it should be a Quick thing to reconfigure an app. Other concepts you might want to know about are Bridges (Where messages to a Topic/Queue can be copied to another) I have used this to have the same message from one topic be copied automatically to 2 different queues. I know you can use a durable subscriber on a topic but that's kind of what a queue is for(IMHO) Message Selecting : The ability to only retrieve messages if they have a specific Header on it. You can also do message selecting on a bridge.
{ "language": "en", "url": "https://stackoverflow.com/questions/84884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JDEdwards XMLInterop Wondering if anybody out there has any success in using the JDEdwards XMLInterop functionality. I've been using it for a while (with a simple PInvoke, will post code later). I'm looking to see if there's a better and/or more robust way. Thanks. A: As promised, here is the code for integrating with JDEdewards using XML. It's a webservice, but could be used as you see fit. namespace YourNameSpace { /// <summary> /// This webservice allows you to submit JDE XML CallObject requests via a c# webservice /// </summary> [WebService(Namespace = "http://WebSite.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class JdeBFService : System.Web.Services.WebService { private string _strServerName; private UInt16 _intServerPort; private Int16 _intServerTimeout; public JdeBFService() { // Load JDE ServerName, Port, & Connection Timeout from the Web.config file. _strServerName = ConfigurationManager.AppSettings["JdeServerName"]; _intServerPort = Convert.ToUInt16(ConfigurationManager.AppSettings["JdePort"], CultureInfo.InvariantCulture); _intServerTimeout = Convert.ToInt16(ConfigurationManager.AppSettings["JdeTimeout"], CultureInfo.InvariantCulture); } /// <summary> /// This webmethod allows you to submit an XML formatted jdeRequest document /// that will call any Master Business Function referenced in the XML document /// and return a response. /// </summary> /// <param name="Xml"> The jdeRequest XML document </param> [WebMethod] public XmlDocument JdeXmlRequest(XmlDocument xmlInput) { try { string outputXml = string.Empty; outputXml = NativeMethods.JdeXmlRequest(xmlInput, _strServerName, _intServerPort, _intServerTimeout); XmlDocument outputXmlDoc = new XmlDocument(); outputXmlDoc.LoadXml(outputXml); return outputXmlDoc; } catch (Exception ex) { ErrorReporting.SendEmail(ex); throw; } } } /// <summary> /// This interop class uses pinvoke to call the JDE C++ dll. It only has one static function. /// </summary> /// <remarks> /// This class calls the xmlinterop.dll which can be found in the B9/system/bin32 directory. /// Copy the dll to the webservice project's /bin directory before running the project. /// </remarks> internal static class NativeMethods { [DllImport("xmlinterop.dll", EntryPoint = "_jdeXMLRequest@20", CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.StdCall, SetLastError = true)] private static extern IntPtr jdeXMLRequest([MarshalAs(UnmanagedType.LPWStr)] StringBuilder server, UInt16 port, Int32 timeout, [MarshalAs(UnmanagedType.LPStr)] StringBuilder buf, Int32 length); public static string JdeXmlRequest(XmlDocument xmlInput, string strServerName, UInt16 intPort, Int32 intTimeout) { StringBuilder sbServerName = new StringBuilder(strServerName); StringBuilder sbXML = new StringBuilder(); XmlWriter xWriter = XmlWriter.Create(sbXML); xmlInput.WriteTo(xWriter); xWriter.Close(); string result = Marshal.PtrToStringAnsi(jdeXMLRequest(sbServerName, intPort, intTimeout, sbXML, sbXML.Length)); return result; } } } You have to send it messages like the following one: <jdeRequest type='callmethod' user='USER' pwd='PWD' environment='ENV'> <callMethod name='GetEffectiveAddress' app='JdeWebRequest' runOnError='no'> <params> <param name='mnAddressNumber'>10000</param> </params> </callMethod> </jdeRequest> A: To anyone trying to do this, there are some dependencies to xmlinterop.dll. you'll find these files on the fat client here ->c:\E910\system\bin32 this will create a 'thin client' PSThread.dll icudt32.dll icui18n.dll icuuc.dll jdel.dll jdeunicode.dll libeay32.dll msvcp71.dll ssleay32.dll ustdio.dll xmlinterop.dll A: I changed our JDE web service to use XML Interop after seeing this code, and we haven't had any stability problems since. Previously we were using the COM Connector, which exhibited regular communication failures (possibly a connection pooling issue?) and was a pain to install and configure correctly. We did have issues when we attempted to use transactions, but if you're doing simple single business function calls this shouldn't be an problem. Update: To elaborate on the transaction issues - if you're attempting to keep a transaction alive over multiple calls, AND the JDE application server is handling a modest number of concurrent calls, the xmlinterop calls start returning an 'XML response failed' message and the DB transaction is left open with no way to commit or rollback. It's possible tweaking the number of kernels might solve this, but personally, I'd always try to complete the transaction in a single call.
{ "language": "en", "url": "https://stackoverflow.com/questions/84885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the easiest or fastest way to make CSS render the same in all browsers Making a web page display correctly im all major browsers today is a very time consuming task. Is there a easy way to make a CSS style that looks identical in every browser? Or at least do you have some tips to make this work easier? A: Organize your work flow in the following way and it'll reduce a lot of time wasting. * *Make sure you declare a doc-type. *Use one of the reset methods others have mentioned here. *Work on your structure *Avoid using width and padding on the same element where you can. *Always think of reducing unneeded HTML and css rather than adding all the time. *Try not to use margin left and right when floating elements. If you stick to those items, a lot of the most common issues will not appear. PS One item I forgot to mention was make use of the validators over at W3. A: I've always created a basic CSS style sheet which works in W3C Fully compliant browsers like firefox and then created alternative browser specific style sheets to fix any styling issues in other browsers, i.e. IE6, IE7 etc. You can use the following code within the HTML to select appropriate IE style sheets. <!--[if lte IE 6]> <link href="/css/eqtr_ie6.css" rel="stylesheet" type="text/css" /> <![endif]--> You can also use online websites such as browsershots to view your site in different browsers. A: It is time consuming at first, especially if you are stilling learning the ropes of DIV+CSS. However after you've done enough practice and met enough of problems and got them all solved, you will have the knowledge of what WORKS and what DOESN'T WORK. It is then you know how to write the most compatible style possible in the first place, thus saving all the time in degugging and rarely have any problems with any of the major modern browsers: IE6, IE7, FF2, FF3, Opera 9, Safari 3 Win / Mac. Yes, it is possible and as easy as it can get. Practice and conquer them one by one, then you know how to do things right in the first attempt. Well the only baffling monster should be IE6 I guess. It's inbrowser. Other than that, ff2, ff3, opera 9, safari win / mac, ie7, ie8 are relatively similar in the rendering engine, at least with much less bugs than it has with IE6. I have a few best practices for you (one who has just begun their trip in CSS) in coding to get the max CSS compatibility: * *Use a reset first. It clears your mind and makes sure each step of your job. *Don't use padding (left and right) and width on the same element unless you know well how that'll work out. *If an element is floated, give its parent overflow:hidden and height: 1% if the parent does not already have a height. *Don't give an element both margin-top or margin-bottom but only margin-top or margin-bottom. Because margins of adjacent elements collapse into one another, making the positioning somewhat unpredictable for novices. *If an element is floated, give it display:inline. *Don't rely on z-index unless your scripting needs it. *If anything weird happens in IE6, use height:1% on that element. According to my experiences, these are things that will really really help you in solving potential problems. Use them and they eliminate your chances of stumbling upon any time consuming problem by 80%. Actually there are more trivial tips than these when dealing with specific tags but let's call it a day. A: The Yahoo css foundation will help. To standardise formatting you will want reset and base. A: First of all you could try a reset, like some other people mentioned here, you can do a quick margin and padding reset with this piece of css: *{margin: 0; padding: 0} When you design your css make sure you're using a modern, standars compliant browser (personally I would recommend firefox 3 which has an excellent web developer toolbar, with which you can edit css from within your browser). Doing this will certainly make your site look ok in all the new browsers. Most of the layout problems you'll have will probably be caused by Internet Explorer's wrong interpretation of the box model, you can avoid this by never setting a width and margin or padding at the same time. This might seem annoying but it's not, just apply the padding or margin to the content which is inside your element which has a width set. Of course more problems exist but this is probably the most common and annoying one, for more specific issues you can always try google. Also, lately I'm considering to ignore IE6 and older browsers if my site's audience allows it, on a web design site you'll never find anyone using IE6, right? Of course this is not possible often since many (crazy ;)) people are still using IE6. Also, if you need to test your site browsershots is a free way to do it quickly. A: Make sure to include the proper DOCTYPE. I still see people regularly coping with box model issues because they forgot to include a doctype. Without the proper doctype Internet Explorer renders in "quirks mode", and so do other browsers to a lesser extent. If you include the proper doctype, browsers switch to "standard mode" and behave very similar to eachother. Other then that, if you do this for a living you will rapidly pick up and remember those subtle corner cases where IE interprets things slightly different from Firefox, etc. With some experience it is entirely possible to design the entire page in your favourite browser and only make very tiny tweaks to the CSS to make it render almost pixel perfect in other browsers. A: I agree with all the "reset" suggestions and the "grid" framework suggestions, but I did want to add a bit of advice: The goal of identical in every browser is, in practical terms, unachievable because you cannot control the client. Case in point: fonts. You declare your font styles in CSS but some Linux machines, some Macs, some mobile browsers -- will not have the font you specified. This variation leads to differing text lengths and wrapping. Then there's the variance of browser versions and operating systems running each; how different browsers implement zoom features; and the text size can be adjusted by the end user. Identical rendering is simply an unachievable goal. But take heart! This is the "art" part of CSS: Being able to be flexible in your design such that variances between browsers, operating systems, and end-user adjustments are handled elegantly. Don't strive for identical rendering -- you should strive for brand consistency + appropriate experience + flexibility. A: Test your CSS on all the browsers as you go. It's awful to get it pixel perfect in your pet browser only to find that it's way off in other browsers. Taking this approach will ease you into an understanding of what will work on all the major browsers. A: I've had success using the Eric Meyer CSS reset available here. It basically overrides a bunch of browser CSS styles that are default. Having said that, there are still a lot of differences (probably some of the ones that are troubling you like box model differences, etc. In that case, it might be better to use Blueprint to handle most of your css. A: Using CSS Reset will give everything the same starting point, but won't do much to help with the changes you make beyond that starting point. I can't say there's really any easy way. One solution is to stick to a limited set of CSS that you know works well in all browser you want to support. You may not be able to do a lot of the fancier CSS stuff, but your CSS debugging time should come down considerably. A: You might also look at a framework for css like Blueprint or css-boilerplate or the yui grids framework. Usually, these frameworks set you up with a standard set of css class definitions that you can apply to elements to lay them out in a specific and defined way. A: If it needs to be pixel-perfect, then you'll need to use px in your stylesheets. Use a css reset stylesheet, then size everything based on pixels. To ensure that your css is rendering correctly in different browsers, you might find a service like BrowserShots useful, however, I think you'll find it very difficult to get absolute consistency across all browsers. My personal preference is to use correct markup and css, leave out any browserhacks, and design layouts to degrade gracefully. A: Conforming to a strict doctype will take care of many of the differences as well. Also, I generally add a <div> tag to encase everything within the body, because I've noticed a difference in how firefox vs ie handle the body tag as a top level element. A: I like developing against Firefox first, often using Yahoo's YUI for reset (and grids for basic structure of the page), and using IE conditional directives to override formats that IE, in all its–a-hem–wisdom, handles differently. index.html <head> <link rel="stylesheet" type="text/css" media="all" href="styles/yui/grids/base-min.css" /> <link rel="stylesheet" type="text/css" media="all" href="styles/yui/grids/grids.css" /> <link rel="stylesheet" type="text/css" media="all" href="styles/screen.foo.css" /> <link rel="stylesheet" type="text/css" media="print" href="styles/print.foo.css" /> <!--[if gt IE 5]> <link rel="stylesheet" type="text/css" href="styles/ie.screen.foo.css" /> <![endif]--> </head> A: Develop for Firefox first. You can test in other browsers but don't worry about fixes until it works just how you want it in Firefox. Then move on to the other standards-based browsers, namely Safari and Opera. If you've written good HTML and CSS it shouldn't require much work in these browsers. Then move on to the beast of the lot, IE. Use conditional comments to target specific IE versions. IE 7 should be fairly easy, for IE 6 you may find you have to sacrifice certain parts of the design to get it to work easily. This is OK, IE 6 is on the way out so don't worry if you don't fully support it. Transparent PNGs are usually the biggest problem, AlphaImageLoader just doesn't do the trick in every situation. As previously mentioned, a CSS reset like Eric Meyer's is a good starting point, use it to build your own reset based on your needs. Other than that the answer is simple: there is no silver bullet. A: Do websites need to look exactly the same in every browser? Apart from that, I guess practice makes perfect. And read about everything you can find about the potential issues you can stumble upon. Using reset-files, correct doctypes, validators and frameworks might help you to a certain extent, but in the end you are in control of the code and only you know exactly what you want it to look like. The code might be valid and the browser might do exactly what you've told it to, and it still does not look like what you want it to. The more you use CSS for layout purposes, the more problems you'll encounter, the more problems you'll find a way around and the more you'll learn. After quite a few years of making layouts entirely with structured, semantic HTML and neat'n'tidy CSS I seldom have to spend a lot of time correcting flaws in one or another browser. A: * *Use a reset snippet *Develop with web standards *Validate your markup and CSS *Don't use margin and padding on the same parts of an element *Use IE conditionals *Test in all the browsers you want to support *Understand that nothings going to be perfect, but you can get pretty close. A: try using a css reset like the eric meyer reset or the YUI reset. will help but no easy or perfect way to make things look identical in every browser A: The Yahoo User Interface (YUI) has a CSS Reset implementation which seeks to form a common baseline across all browsers. This should get you pretty close. A: This is really a hard question to answer -- all browsers? Does this mean all versions? Mobile browsers? Just the "mainline" ones (opera, firefox, ie and safari)? You won't find even full compliance on CSS level 1 stuff, so there are going to be some tweaks you're going to have to make. In my experience opera, firefox and safari all behave similarly when it comes to basic stuff (positioning, floats, divs, etc) and it's just IE you'll have to tweak for. You could also use a tested CSS library or framework like yahoo grids (http://developer.yahoo.com/yui/grids/) or a programmatic interface like google's web toolkit (http://code.google.com/webtoolkit/). A: I tend to find that identical looking CSS comes about if I use floats to layout the page in boxes. The flow model works as you think it should, and they're faithfully rendered in all major browsers. I know some would tell me that the use of a lot of floats is wrong, but it works surprisingly well. A: At the basis there is no guarantee that such a thing will ever work perfectly. As long as the browser developers find ways to do their own thing rather than the 'standard' way of doing things, you will have differences. I've had positive results using the Yahoo User Interface Base CSS, but in the end even that couldn't cope with the more complex items that should be possible with CSS. In the end I went for a less-than-perfect solution and simply made my framework check if I had set up browser-specific stylesheets. Here's a PHP snippet to illustrate. Sorry for the language-specific solution, but I guess the idea is clear enough to implement in different languages: $sHTML .= "\t\t<LINK rel=\"stylesheet\" type=\"text/css\" href=\"".$sURLCSS.$sStyle."\" />\n"; if (file_exists($sPathCSS.$sFileStyle."_".BROWSER_AGENT.".".$sExtension)) $sHTML .= "\t\t<LINK rel=\"stylesheet\" type=\"text/css\" href=\"".$sURLCSS.$sFileStyle."_".BROWSER_AGENT.".".$sExtension."\" />\n"; if (file_exists($sPathCSS.$sFileStyle."_".BROWSER_AGENT."_".BROWSER_VERSION.".".$sExtension)) $sHTML .= "\t\t<LINK rel=\"stylesheet\" type=\"text/css\" href=\"".$sURLCSS.$sFileStyle."_".BROWSER_AGENT."_".BROWSER_VERSION.".".$sExtension."\" />\n"; With no missing files, no unrecognized tags or other code that might choke some browsers, the pages from the framework render as we want them to render in all browsers requested by our clients. More importantly, they do so without producing errors (i.e. an empty Error Console in FireFox) which makes debugging when you actually do run into an error a lot easier. A: I'd recommend taking a look at Blueprint and 960 Grid System. Besides doing resets and including CSS fixes for Internet Explorer, they'll both give you an easy to work with design grid that will take care of a lot of the tedious tweaking when building CSS-based layouts. A: I usually develop against the W3C CSS validator, then verify things look the way I want them to in the respective browsers. Validating goes a long way toward consistent behavior. Sometimes I'll strip the page down to only styles that validate and show properly in the major browsers I'm targeting, sometimes I'll supplement it with browser-specific tweaks as other posters have mentioned. A: css frameworks certainly help, although they can easily be heavy due to a heap of styles that you won't need or use. check out Targeting IE Using Conditional Comments and Just One Stylesheet over at Position is Everything for a great technique to feed IE version-specific styles without using CSS hacks; this allows you to keep style rules together by selector rather than by browser. A: You're asking the wrong question, because here's the only way to answer that: <!DOCTYPE html> <html> <head> <style>* { background: #fff }</style> </head> <body></body> </html> Not much of an answer, is it? :) Everyone else is right here - make your CSS work in every browser, don't try to make it look the same. You can't. A: Applying the Design Tinfoil Hat CSS: *{display:none}
{ "language": "en", "url": "https://stackoverflow.com/questions/84912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: RIghtFax Esoteric error message in .NET 1.1 I have a problem with RightFax component Interop.RFCOMAPILib.dll version 1.0.0.0 , using VB .NET 1.1. It works in several environments, but not in Production. It returns this message in the exception - "?" - . How can I solve it? I couldn't find any solution in manuals or on the internet. A: remembers rightfax and lack of information on the internet. this is no answer to your question but one could switch to the builtin windows 2003 fax server with dedicated isdn fax board, has automatic mailforwarding
{ "language": "en", "url": "https://stackoverflow.com/questions/84916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get the full path to a Perl script that is executing? I have Perl script and need to determine the full path and filename of the script during execution. I discovered that depending on how you call the script $0 varies and sometimes contains the fullpath+filename and sometimes just filename. Because the working directory can vary as well I can't think of a way to reliably get the fullpath+filename of the script. Anyone got a solution? A: Getting the absolute path to $0 or __FILE__ is what you want. The only trouble is if someone did a chdir() and the $0 was relative -- then you need to get the absolute path in a BEGIN{} to prevent any surprises. FindBin tries to go one better and grovel around in the $PATH for something matching the basename($0), but there are times when that does far-too-surprising things (specifically: when the file is "right in front of you" in the cwd.) File::Fu has File::Fu->program_name and File::Fu->program_dir for this. A: Some short background: Unfortunately the Unix API doesn't provide a running program with the full path to the executable. In fact, the program executing yours can provide whatever it wants in the field that normally tells your program what it is. There are, as all the answers point out, various heuristics for finding likely candidates. But nothing short of searching the entire filesystem will always work, and even that will fail if the executable is moved or removed. But you don't want the Perl executable, which is what's actually running, but the script it is executing. And Perl needs to know where the script is to find it. It stores this in __FILE__, while $0 is from the Unix API. This can still be a relative path, so take Mark's suggestion and canonize it with File::Spec->rel2abs( __FILE__ ); A: Have you tried: $ENV{'SCRIPT_NAME'} or use FindBin '$Bin'; print "The script is located in $Bin.\n"; It really depends on how it's being called and if it's CGI or being run from a normal shell, etc. A: In order to get the path to the directory containing my script I used a combination of answers given already. #!/usr/bin/perl use strict; use warnings; use File::Spec; use File::Basename; my $dir = dirname(File::Spec->rel2abs(__FILE__)); A: use File::Spec; File::Spec->rel2abs( __FILE__ ); http://perldoc.perl.org/File/Spec/Unix.html A: There are a few ways: * *$0 is the currently executing script as provided by POSIX, relative to the current working directory if the script is at or below the CWD *Additionally, cwd(), getcwd() and abs_path() are provided by the Cwd module and tell you where the script is being run from *The module FindBin provides the $Bin & $RealBin variables that usually are the path to the executing script; this module also provides $Script & $RealScript that are the name of the script *__FILE__ is the actual file that the Perl interpreter deals with during compilation, including its full path. I've seen the first three ($0, the Cwd module and the FindBin module) fail under mod_perl spectacularly, producing worthless output such as '.' or an empty string. In such environments, I use __FILE__ and get the path from that using the File::Basename module: use File::Basename; my $dirname = dirname(__FILE__); A: perlfaq8 answers a very similar question with using the rel2abs() function on $0. That function can be found in File::Spec. A: There's no need to use external modules, with just one line you can have the file name and relative path. If you are using modules and need to apply a path relative to the script directory, the relative path is enough. $0 =~ m/(.+)[\/\\](.+)$/; print "full path: $1, file name: $2\n"; A: I think the module you're looking for is FindBin: #!/usr/bin/perl use FindBin; $0 = "stealth"; print "The actual path to this is: $FindBin::Bin/$FindBin::Script\n"; A: $0 is typically the name of your program, so how about this? use Cwd 'abs_path'; print abs_path($0); Seems to me that this should work as abs_path knows if you are using a relative or absolute path. Update For anyone reading this years later, you should read Drew's answer. It's much better than mine. A: You could use FindBin, Cwd, File::Basename, or a combination of them. They're all in the base distribution of Perl IIRC. I used Cwd in the past: Cwd: use Cwd qw(abs_path); my $path = abs_path($0); print "$path\n"; A: Are you looking for this?: my $thisfile = $1 if $0 =~ /\\([^\\]*)$|\/([^\/]*)$/; print "You are running $thisfile now.\n"; The output will look like this: You are running MyFileName.pl now. It works on both Windows and Unix. A: #!/usr/bin/perl -w use strict; my $path = $0; $path =~ s/\.\///g; if ($path =~ /\//){ if ($path =~ /^\//){ $path =~ /^((\/[^\/]+){1,}\/)[^\/]+$/; $path = $1; } else { $path =~ /^(([^\/]+\/){1,})[^\/]+$/; my $path_b = $1; my $path_a = `pwd`; chop($path_a); $path = $path_a."/".$path_b; } } else{ $path = `pwd`; chop($path); $path.="/"; } $path =~ s/\/\//\//g; print "\n$path\n"; :DD A: The problem with just using dirname(__FILE__) is that it doesn't follow symlinks. I had to use this for my script to follow the symlink to the actual file location. use File::Basename; my $script_dir = undef; if(-l __FILE__) { $script_dir = dirname(readlink(__FILE__)); } else { $script_dir = dirname(__FILE__); } A: use strict ; use warnings ; use Cwd 'abs_path'; sub ResolveMyProductBaseDir { # Start - Resolve the ProductBaseDir #resolve the run dir where this scripts is placed my $ScriptAbsolutPath = abs_path($0) ; #debug print "\$ScriptAbsolutPath is $ScriptAbsolutPath \n" ; $ScriptAbsolutPath =~ m/^(.*)(\\|\/)(.*)\.([a-z]*)/; $RunDir = $1 ; #debug print "\$1 is $1 \n" ; #change the \'s to /'s if we are on Windows $RunDir =~s/\\/\//gi ; my @DirParts = split ('/' , $RunDir) ; for (my $count=0; $count < 4; $count++) { pop @DirParts ; } my $ProductBaseDir = join ( '/' , @DirParts ) ; # Stop - Resolve the ProductBaseDir #debug print "ResolveMyProductBaseDir $ProductBaseDir is $ProductBaseDir \n" ; return $ProductBaseDir ; } #eof sub A: The problem with __FILE__ is that it will print the core module ".pm" path not necessarily the ".cgi" or ".pl" script path that is running. I guess it depends on what your goal is. It seems to me that Cwd just needs to be updated for mod_perl. Here is my suggestion: my $path; use File::Basename; my $file = basename($ENV{SCRIPT_NAME}); if (exists $ENV{MOD_PERL} && ($ENV{MOD_PERL_API_VERSION} < 2)) { if ($^O =~/Win/) { $path = `echo %cd%`; chop $path; $path =~ s!\\!/!g; $path .= $ENV{SCRIPT_NAME}; } else { $path = `pwd`; $path .= "/$file"; } # add support for other operating systems } else { require Cwd; $path = Cwd::getcwd()."/$file"; } print $path; Please add any suggestions. A: Without any external modules, valid for shell, works well even with '../': my $self = `pwd`; chomp $self; $self .='/'.$1 if $0 =~/([^\/]*)$/; #keep the filename only print "self=$self\n"; test: $ /my/temp/Host$ perl ./host-mod.pl self=/my/temp/Host/host-mod.pl $ /my/temp/Host$ ./host-mod.pl self=/my/temp/Host/host-mod.pl $ /my/temp/Host$ ../Host/./host-mod.pl self=/my/temp/Host/host-mod.pl A: All the library-free solutions don't actually work for more than a few ways to write a path (think ../ or /bla/x/../bin/./x/../ etc. My solution looks like below. I have one quirk: I don't have the faintest idea why I have to run the replacements twice. If I don't, I get a spurious "./" or "../". Apart from that, it seems quite robust to me. my $callpath = $0; my $pwd = `pwd`; chomp($pwd); # if called relative -> add pwd in front if ($callpath !~ /^\//) { $callpath = $pwd."/".$callpath; } # do the cleanup $callpath =~ s!^\./!!; # starts with ./ -> drop $callpath =~ s!/\./!/!g; # /./ -> / $callpath =~ s!/\./!/!g; # /./ -> / (twice) $callpath =~ s!/[^/]+/\.\./!/!g; # /xxx/../ -> / $callpath =~ s!/[^/]+/\.\./!/!g; # /xxx/../ -> / (twice) my $calldir = $callpath; $calldir =~ s/(.*)\/([^\/]+)/$1/; A: None of the "top" answers were right for me. The problem with using FindBin '$Bin' or Cwd is that they return absolute path with all symbolic links resolved. In my case I needed the exact path with symbolic links present - the same as returns Unix command "pwd" and not "pwd -P". The following function provides the solution: sub get_script_full_path { use File::Basename; use File::Spec; use Cwd qw(chdir cwd); my $curr_dir = cwd(); chdir(dirname($0)); my $dir = $ENV{PWD}; chdir( $curr_dir); return File::Spec->catfile($dir, basename($0)); } A: On Windows using dirname and abs_path together worked best for me. use File::Basename; use Cwd qw(abs_path); # absolute path of the directory containing the executing script my $abs_dirname = dirname(abs_path($0)); print "\ndirname(abs_path(\$0)) -> $abs_dirname\n"; here's why: # this gives the answer I want in relative path form, not absolute my $rel_dirname = dirname(__FILE__); print "dirname(__FILE__) -> $rel_dirname\n"; # this gives the slightly wrong answer, but in the form I want my $full_filepath = abs_path($0); print "abs_path(\$0) -> $full_filepath\n"; A: use File::Basename; use Cwd 'abs_path'; print dirname(abs_path(__FILE__)) ; Drew's answer gave me: '.' $ cat >testdirname use File::Basename; print dirname(__FILE__); $ perl testdirname .$ perl -v This is perl 5, version 28, subversion 1 (v5.28.1) built for x86_64-linux-gnu-thread-multi][1] A: On *nix, you likely have the "whereis" command, which searches your $PATH looking for a binary with a given name. If $0 doesn't contain the full path name, running whereis $scriptname and saving the result into a variable should tell you where the script is located. A: What's wrong with $^X ? #!/usr/bin/env perl<br> print "This is executed by $^X\n"; Would give you the full path to the Perl binary being used. Evert
{ "language": "en", "url": "https://stackoverflow.com/questions/84932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "181" }
Q: How do you disable a SharePoint webpart temporarily? Can this be done by setting a property? I'd prefer that approach then to remove all security before re-adding it. (As this may have other consequences.) Another option I can think of is to replace the particular webpart dll with a temporary one, and restart the .net process, but that's not an approach I like at all. What other options are there? AM I missing something obvious? What i'm trying to do is find a way to disable a webpart while we update the underlying database schema it's using, for example. So we'd ideally like to disable a specific webpart for all users, whether it's on a mysite, or a community site, make the required changes and then re-enable it. Thus decreasing the downtime for users. Whatever the solution is, we need to be able to do it across multiple front end servers, on potentially two farms easily. Thanks for your help. A: Go to Site Actions -> Edit Page You get all the web parts edited. Click on the "Edit" dropdown of the Web Part you want to disable and choose "Close". The web part disappears, but don't fear! It's not gone for good! To have it back: -> click to Add a new Web Part -> Advanced Web Part Gallery and Options. The very first option you have is to choose among "Closed Web Parts". When clicking on that link, you will have displayed a list of all the web parts you had closed. Just add the one you want back! A: In the web.config, you can set safe="false" for the SafeControl tag for the webpart. This will cause the web part to render an error message until you set it back to true. http://technet.microsoft.com/en-us/library/cc287909.aspx A: write code to set a value in property bag of the site, set the value through the code and in page lode of the web part check for the value of the property bag if set show the content else just skip. hope you understood if not let me know i will make it clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/84964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual Studio Intellisense, c#, no code behind If I open a file in Design View (web form), I get intellisense for my display code, but not my script code.. If I open with source code editor I, occasionally, get intellisense within the script tags. Anyone know how to get intellisense working all of the time for all of my code? Been living with this one for a long time. A: What version are you using? Design view is for human-readable elements, you wouldn't be editing code there and therefore wouldn't need intellisense. If you are not using code-behind, you should only have one <script runat="server"> tag on the page, and you would edit this in Source view. To enable intellisense, add the following on the first line: <%@ Page Language="C#" %> If you change it, the tag will be underlined and it will say that you need to close the file and reopen it. If you are in VS 2008, JavaScript intellisense will be available to you as well. Make sure you specify the language in the <script> tag. A: VS2008. So far doing a re-install seems to be the best advice. I am using the <%@ Page Language="C#" MasterPageFile="~/common/masterpages/MasterPage.master" %>. When I say design-view I mean that I right+click on the file and choose "view designer" - this gives me access to the toolbox and tabs for designer,split, and code-view (which is the view I primarily work in). In that mode, all of my <asp: tags get intellisense, but then I lose all intellisense within my <script> tags. I've never been able to have intellisense working both within the <script> tags and within my form. I should say that when we create a website, we don't do it through file>new>website.. I mention this because I wonder if VS might configure a website differently when creating it that way vs. pointing VS to an existing set of directories which contain our website. A: Some service packs have broken Intellisense and in the past I have had to either reinstall the product or repair. Try repair first! A: I'm not sure if it helps, but I've been working on some code recently which uses a bunch of projects compiled using NMake. For those, there's an option if you right-click on the project and select the NMake option (I guess you might have a web form option in there?). I found intellisense often wouldn't pick everything up unless I set the right include directories: * *Right-click on the project. *Select NMake (or whatever it is you 'compile' the form with) from the tree of options on the left of the dialog. *In the pane on the right you'll hopefully see a bunch of options under an 'intellisense' listing. *Make sure the files you're interested in intellisensing are in a directory which is listed in the 'Include search paths' option.
{ "language": "en", "url": "https://stackoverflow.com/questions/84968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Array Formulas in Conditional Formatting of Excel XML Spreadsheet files? Excel usually treats Conditional Formatting formulas as if they are array formulas, except when loading them from an Excel 2002/2003 XML Spreadsheet file. This is only an issue with the Excel 2002/2003 XML Spreadsheet format... the native Excel format works fine, as does the newer Excel 2007 XML format (xlsx). After loading the spreadsheet, it is possible to make it work correctly by selecting the formatted range, going to the Conditional Formatting dialog, and clicking OK--but this only fixes the problem for the session. Test case: Enter the following into a new sheet: A B C 1 N N N 2 x x x 3 x x x Create this conditional format formula on cells A1:C1 (your choice of pretty colors for the format): =(SUM(($A1:$C1="N")*($A$2:$C$2=A$3))>0) This is an array formula that activates for A1, B1, and C1 whenever any of them has an "N" and the cell in row 2 below the "N" is equal to the cell in row 3 of the current column. (This has been simplified from a real-world business spreadsheet. Sorry for the complexity of the test case, I am trying to find an easier test case to present here.) And it works... you can alter the N's or the x's in any way you want and the formatting works just fine. Save this as an XML Spreadsheet. Close Excel, and re-open the file. Formatting is now broken. Now, you can only activate conditional formatting if A1 is an "N" and A2 is the same as A3, B3, or C3. The values of B1, B2, C1, and C2 have no effect on the formatting. Now, select A1:C1 and look at the conditional formatting formula. Exactly the same as before. Hit OK. Conditional formatting starts working again, and will work during the entire session the file is open. Workarounds considered: * *Providing the file in native (BIFF) Excel format. Not an option, these spreadsheets are generated on the fly by a web server and this is only one of dozens of types of workbooks generated dynamically by our system. *Providing the file in the Excel 2007 native XML format (xlsx). Not an option, current user base does not have Office 2007 or the compatibility plug-in. *Asking users to select the range, enter the Conditional Formatting dialog, and hitting ok. Not an option in this case, unsophisticated users. *Asking users to open the XML spreadsheet, save as native XLS, close, and re-open the XLS file. This does not work! Formatting remains broken in the native XLS format if it was loaded broken from an XML file. If (3) above is performed before saving, the XLS file will work properly. I ended up rewriting the conditional formatting to not use array formulas. So I guess this is "answered" to some degree, but it's still an undocumented, if obscure, bug in Excel 2002/2003's handling of XML files. A: I tried to recreate the problem you describe. Here is what I found. * *Could consistently recreate the problem using Excel 2003 on Windows XP when saving as an XML spreadsheet. *Could not reproduce the problem using Excel 2003 on Windows XP when saving as a standard xls spreadsheet. *Could not reproduce the problem using Excel 2007 on Windows Vista when saving the file in the native xlsx format. *Could not reproduce the problem using Excel 2007 on Windows Vista when saving the file in the Excel 97-2003 xls format. (Note: All instances of Excel and Windows are current with all Windows updates.) I also added a simple conditional formatting formula to each test. In every case, it worked as expected after saving the file, closing Excel, and reopening the file. So the answer seems to be to use the standard Excel 2003 file format when saving the file. BTW, this is a very odd formatting formula. It is difficult to imagine how you would use it. It must be a very specific & unusual business case. I also have the feeling something is missing in your post. (I'm not accusing you of being dishonest – just wondering if you may have shortened the formula for readability.) If this is not the exact formula you are using, please edit your original post with the complete formula and I will be happy to revisit this issue. A: You can find some tutorial videos for self studying the conditional formatting issue over the following pages: conditional formatting
{ "language": "en", "url": "https://stackoverflow.com/questions/84978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resending invitation/action emails I've got a web app that sends out emails in response to a user-initaited action. These emails prompt the recipient for a response (an URL is included related to the specific action.) I've got some users asking for a "resend" feature to push that email again. My objection is that if the original email ended up in a spam folder (or didn't make it all the first time), the same thing is likely to happen the second time. (I've confirmed that the emails haven't bounced; they were accepted by the recipient's mail server.) So what does the community think: is the ability to resend and email invitation/notification useful or pointless? A: Definitely useful, at least from the user's point of view. By manually resending the email, they know that it has been sent and can check their spam folder immediately to catch the mail. Otherwise, they might not know about the mail and it will dissapear from their spam before they can catch it. A: It can be useful. The users may have deleted it by accident. It may have been a transient error in the recipient's mail server. Spam filters aren't the only cause of lost mail. A: Absolutely pointless. But, if the user's want it, and it doesn't take too long, it may be worthwhile. Users are silly sometimes, and if it makes them happy... A: Useful - any number of factors can change between the first and the second sending. A: It is definitely useful. There could be a number of cases. For example, user deleted the original email accidentally. A: Your objection is assuming that the issue was the invitation was going to the spam folder. You don't know that for sure (or, at least, you hint at such). They could want a Resend button because they want to remind the customer for payment or notify them of something again or whatever. It doesn't matter the reason because the effect should be fairly easy to accomplish and allows them to send as many messages as they like. One of those 'the customer wants it, it's not entirely unreasonable, maybe you should just implement it instead of questioning them or coming up with a reason to veto it' dealies :) A: This is absolutely required. Just because your application didn't get a bounce doesn't mean that the mail actually went through. Many sites drop e-mails that trigger a spam filter rather than deliver them to a spam folder. In such a circumstance, it's conceivable that a user might in the meantime opt-out of his sites spam filtering and then want to retry. A: If you implement it I would get the user to re-enter and re-confirm the email address they entered and I would not allow it to be used more than a few times, otherwise it would be very easy to script an abuse script to bomb someones mailbox. A: There's no argument against the ability to re-send it, is there? Assuming that re-sending it will end up with the same action doesn't count - there's no harm to re-sending it. If there's an argument for it, and none against it, that should be an easy decision.
{ "language": "en", "url": "https://stackoverflow.com/questions/84980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using P4Package (Java) from Java app to validate Perforce directory In a web-app I'm writing, the user is supposed to enter the path in the Perforce repository for the node they're entering. The application is supposed to validate that the entered directory exists in the repo. I've got the P4Package (p4.jar) lib, and I'm configuring it correctly enough that it works for almost everything, EXCEPT this directory validation. I'm creating a DirEntry (from the p4.jar) using a configured Env and a path, but when I call DirEntry.sync(), it issues an incorrect command. Where I want it to issue the command: p4 [config info] dirs directory_argument <-- using the dirs command to validate a dir Instead, it issues: p4 [config info] dirs directory_argument%1 <-- note extraneous %1 Which always fails, since none of the directories have a %1 at the end of them. Any help? Is there a different way to check that a directory exists using this package? A: Sounds like the sync command has a bug in relation to dir entries and the command. My suggestion would be to just roll the command yourself, using the perforce command line as that has to be set up anyway in order to use the java library. Process p = Runtime.getRuntime().exec("p4 dirs " + directory_argument); BufferedReader stdOut = new BufferedReader(new InputReader(p.InputStream())); //Read the output of the command and process appropriately after this A: So, the code I was using did have a bug requiring me to make a change and check the code into my repository. However, since then, Perforce has come up with their own Java wrapper for the P4 client which works much better. I'd give that one a shot. A: I would try another library, P4Java, instead: http://tek42.com/p4java P4Java is much newer and I've found works much better than the P4Package. It is used in the Hudson project and I've seen it in the Fisheye source, though, I'm not sure if they are using it or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/84983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change default port when registering a new SQL 2000 server I'm trying to register an externally hosted SQL 2000 server through Enterprise Manager which isn't on the default port and I can't see anywhere to change it within Enterprise Manager. So, the question is, how do I connect to the database if: I.P. Address is 123.456.789 (example) Port is 1334 A: I found this via Google: You add a comma and the port number to the end of the server name. So if you want to connect to MySqlServer.MyDomain.com on port 3821, you type... MySqlServer.MyDomain.com,3821 A: Rob is correct - I have a SQL 2000 server running on the non-default port on a different instance name and the way I access it is like this: [ip or dns name]\[instance], [port] example: my.server.com\MSSQLSERVER2, 12345 You don't need \\[instance] if you used the default sql server instance when you installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/84992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to stream a PDF file as binary to the browser using .NET 2.0 I'm looking for a way to stream a PDF file from my server to the browser using .NET 2.0 (in binary). I'm trying to grab an existing PDF file from a server path and push that up as binary to the browser. A: Here you go: How To Write Binary Files to the Browser Using ASP.NET and Visual C# .NET A: * *Set Content-Type: Response.ContentType = "application/pdf" *Set ContentDisposition, if you want to give a new name for the file: Response.Headers.Add("Content-Disposition", "attachment: filename=file.pdf"); *Write the content, using Response.OutputStream as Mr. Kopp said. Step 2 is not strictly necessary, but it's probably a good idea if you don't want the browser to try to save the PDF with the same name as your ASPX file. A: Write the binary to the output stream, Response.OutputStream. Then just add the header Content-Disposition header. A: You can just setup a handler or a page that set's the correct response type and output the pdf to the response output buffer.
{ "language": "en", "url": "https://stackoverflow.com/questions/84995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oracle ORDImage processing in PL/SQL: Getting IMG-00710 and ORA-01031 I have loaded image into a new, initialized Oracle ORDImage object and am processing it by PL/SQL. I can read its properties, but cannot process it with the process() method. vLocalImage ORDImage := ORDImage.init(); ... vLocalImage.source.localdata := PORTAL.wwdoc_admin.get_document_blob_content(pFile); vLocalImage.setProperties(); ... if vLocalImage.width > lMaxWidth then vLocalImage.process('maxScale 534 401'); end if; This should scale the image down, conserving aspect ratio, so that it is no more than 534 px wide and no more than 401 px high. However, I get the following error stack: Internal error: ORA-29400: data cartridge error IMG-00710: unable to write to destination image ORA-01031: insufficient privileges Trying other operations (like 'rotate 90') gives same errors. A: Even though the documentation states that it should be possible to edit an ORDImage "in-place", I was unable to make it work. Instead, I created a new ORDImage object and used processCopy: vNewImage ORDImage; ... vLocalImage.processCopy('maxScale 534 401', vNewImage); A: Can you please show the select statement you use to get l_ordimage? The main cause of this error seems to be if you don't have "for update" in your select statement, but I can't get intermedia going at the moment to test.
{ "language": "en", "url": "https://stackoverflow.com/questions/85006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Object Oriented Update Approach I've been tasked with maintaining an application originally written in VB6. It has since been imported into VB .Net and to say the least the code is anything but Object Oriented. The code is riddled with classes which contain nothing more than Public Shared attributes(variables) and methods(functions), the result of which restricts the application from opening more than one project at a time. A project consists of a XML file which contains general project settings, as well as the location to an Access database which contains other project related data. Over the years the format of the XML file has been modified, and an update and versioning strategy has been adopted. The chosen strategy performs an update upon open whenever an old version is encountered. Thus far, updates have only consisted of rearranging data within the XML file or making database schema changes and moving data from the XML file to the database. Having quite a bit of background in OOP it's easy for me to see that a project should be a self contained object which other objects interact with. However, I fail to see how to apply the chosen update strategy in OOP. The problem of implementing the chosen update strategy in OOP has kept me from using OOP as of yet. If anyone has experience with such a task, or recommendations on how to proceeded I'd appreciate any assistance you can provide. A: Build a class which reads the XML file in, and provides properties/methods/etc based upon the data in that file. When the class writes the XML file back out, have it format in the manner needed for the new version. So, basically, the class will be able to read in the current version, plus all the older versions, but it will always write out the new version. Data would be held in internal variables of the class, rather than having to scan the XML file every time you need something. Adding a VERSION node to your XML file will also help in this case. A: You might have answered your own question when you used the word strategy (i.e. the Strategy Design Pattern). Possibly you could: * *Create a project class that knows nothing about conversions but accepts a strategy object. *Create a hierarchy of classes to model each possible conversion strategy. *Use a factory method to build your project object with the right strategy A: I don't understand why this is a troubling problem. It could be solved in any number of ways. If you want to do a full object oriented enterprisey type thing, you could take any subset of the following solution: * *Create an interface IProject which describes how other objects interact with a project. *Create the current implementation of Project which implements IProject and can read and write to the current version. *Extend Project for each past version, overriding the xml and database read methods and having the constructor call write when these classes are instanced *For extra enterpriseyness, create a ProjectFactory, which detects the version of the file and instanciates the correct version. *If further versions are needed, rewrite the current Project to do the same thing as past projects, accessing the new version of Project with all the reads and then calling write. The advantage of this solution is that you can continue meandering about with different versions and each new version only requires the ability to be updated to from the previous version, with all previous versions cascading up to the second to last version.
{ "language": "en", "url": "https://stackoverflow.com/questions/85010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you make a web page send to the printer something different than what's in the browser window? Google Maps used to do this bit where when you hit the "Print" link, what would be sent to the printer wasn't exactly what you had on the screen, but rather a differently-formatted version of mostly the same information. It appears that they've largely moved away from this concept (I guess people didn't understand it) and most websites have a "print version" of things like articles and so forth. But if you wanted to make a webpage such that a "printer friendly" version of the page is what gets sent to the printer without having to make a separate page for it, how would you do that? A: You can achieve this effect by creating a css stylesheet which is targeted directly to printing, and another targeted directly for the screen. Use the link tag: <link rel="stylesheet" type="text/css" href="print.css" media="print, handheld" /> <link rel="stylesheet" type="text/css" href="screen.css" media="screen" /> to embed your stylesheet into your document. To hide is easy, just set your block style to hidden in whatever stylesheet you want and it wont be displayed. For example: .newStyle1 { display: none; } Then anything set to the style of newStyle1 will not be displayed. A: The @media rule in CSS can be used to define alternate rules for print.This is often used to hide navigation and change the style to fit print better: @media print { .sidebar { display: none; } } You can also link a seperate stylesheet for print: <link rel="stylesheet" href="print.css" type="text/css" media="print" /> A: You can do this with the css when you specify media as print. A: Use a print stylesheet. Edit: Regarding the followup, you can't, in general, add things to a page with CSS. One option is to include your print-only content in the page, and hide it for screen stylesheets. You should make sure that the page still makes sense without CSS though. Another option is to use generated content, but this isn't supported by Internet Explorer 7 and below, and can be quite limited. If the print-only content is an image, you can swap that out using one of the popular image replacement techniques. A: Another way, if desired, is to have the 'print' button on the page change the page in some way that you decide, then perform a javascript 'window.print();' to bring up the browser's print dialog. A: There are several options available to you: * *You can open a new window with slightly different data to be printed. *There are also CSS styles which you can use to alter the page layout. *Finally you can specify completly different style sheets for screen, printed media, Braille readers etc. e.g. <link href="css/print.css" type="text/css" rel="stylesheet" media="print" /> See also CSS2 Print Reference A: The easiest way is to use CSS media types. For each CSS file you include, you can specify where it ought to be used: on-screen, when printing, for handhelds, for screen-readers, or various combinations of these. Example: <link rel="stylesheet" type="text/css" media="print, handheld" href="foo.css"> This has been a standard since CSS2, and most browsers support it now. More information is available here: http://www.w3.org/TR/CSS2/media.html A: CSS allows you to create stylesheets for particular types of media, meaning that you can have a stylesheet that only applies when you're printing a page, allowing you to cause it to be formatted differently. Just include a media="print" attribute on your stylesheet link for that stylesheet. This A List Apart article seems to be quite good on the subject. A: I tried using different style sheets based on the media, but I ran into trouble getting all the options I needed in. Since then I usually redirect to a different entrance of our (Fusebox) framework (i.e. print.php in stead of index.php) which in essence is the same file except it sets an extra flag/constant. In the XSL file associated with the page I then do additional work based on that flag/constant like leaving out the menu, columns of a table etc. i.e. (Page shows a link that the user has to click to display the password on the screen. The print version has the password printed.) if (!BOOL_PRINT) echo "<TD class=\"tbl_teams_scroll_item\"><SPAN class=\"span_password_hidden\" id=\"span_password_{\$team_id}\" onClick=\"RevealPassword('{\$team_id}','{\$password}');\"><xsl:value-of select=\"/PAGE/TEXTS/HIDDEN\" /></SPAN></TD>\n"; else echo "TD class=\"tbl_teams_scroll_item\"><xsl:value-of select=\"PASSWORD\" /></TD>\n"; A: You can define css rules that are specific to a media type. The following is a css example (copied from http://www.w3.org/TR/CSS2/media.html, section 7.2.1) that specifies different font sizes what gets displayed on a web page and what gets printed. @media print { BODY { font-size: 10pt } } @media screen { BODY { font-size: 12pt } } @media screen, print { BODY { line-height: 1.2 } } Alternatively, you can specify what media a stylesheet should be applied to when including it in a page: <link href="webstyles.css" type="text/css" rel="stylesheet" media="screen"/> <link href="printstyles.css" type="text/css" rel="stylesheet" media="print"/> <link href="commonstyles.css" type="text/css" rel="stylesheet" media="screen,print"/> A: Yet another option is to have a hidden IFRAME that you call iframe.contentWindow.print() on. That will allow you to create an invisible layout that prints exactly as you want it to. Of course, an even better solution is to export the file to a PDF and let the user print it out that way. PDFs produce the highest quality output, period. However, it is one more hoop for the user to jump through, so the rule of thumb is: * *PDFs for when the print layout matters *HTML for when the pure text is more important than the layout A: nsayer mentions having a print button change the layout of your screen and then kicking off a window.print() This is a solution that will probably have been overlooked by a lot of people and should be considered when you think your users want a little more of a WYSIWYG. It should probably be a "printer friendly" link though that changes the media type of your sheet sheets rather than "print this". Using jquery, you could do something like this (not checked): $(document).ready(function(){ $("#printFriendly").click(function(){ $(link[rel=link][media=screen]).remove(); $(link[rel=link][media=print]).attr("media","screen"); }); }); A: Anything you can do with CSS you can do in a print stylesheet. This means you can hide content in the print version which is shown in the screen version or hide content in the screen version which you want to show up when printing.All you do is apply display:none to the appropriate sections in the appropriate stylesheet. Also it is a good idea to size your text in points for the print version (which is a bad idea for the screen version - stick to pixels, ems or percentages here). There is universal agreement as to what printed point sizes are where as mappings of pixels to points will vary with different resolution devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/85019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Converting std::vector<>::iterator to .NET interface in C++/CLI I am wrapping a native C++ class, which has the following methods: class Native { public: class Local { std::string m_Str; int m_Int; }; typedef std::vector<Local> LocalVec; typedef LocalVec::iterator LocalIter; LocalIter BeginLocals(); LocalIter EndLocals(); private: LocalVec m_Locals; }; 1) What is the ".NET way" of representing this same kind of interface? A single method returning an array<>? Does the array<> generic have iterators, so that I could implement BeginLocals() and EndLocals()? 2) Should Local be declared as a value struct in the .NET wrapper? I'd really like to represent the wrapped class with a .NET flavor, but I'm very new to the managed world - and this type of information is frustrating to google for... A: Iterators aren't exactly translatable to "the .net way", but they are roughly replaced by IEnumerable < T > and IEnumerator < T >. Rather than vector<int> a_vector; vector<int>::iterator a_iterator; for(int i= 0; i < 100; i++) { a_vector.push_back(i); } int total = 0; a_iterator = a_vector.begin(); while( a_iterator != a_vector.end() ) { total += *a_iterator; a_iterator++; } you would see (in c#) List<int> a_list = new List<int>(); for(int i=0; i < 100; i++) { a_list.Add(i); } int total = 0; foreach( int item in a_list) { total += item; } Or more explicitly (without hiding the IEnumerator behind the foreach syntax sugar): List<int> a_list = new List<int>(); for (int i = 0; i < 100; i++) { a_list.Add(i); } int total = 0; IEnumerator<int> a_enumerator = a_list.GetEnumerator(); while (a_enumerator.MoveNext()) { total += a_enumerator.Current; } As you can see, foreach just hides the .net enumerator for you. So really, the ".net way" would be to simply allow people to create List< Local > items for themselves. If you do want to control iteration or make the collection a bit more custom, have your collection implement the IEnumerable< T > and/or ICollection< T > interfaces as well. A near direct translation to c# would be pretty much what you assumed: public class Native { public class Local { public string m_str; public int m_int; } private List<Local> m_Locals = new List<Local>(); public List<Local> Locals { get{ return m_Locals;} } } Then a user would be able to foreach( Local item in someNative.Locals) { ... } A: @Phillip - Thanks, your answer really got me started in the right direction. After seeing your code, and doing a little more reading in Nish's book C++/CLI in Action, I think using an indexed property that returns a const tracking handle to a Local instance on the managed heap is probably the best approach. I ended up implementing something similar to the following: public ref class Managed { public: ref class Local { String^ m_Str; int m_Int; }; property const Local^ Locals[int] { const Local^ get(int Index) { // error checking here... return m_Locals[Index]; } }; private: List<Local^> m_Locals; };
{ "language": "en", "url": "https://stackoverflow.com/questions/85033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SqlServer create table with MySql like auto_increment primary key I want to make a table in SqlServer that will add, on insert, a auto incremented primary key. This should be an autoincremented id similar to MySql auto_increment functionality. (Below) create table foo ( user_id int not null auto_increment, name varchar(50) ) Is there a way of doing this with out creating an insert trigger? A: As others have mentioned: add the IDENTITY attribute to the column, and make it a primary key. There are, however, differences between MSSQL's IDENTITY and MySQL's AUTO_INCREMENT: * *MySQL requires that a unique constraint (often in the form of a primary key) be defined for the AUTO_INCREMENT column.MSSQL doesn't have such a requirement. *MySQL lets you manually insert values into an AUTO_INCREMENT column. MSSQL prevents you from manually inserting a value into an IDENTITY column; if needed, you can override this by issuing a "SET IDENTITY_INSERT tablename ON" command before the insert. *MySQL allows you to update values in an AUTO_INCREMENT column.MSSQL refuses to update values in an IDENTITY column. A: Like this create table foo ( user_id int not null identity, name varchar(50) ) A: Just set the field as an identity field. A: OP requested an auto incremented primary key. The IDENTITY keyword does not, by itself, make a column be the primary key. CREATE TABLE user ( TheKey int IDENTITY(1,1) PRIMARY KEY, Name varchar(50) ) A: They have answered your question but I want to add one bit of advice for someone new to using identity columns. There are times when you have to return the value of the identity just inserted so that you can insert into a related table. Many sources will tell you to use @@identity to get this value. Under no circumstances should you ever use @@identity if you want to mantain data integrity. It will give the identity created in a trigger if one of them is added to insert to another table. Since you cannot guarantee the value of @@identity will always be correct, it is best to never use @@identity. Use scope_identity() to get this value instead. I know this is slightly off topic, but it is important to your understanding of how to use identity with SQL Server. And trust me, you did not want to be fixing a problem of the related records having the wrong identity value fed to them. This is something that can quietly go wrong for months before it is dicovered and is almost impossible to fix the data afterward. A: declare the field to be identity A: As advised above, use an IDENTITY field. CREATE TABLE foo ( user_id int IDENTITY(1,1) NOT NULL, name varchar(50) ) A: As others have said, just set the Identity option.
{ "language": "en", "url": "https://stackoverflow.com/questions/85034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How can I quickly identify most recently modified stored procedures in SQL Server I need to manually migrate modified stored procedures from a DEV SQL Server 2005 database instance to a TEST instance. Except for the changes I'm migrating, the databases have the same schemas. How can I quickly identify which stored procedures have been modified in the DEV database for migration to the TEST instance? I assume I can write a query against some of the system tables to view database objects of type stored procedure, sorting by some sort of last modified or compiled data, but I'm not sure. Maybe there is some sort of free utility someone can point me to. A: instead of using sysobjects which is not recommended anymore use sys.procedures select name,create_date,modify_date from sys.procedures order by modify_date desc you can do the where clause yourself but this will list it in order of modification date descending A: Although not free I have had good experience using Red-Gates SQL Compare tool. It worked for me in the past. They have a free trial available which may be good enough to solve your current issue. A: You can execute this query to find all stored procedures modified in the last x number of days: SELECT name FROM sys.objects WHERE type = 'P' AND DATEDIFF(D,modify_date, GETDATE()) < X A: There are some special cases where scripts might not give optimal results. One is deleting stored procedures or other objects in dev environment – you won’t catch this using system views because object won’t exist there any longer. Also, I’m not really sure this approach can work on changes such as permissions and similar. In such cases its best to use some third party tool just to double check nothing is missed. I’ve successfully used ApexSQL Diff in the past for similar tasks and it worked really good on large databases with 1000+ objects but you can’t go wrong with SQL Compare that’s already mentioned here or basically any other tool that exists on the market. Disclaimer: I’m not affiliated with any of the vendors I’m mentioning here but I do use both set of tools (Apex and RG) in the company I work for. A: you can also use the following code snipet USE AdventureWorks2008; GO SELECT SprocName=name, create_date, modify_date FROM sys.objects WHERE type = 'P' AND name = 'uspUpdateEmployeeHireInfo' GO A: You can use following type of query to find modified stored procedures , you can use any number then 7 as per your needs SELECT name FROM sys.objects WHERE type = 'P' AND DATEDIFF(D,modify_date, GETDATE()) < 7 A: There are several database compare tools out there. One that I've always like is SQLCompare by Red Gate. You can also try using: SELECT name FROM sys.objects WHERE modify_date > @cutoffdate In SQL 2000 that wouldn't have always worked, because using ALTER didn't update the date correctly, but in 2005 I believe that problem is fixed. I use a SQL compare tool myself though, so I can't vouch for that method 100%
{ "language": "en", "url": "https://stackoverflow.com/questions/85036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Editable JTable Tutorial Are there any good books or website that go over creating a JTable? I want to make one column editable. I would like to actually put a inherited JCheckBox component (that we created here) into one of the table columns instead of just having the table put JCheckBox in based on it being an editable boolean field. I have the JFC Swing Tutorial Second Edition book but I just would like to know if there are other examples I could look at and learn how to deal with the tables better. The book seems to just take the java 'trail' online and put it in the book. I am re-reading the stuff though, just curious if anyone has found something that might help out more. A: To make a column editable you have to override the isCellEditable method in the TableModel. Creating a TableModel is fairly easy if you inherit AbstractTableModel and I'd recommend it for all but the most simple JTables. However, adapting the TableModel is only part of what you need to do. To actually get a custom component in the JTable, you need to set a custom cell renderer. To use an interactive custom component, you need to set a custom cell editor. In some cases, it's enough to use slightly modificated versions of the default classes for this. Editors If you already have got a custom component is easily done using delegation: Create a new class implementing TableCellEditor, and return a new instance of the component in the getCellEditorComponent method. The paramaters to this method include the current value as well as the cell coordinates, a link back to the table and wether or not the cell is selected. The TableCellEditor also has a method that is called when the user commits a change to the cell contents (where you can validate user input and adjust the model) or cancels an edit. Be sure to call the stopEditing() method on your editor if you ever programmatically abort editing, otherwise the editor component will remain on screen -- this once took me like 2 hours to debug. Note that within a JTable editors and only editors receive events! Displaying a button can be done using a renderer. But to get a functioning button, you need to implement an editor with the correct EventListeners registered. Registering a listener on a renderer does nothing. Renderers Implementing a renderer is not strictly necessary for what you describe in your question, but you typically end up doing it anyway, if only for minor modifications. Renderers, unlike editors, are speed critical. The getTableCellRendererComponent of a renderer is called once for every cell in the table! The component returned by a renderer is only used to paint the cell, not for interaction, and thus can be "reused" for the next cell. In other words, you should adjust the component (e.g. using setText(...) or setFont(...) if it is a TextComponent) in the renderer, you should not instantiate a new one -- that's an easy way to cripple the performance. Caveats Note that for renderers and editors to work, you need to tell the JTable when to use a certain renderer/editor. There are basically two ways to do this. You can set the default cell renderer/editor for a certain type using the respective JTable methods. For this way to work, your TableModel needs to return exactly this type in the getColumnClass(...) method! The default table model will not do this for you, it always returns Object.class. I'm sure that one has stumped a lot of people. The other way to set the editor/renderer is by explicitly setting it on the column itself, that is, by getting the TableColumn via the getTableColumn(...) method of the JTable. This is a lot more elaborate, however, it's also the only way to have two different renderers/editors for a single class. E.g. your model might have two columns of class String which are rendered in entirely different ways, maybe once using a JLabel/DefaultRenderer and the other using a JButton to access a more elaborate editor. JTable with its custom renderers and editors is extremely versatile, but it is also a lot to take in, and there are a lot of things to do wrong. Good luck! How to Use Tables in The Swing Tutorial is mandatory reading for anyone customising JTables. In particular, read and reread Concepts: Editors and Renderers because it typically takes a while for it to "click". The examples on custom renderers and editors are also very worthwhile. A: The class you want to look into extending to create your own behavior is DefaultTableModel. That will allow you to define your own behavior. A decent tutorial can be found on sun's site. A: This tutorial from the java lobby is easy to follow. The online Swing trail for JTable that you reference indicates that it has been updated. Did you scan through the whole thing for possible better (isn't newer always better) information? A: If you are trying to use a simple JTable with 1 column editable and you know the column location you could always use default table model and overload the isCellEditable call. something like this : myTable.setModel(new DefaultTableModel(){ @Override public boolean isCellEditable(int row, int column) { if (column == x) { return true; } else return false; } }); And for the check box create a renderer class MyCheckBoxRenderer extends JCheckBox implements TableCellRenderer A: Some useful classes are: Package javax.swing.table : TableModel - Interface for a tablemodel AbstractTableModel - Nice class to extend for creating your own table with custom data structures DefaultTableModel - Default table model which can deal with arrays[] and Vectors To disable editing on any cell you need to override the isCellEditable(int row, int col) method A: in your table Model, you should override "isCellEditable" and "setValueAt" functions, like below. Column 4 is the column for editable cells. Then when you double click the cell and type something, setValueAt() will be called and save the value to the tableModel's DO,field col4. public ArrayList<XXXDO> tbmData = new ArrayList<XXXDO>(); //arraylist for data in table @Override public boolean isCellEditable(int row, int col) { if (col == 4) { return true; } else { return false; } } @Override public void setValueAt(Object value, int row, int col) { if ((row >= 0) && (row < this.tbmData.size()) && (col >= 0) && (col < this.colNm.length)) { if (col == 4) { tbmData.get(row).col4= (String) value; } fireTableCellUpdated(row, col); } else { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/85046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Git over Email? Assuming network access is sporadic with no central server, what would be the best way to use git to keep three or more branches in sync? Is there a way to extract just my deltas, email those, and merge them on the other end? A: See the main pages for git-format-patch and git-am. This is one of the ways the system was originally designed to work with. A: While "git format-patch" and "git am" are great ways to manage patches from non-git sources, for git repositories you should investigate "git bundle". "git bundle" and the subcommands "create" and "unbundle" can be used to create and use a binary blob of incremental commits that can be used to transfer branch history across a 'weak' link via an alternative file transfer mechanism (e.g. email, snail-mail, etc.). git bundles will preserve commit ids, whereas format-patch/am will not resulting in the destination commits not being identical (different SHA1s). A: There are a few tools in git to use to mail patches or import mailed patches: git-am (apply patches from a mailbox), git-format-patch (prepare email for mailing), git-send-email (send a collection of patches via mail), etc. man 1 git has a complete list.
{ "language": "en", "url": "https://stackoverflow.com/questions/85051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Why do we need other JVM languages I see here that there are a load of languages aside from Java that run on the JVM. I'm a bit confused about the whole concept of other languages running in the JVM. So: What is the advantage in having other languages for the JVM? What is required (in high level terms) to write a language/compiler for the JVM? How do you write/compile/run code in a language (other than Java) in the JVM? EDIT: There were 3 follow up questions (originally comments) that were answered in the accepted answer. They are reprinted here for legibility: How would an app written in, say, JPython, interact with a Java app? Also, Can that JPython application use any of the JDK functions/objects?? What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK? A: Turning this on its head, consider you want to design a new language and you want it to run in a managed runtime with a JIT and GC. Then consider that you could: (a) write you own managed runtime (VM) and tackle all sorts of technically difficult issues that will doubtless lead to many bugs, bad performance, improper threading and a great deal of portability effort or (b) compile your language into bytecode that can run on the Java VM which is already quite mature, fast and supported on a number of platforms (sometimes with more than one choice of vendor impementation). Given that the JavaVM bytecode is not tied so closely to the Java language as to unduly restrict the type of language you can implement, it has been a popular target environment for languages that want to run in a VM. A: Java is a fairly verbose programming language that is getting outdated very quickly with all of the new fancy languages/frameworks coming out in the past 5 years. To support all the fancy syntax that people want in a language AND preserve backwards compatibility it makes more sense to add more languages to the runtime. Another benefit is it lets you run some web frameworks written in Ruby ala JRuby (aka Rails), or Grails(Groovy on Railys essentially), etc. on a proven hosting platform that likely already is in production at many companies, rather than having to using that not nearly as tried and tested Ruby hosting environments. To compile the other languages you are just converting to Java byte code. A: To address your three questions separately: What is the advantage in having other languages for the JVM? There are two factors here. (1) Why have a language other than Java for the JVM, and (2) why have another language run on the JVM, instead of a different runtime? * *Other languages can satisfy other needs. For example, Java has no built-in support for closures, a feature that is often very useful. *A language that runs on the JVM is bytecode compatible with any other language that runs on the JVM, meaning that code written in one language can interact with a library written in another language. What is required (in high level terms) to write a language/compiler for the JVM? The JVM reads bytecode (.class) files to obtain the instructions it needs to perform. Thus any language that is to be run on the JVM needs to be compiled to bytecode adhering to the Sun specification. This process is similar to compiling to native code, except that instead of compiling to instructions understood by the CPU, the code is compiled to instructions that are interpreted by the JVM. How do you write/compile/run code in a language (other than Java) in the JVM? Very much in the same way you write/compile/run code in Java. To get your feet wet, I'd recommend looking at Scala, which runs flawlessly on the JVM. Answering your follow up questions: How would an app written in, say, JPython, interact with a Java app? This depends on the implementation's choice of bridging the language gap. In your example, Jython project has a straightforward means of doing this (see here): from java.net import URL u = URL('http://jython.org') Also, can that JPython application use any of the JDK functions/objects? Yes, see above. What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK? No. Scala (link above) for example implements functional features while maintaining compatibility with Java. For example: object Timer { def oncePerSecond(callback: () => unit) { while (true) { callback(); Thread sleep 1000 } } def timeFlies() { println("time flies like an arrow...") } def main(args: Array[String]) { oncePerSecond(timeFlies) } } A: I would answer, “because Java sucks” but then again, perhaps that's too obvious … ;-) A: The advantage to having other languages for the JVM is quite the same as the advantage to having other languages for computer in general: while all turing-complete languages can technically accomplish the same tasks, some languages make some tasks easier than others while other languages make other tasks easier. Since the JVM is something we already have the ability to run on all (well, nearly all) computers, and a lot of computers, in fact already have it, we can get the "write once, run anywhere" benefit, but without requiring that one uses Java. Writing a language/compiler for the JVM isn't really different from writing one for a real machine. The real difference is that you have to compile to the JVM's bytecode instead of to the machine's executable code, but that's really a minor difference in the grand scheme of things. Writing code for a language other than Java in the JVM really isn't different from writing Java except, of course, that you'll be using a different language. You'll compile using the compiler that somebody writes for it (again, not much different from a C compiler, fundamentally, and pretty much not different at all from a Java compiler), and you'll end up being able to run it just like you would compiled Java code since once it's in bytecode, the JVM can't tell what language it came from. A: Different languages are tailored to different tasks. While certain problem domains fit the Java language perfectly, some are much easier to express in alternative languages. Also, for a user accustomed to Ruby, Python, etc, the ability to generate Java bytecode and take advantage of the JDK classes and JIT compiler has obvious benefits. A: Answering just your second question: The JVM is just an abstract machine and execution model. So targetting it with a compiler is just the same as any other machine and execution model that a compiler might target, be it implemented in hardware (x86, CELL, etc) or software (parrot, .NET). The JVM is fairly simple, so its actually a fairly easy target for compilers. Also, implementations tend to have pretty good JIT compilers (to deal with the lousy code that javac produces), so you can get good performance without having to worry about a lot of optimizations. A couple of caveats apply. First, the JVM directly embodies java's module and inheritance system, so trying to do anything else (multiple inheritance, multiple dispatch) is likely to be tricky and require convoluted code. Second, JVMs are optimized to deal with the kind of bytecode that javac produces. Producing bytecode that is very different from this is likely to get into odd corners of the JIT compiler/JVM which will likely be inefficient at best (at worst, they can crash the JVM or at least give spurious VirtualMachineError exceptions). A: You need other languages on the JVM for the same reason you need multiple programming languages in general: Different languages are better as solving different problems ... static typing vs. dynamic typing, strict vs. lazy ... Declarative, Imperative, Object Oriented ... etc. In general, writing a "compiler" for another language to run on the JVM (or on the .Net CLR) is essentially a matter of compiling that language into java bytecode (or in the case of .Net, IL) instead of to assembly/machine language. That said, a lot of the extra languages that are being written for JVM aren't compiled, but rather interpreted scripting languages... A: What the JVM can do is defined by the JVM's bytecode (what you find in .class files) rather than the source language. So changing the high level source code language isn't going to have a substantial impact on the available functionality. As for what is required to write a compiler for the JVM, all you really need to do is generate correct bytecode / .class files. How you write/compile code with an alternate compiler sort of depends on the compiler in question, but once the compiler outputs .class files, running them is no different than running the .class files generated by javac. A: The advantage for these other languages is that they get relatively easy access to lots of java libraries. The advantage for Java people varies depending on language -- each has a story tell Java coders about what they do better. Some will stress how they can be used to add dynamic scripting to JVM-based apps, others will just talk about how their language is easier to use, has a better syntax, or so forth. What's required are the same things to write any other language compiler: parsing to an AST, then transforming that to instructions for the target architecture (byte code) and storing it in the right format (.class files). From the users' perspective, you just write code and run the compiler binaries, and out comes .class files you can mix in with those your java compiler produces. A: The .NET languages are more for show than actual usefulness. Each language has been so butchered, that they're all C# with a new face. There are a variety of reasons to provide alternative languages for the Java VM: * *The JVM is multiplatform. Any language ported to the JVM gets that as a free bonus. *There is quite a bit of legacy code out there. Antiquated engines like ColdFusion perform better while offering customers the ability to slowly phase their applications from the legacy solution to the modern solution. *Certain forms of scripting are better suited to rapid development. JavaFX, for example, is designed with rapid Graphical development in mind. In this way it competes with engines like DarkBasic. (Processing is another player in this space.) *Scripting environments can offer control. For example, an application may wish to expose a VBA-like environment to the user without exposing the underlying Java APIs. Using an engine like Rhino can provide an environment that supports quick and dirty coding in a carefully controlled sandbox. *Interpreted scripts mean that there's no need to recompile anything. No need to recompile translates into a more dynamic environment. e.g. Despite OpenOffice's use of Java as a "scripting language", Java sucks for that use. The user has to go through all kinds of recompile/reload gyrations that are unnecessary in a dynamic scripting environment like Javascript. *Which brings me to another point. Scripting engines can be more easily stopped and reloaded without stopping and reloading the entire JVM. This increases the utility of the scripting language as the environment can be reset at any time. A: It's much easier for a compiler writer to generate JVM or CLR byte-codes. They are a much cleaner and higher level abstraction than any machine language. Because of this, it is much more feasible to experiment with creating new languages than ever before, because all you have to do is target one of these VM architectures and you will have a set of tools and libraries already available for your language. They let language designers focus more on the language than all the necessary support infrastructure. A: Because the JSR process is rendering Java more and more dead: http://www.infoq.com/news/2009/01/java7-updated It's a shame that even essential and long known additions like Closures are not added just because the members cannot agree on an implementation. A: Java has accumulated a massive user base over seven major versions (from 1.0 to 1.6). Its capability to evolve is limited by the need to preserve backwards compatibility for the uncountable millions of lines of Java code running in production. This is a problem because Java needs to evolve to: * *compete with newer programming languages that have learned from Java's successes and failures. *incorporate new advances in programming language design. *allow users to take full advantage of advances in hardware - e.g. multi-core processors. *fix some cutting edge ideas that introduced unexpected problems (e.g. checked exceptions, generics). The requirement for backwards compatibility is a barrier to staying competitive. If you compare Java to C#, Java has the advantage in mature, production ready libraries and frameworks, and a disadvantage in terms of language features and rate of increase in market share. This is what you would expect from comparing two successful languages that are one generation apart. Any new language has the same advantage and disadvantage that C# has compared to Java to an extreme degree. One way of maximizing the advantage in terms of language features, and minimizing the disadvantage in terms of mature libraries and frameworks is to build the language for an existing virtual machine and make it interoperable with code written for that virtual machine. This is the reason behind the modest success of Groovy and Clojure; and the excitement around Scala. Without the JVM these languages could only ever have occupied a tiny niche in a very specialized market segment, whereas with the JVM they occupy a significant niche in the mainstream. A: They do it to keep up with .Net. .Net allows C#, VB, J# (formerly), F#, Python, Ruby (coming soon), and c++. I'm probably missing some. Probably the big one in there is Python, for the scripting people. A: To an extent it is probably an 'Arms Race' against the .NET CLR. But I think there are also genuine reasons for introducing new languages to the JVM, particularly when they will be run 'in parallel', you can use the right language for the right job, a scripting language like Groovy may be exactly what you need for your page presentation, whereas regular old Java is better for your business logic. I'm going to leave someone more qualified to talk about what is required to write a new language/compiler. As for how to writing code, you do it in notepad/vi as usual! (or use a development tool that supports the language if you want to do it the easy way.) Compiling will require a special compiler for the language that will interpret and compile it into bytecode. Since java also produces bytecode technically you don't need to do anything special to run it. A: The reason is that the JVM platform offers a lot of advantages. * *Giant number of libraries *Broader degree of platform implementations *Mature frameworks *Legacy code that's already part of your infrastructure The languages Sun is trying to support with their Scripting spec (e.g. Python, Ruby) are up and comers largely due to their perceived productivity enhancements. Running Jython allows you to, in theory, be more productive, and leverage the capabilities of Python to solve a problem more suited to Python, but still be able to integrate, on a runtime level, with your existing codebase. The classic implementations of Python and Ruby effect the same ability for C libraries. Additionally, it's often easier to express some things in a dynamic language than in Java. If this is the case, you can go the other way; consume Python/Ruby libraries from Java. There's a performance hit, but many are willing to accept that in exchange for a less verbose, clearer codebase.
{ "language": "en", "url": "https://stackoverflow.com/questions/85058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How do I implement an A* pathfinding algorithm, with movement costs for every programming language? Can we get people to post code of simple, optimized implementations of the A* pathfinding algorithm, in every single language? This is mostly for fun and to play with what stackoverflow itself is capable of... although I actually am interested in getting an ActionScript 3 version of this. But the idea is that this "Question" will continue to be updated eternally into the future, even as different programming languages are created! I don't know of any other place online where you can see pseudocode "translated" into many (much less every) different language. Seems like it's a worthwhile resource, and while not necessarily what this site was designed for, there's no harm in trying it out and seeing if it turns out to be a worthwhile thing that stackoverflow could be used for!
{ "language": "en", "url": "https://stackoverflow.com/questions/85065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: .NET Remoting Server Only processes One request I am using .NET Remoting. My server/hoster is a Windows Service. It will sometimes work just fine and other times it will process one request and then it does not process any more (until I restart it). It is running as a Windows service Here is the code from the Windows Service: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.ServiceProcess; using System.Text; using Remoting; namespace CreateReview { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } readonly TcpChannel channel = new TcpChannel(8180); protected override void OnStart(string[] args) { // Create an instance of a channel ChannelServices.RegisterChannel(channel, false); // Register as an available service with the name HelloWorld RemotingConfiguration.RegisterWellKnownServiceType( typeof(SampleObject), "SetupReview", WellKnownObjectMode.SingleCall); } protected override void OnStop() { } } } Thanks for any help offered. Vaccano A: as a SingleCall type, your SampleObject will be created for every call the client makes. This suggests to me that your object is at fault, and you don't show what it does. You need to look at any dependancies it has on shared resources orlocks. Try writing some debug out in the SampleObject's constructor to see how far the remoting call gets.
{ "language": "en", "url": "https://stackoverflow.com/questions/85083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass by reference not returning in RMI for ArrayList I've got an RMI call defined as: public void remoteGetCustomerNameNumbers(ArrayList<String> customerNumberList, ArrayList<String> customerNameList) throws java.rmi.RemoteException; The function does a database lookup and populates the two ArrayLists. The calling function gets nothing. I believe this works with Vector types. Do I need to use the Vector, or is there a way to get this to work without making two calls. I've got some other ideas that I'd probably use, like returning a key/value pair, but I'd like to know if I can get this to work. Update: I would accept all of the answers given so far if I could. I hadn't known the network cost, so It makes sense to rework the function to return a LinkedHashMap instead of the two ArrayLists. A: Arguments in RMI calls a serialised. Deserialisation on the server creates a copy of the lists. If the lists remained on the client side, then the number of network calls would be quite high. You can pass remote objects, but beware of the performance implications. A: You lose your references when you make the remote call. You'll need to return the lists rather than expect them to be populated by the remote call. A: As Tom mentions, you can pass remote objects. You'd have to create a class to hold your list that implements Remote. Anytime you pass something that implements Remote as an argument, whenever the receiving side uses it, it turns around and makes a remote call back to the caller to work with that object. A: As others have already mentioned, when passing objects as parameters to an RMI method, the object will get serialized, then deserialized on the other end inside the target object containing the RMI method. This breaks the reference from the original objects passed in, as you now have two distinct objects: one in the client code calling the method, and one on the remote side. In this specific example, a better approach would be to break up your method calls (since you appear to be doing two things in one method: getting customer names and getting customer numbers) and instead have your results returned to the caller rather than passing in a collection...like this: public ArrayList<String> getCustomerNames() throws java.rmi.RemoteException; public ArrayList<String> getCustomerNumbers() throws java.rmi.RemoteException; Since both ArrayList and String implement Serializable, the results in the collection will be serialized and sent over the wire to the client code calling the method, at which point you can work with the data however you need. If instead you need to use a custom object in the collection, as long as your class implements the java.io.Serializable interface, and follows the specification for that interface you should have no problems. This would result in two separate calls over the wire, but is a much cleaner and simpler interaction, and avoids the reference breaking problem in your original example.
{ "language": "en", "url": "https://stackoverflow.com/questions/85085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error BC30002 - Type XXX is not defined OK, this begins to drive me crazy. I have an asp.net webapp. Pretty straightforward, most of the code in the .aspx.vb, and a few classes in App_Code. The problem, which has begun to occur only today (even though most of the code was already written), is that once in a while, I have this error message : Error BC30002: Type ‘XXX’ is not defined The error occurs about every time I modify the files in the App_Code folder. EDIT : OK, this happens also if I don't touch anything for a while then refresh the page. I'm still trying to figure out exactly how to trigger this error. I just have to wait a little bit without touching anything, then refresh the page and it works, but it's very annoying. So I searched a little bit, but nothing came up except imports missing. Any idea ? A: I think I found the problem. My code was like that : Imports CMS Sub Whatever() Dim a as new Arbo.MyObject() ' Arbo is a namespace inside CMS Dim b as new Util.MyOtherObject() ' Util is a namespace inside Util End Sub I'm not sure why I wrote it like that, but it turns out the fact I was calling classes without either calling their whole namespace or importing their whole namespace was triggering the error. I rewrote it like this : Imports CMS.Arbo Imports CMS.Util Sub Whatever() Dim a as new MyObject() Dim b as new MyOtherObject() End Sub And now it works... A: This happened to me after I added a new project to an old solution. I lowered the Target framework to match that of the other 'older' projects and the error went away. A: Sounds like a pre compile issue, particularly because you mention that you get the error and then wait and it disappears. ASP.NET may be still in the process of dynamically compiling your application or it has compiled the types into different assemblies. With dynamic compilation, you are not guaranteed to have different codebehind files compiled into the same assembly. So the type you are referencing may not be able to be resolved within its precompiled assembly. Try using the "@Reference" directive to indicate to the runtime that your page and the file that contains your type should be compiled into the same assembly. @ Reference - MSDN A: Check for a compiler warning (Output window of Visual Studio) "warning : The following assembly has dependencies on a version of the .NET Framework that is higher than the target and might not load correctly during runtime causing a failure". This happens when one of your dlls is compiled with a newer version of dotnet. If your current project is set to use a lower version of dotnet, the dependency chain prevents the dll (with the higher dotnet ver) from loading. It gives a compile error in Visual Studio, but can still run in IIS. A: Sounds like it happens every time the website spins up (the app gets recycled every time you touch app_code and probably you have IIS configured to shut down the website after X minutes of inactivity). I bet it has something to do with the asp.net worker process not having the correct access rights on the server. So its trying to load an assembly and is being denied. Check this link and Table 19.3 for a list of all the folders the worker process account must have access to in order to function. And don't forget to give it rights to all files and folders in your virtual directory! A: Replace your vbproj and vbproj.user file from your backup before if the references are equal
{ "language": "en", "url": "https://stackoverflow.com/questions/85091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do you structure a development sprint? So I have a backlog of features and we are about to get started on a sizable project. I am working on defining the structure of our sprints and I'm interested in the communities feedback. What I'm thinking is: * *One day sprint planning * *Fill the backlog and figure out what each dev will go after this sprint *Three weeks of development * *GO! GO! GO! *Daily stand up meeting * *Check to see if anyone needs help or feels off track *Two days of sprint review * *code reviews happen here, stakeholder presentations *One day sprint retrospective * *what did we get done in the last sprint? how can we do better next time? Sprints should always end on a Tuesday (to avoid too much weekend stress). Anything else? There is obviously more to agile than this. I want to provide the team with a simple outline of how we are going to operate as we get this project started. A: I'd consider experimenting with sprints that are shorter then one month. Personally I find one-two week iterations more effective at getting effective feedback quickly. It also prevents any issues that may be causing problems at the iteration level building up to levels that become harder to manage. Even for the 30 day sprint - two days sounds about a day to long for the sprint review... and one day sounds about 0.5 days too long for the retrospective. I've found that if you need much more than that there have been communication problems while the iterations has been going on - so you might want to look at needing long reviews as a possible red flag. Of course that's just been my experience - of mostly developing web apps with smallish (4-12) person teams. You're experience may vary. That said - I'd definitely give shorter sprints a try. Like integration builds - a lot of things get easier if you do them more often. A: Turn off email, cell phone and instant messaging apps for core code time. 10am to 1pm, 2pm to 5pm might be good blocks for this. Order food, drinks for team when they are in "the zone". Cancel all other meetings for the days of, before and after the planning session and the review days. A: * *Make sure the "stand-up" remains a STAND-up. It is very easy to slide into longer and longer meetings. *One day of sprint planning and three days at the end may be too much. Only schedule as much time as you need. *+1 to the idea of shorter iterations. Personally, four one-week iterations within a sprint have worked well. People are great at estimating near-term tasks; past that it becomes more and more guesswork. A: Looks like a good approach. I second what adrianh and jedidja said about possibly shorter iterations. I like 1 weekers myself. As well as better estimation, it also keeps the idea of "working software" on a much shorter cycle. A few questions: Why are code reviews left until the end? Either pair program, or do your reviews as you go. Does 3 weeks of development mean "dev, test, documentation, installers, etc" ? I.e. everything you need to be truly done? A: We structure our sprints very similar to your outline except our sprint reviews are the last day of the sprint and generally on last about an hour. The sprint review is the time where you exhibit your work to the customers and any other interested parties, not the time to do code reviews. Code reviews, if you chose to do them, should be done periodically throughout the sprint. We used to have a one hour block each week where we'd go over developer nominated code, meaning we didn't waste time reviewing every LOC written. We also end our sprints on a Tuesday and begin on a Thursday leaving Wednesday to wrap up loose ends and tackle technical debt created during the sprint. A: I don't recommend postponing code reviews until after the sprint, they should be an integral part of the development process. In other words, a task is not done unless the code has been reviewed (and tested, and documented, and ...). A: Its important to stay away from managing for the sake of managing. SCRUM only requires 1 meeting a day, and that's a short one. Additionally, during each sprint, the only other meetings are the Spring retrospective, and the sprint planning. This allows us to implement ROWE, or a Results Oriented Work Environment. Let your developers decide How, Where, When they will do thier development. Use your daily stand-ups to track that they are doing their work. Other than that, stand back and be amazed at thier productivity. Ideas like "turn off cell phones, turn off IM apps, etc during coding" are all bad ideas. When you hire your team, you are hiring them with confidence that they know how to do thier job correctly. If you hired them with that understanding, why would you want to constrain thier ability to get thier job done the best way they know possible? If you're using SCRUM, then each developer will have chosen the work they feel they're able to do, your job as a Scrum-Master is to remove obstacles, not create them. Code Reviews: Absolutely necessary. Peer reviews of code are a great teaching tool for junior developers attending meetings, and for the folks having thier code reviewed. Design Documents: I personally feel that detailed design documents covering what the developer intends to do is very important, and I also feel they are an important part of the development process. Now, this is not specifically in-line with agile development, but I personally regularly refer back to design documents created years ago to see what the original developer was thinking when they coded their modules.
{ "language": "en", "url": "https://stackoverflow.com/questions/85114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Display date/time in user's locale format and time offset I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone. Bonus if I can output in the user's locale date format. A: Once you have your date object constructed, here's a snippet for the conversion: The function takes a UTC formatted Date object and format string. You will need a Date.strftime prototype. function UTCToLocalTimeString(d, format) { if (timeOffsetInHours == null) { timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1); } d.setHours(d.getHours() + timeOffsetInHours); return d.strftime(format); } A: // new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) var serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server var serverDateStr = serverDate.toLocaleString("en-US", { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }) var userDate = new Date(serverDateStr + " UTC"); var locale = window.navigator.userLanguage || window.navigator.language; var clientDateStr = userDate.toLocaleString(locale, { year: 'numeric', month: 'numeric', day: 'numeric' }); var clientDateTimeStr = userDate.toLocaleString(locale, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }); console.log("Server UTC date: " + serverDateStr); console.log("User's local date: " + clientDateStr); console.log("User's local date&time: " + clientDateTimeStr); A: You can do it with moment.js (deprecated in 2021) It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers): var m = moment("2013-02-08T09:30:26Z"); Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it. You can even format a moment object in the users locale like this: m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use. Note: Moment JS recommends more modern alternatives, so it is probably not a good choice for new projects. A: Here's what I've used in past projects: var myDate = new Date(); var tzo = (myDate.getTimezoneOffset()/60)*(-1); //get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss'); myDate.setHours(myDate.getHours() + tzo); //here you would have to get a handle to your span / div to set. again, I'm using MS Ajax's $get var dateSpn = $get('dataDate'); dateSpn.innerHTML = myDate.localeFormat('F'); A: The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours) To the get a normal time-zone offset in hours, you need to use: var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60 Important detail: Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset. A: With date from PHP code I used something like this.. function getLocalDate(php_date) { var dt = new Date(php_date); var minutes = dt.getTimezoneOffset(); dt = new Date(dt.getTime() + minutes*60000); return dt; } We can call it like this var localdateObj = getLocalDate('2015-09-25T02:57:46'); A: I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format. The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server. Python/Django: send request browser language as context parameter: language = request.META.get('HTTP_ACCEPT_LANGUAGE') return render(request, 'cssexy/index.html', { "language": language }) HTML: write it in a hidden input: <input type="hidden" id="browserlanguage" value={{ language }}/> JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression const browserlanguage = document.getElementById("browserlanguage").value; var defaultlang = browserlanguage.replace(/(\w{2}\-\w{2}),.*/, "$1"); JavaScript: convert to datetime and format it: var options = { hour: "2-digit", minute: "2-digit" }; var dt = (new Date(str)).toLocaleDateString(defaultlang, options); See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString The result is (browser language is en-gb): 05/12/2016, 14:58 A: You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale. Here's the whole list: Working with Dates A: Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want. Then the various toLocale…String methods will provide localized output. Example: // This would come from the server. // Also, this whole block could probably be made into an mktime function. // All very bare here for quick grasping. d = new Date(); d.setUTCFullYear(2004); d.setUTCMonth(1); d.setUTCDate(29); d.setUTCHours(2); d.setUTCMinutes(45); d.setUTCSeconds(26); console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT) console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004 console.log(d.toLocaleDateString()); // -> 02/28/2004 console.log(d.toLocaleTimeString()); // -> 23:45:26 Some references: * *toLocaleString *toLocaleDateString *toLocaleTimeString *getTimezoneOffset A: You could use the following, which reports the timezone offset from GMT in minutes: new Date().getTimezoneOffset(); Note : - this function return a negative number. A: The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time. http://momentjs.com/ Moment.js will display the time nicely. A: In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above. Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js. var d = new Date(); d = new Date(d.getTime() - d.getTimezoneOffset() * 60000) var yyyymmdd = t.toISOString().slice(0, 10); // 2017-05-09T08:24:26.581Z (but this is not UTC) The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000. A: 2021 - you can use the browser native Intl.DateTimeFormat const utcDate = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738)); console.log(new Intl.DateTimeFormat().format(utcDate)); // expected output: "21/04/2021", my locale is Switzerland Below is straight from the documentation: const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738)); // Results below assume UTC timezone - your results may vary // Specify default date formatting for language (locale) console.log(new Intl.DateTimeFormat('en-US').format(date)); // expected output: "12/20/2020" // Specify default date formatting for language with a fallback language (in this case Indonesian) console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date)); // expected output: "20/12/2020" // Specify date and time format using "style" options (i.e. full, long, medium, short) console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date)); // Expected output "Sunday, 20 December 2020 at 14:23:16 GMT+11" A: getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js. There's a few more options discussed in the answer to this question A: To convert date to local date use toLocaleDateString() method. var date = (new Date(str)).toLocaleDateString(defaultlang, options); To convert time to local time use toLocaleTimeString() method. var time = (new Date(str)).toLocaleTimeString(defaultlang, options); A: A very old question but perhaps this helps someone stumbling into this. Below code formats an ISO8601 date string in a human-friendly format corresponding the user's time-zone and locale. Adapt as needed. For example: for your app, are the hours, minutes, seconds even significant to display to the user for dates more than 1 days, 1 week, 1 month, 1 year or whatever old? Also depending on your application's implementation, don't forget to re-render periodically. (In my code below at least every 24hours). export const humanFriendlyDateStr = (iso8601) => { // Examples (using Node.js): // Get an ISO8601 date string using Date() // > new Date() // 2022-04-08T22:05:18.595Z // If it was earlier today, just show the time: // > humanFriendlyDateStr('2022-04-08T22:05:18.595Z') // '3:05 PM' // If it was during the past week, add the day: // > humanFriendlyDateStr('2022-04-07T22:05:18.595Z') // 'Thu 3:05 PM' // If it was more than a week ago, add the date // > humanFriendlyDateStr('2022-03-07T22:05:18.595Z') // '3/7, 2:05 PM' // If it was more than a year ago add the year // > humanFriendlyDateStr('2021-03-07T22:05:18.595Z') // '3/7/2021, 2:05 PM' // If it's sometime in the future return the full date+time: // > humanFriendlyDateStr('2023-03-07T22:05:18.595Z') // '3/7/2023, 2:05 PM' const datetime = new Date(Date.parse(iso8601)) const now = new Date() const ageInDays = (now - datetime) / 86400000 let str // more than 1 year old? if (ageInDays > 365) { str = datetime.toLocaleDateString([], { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', }) // more than 1 week old? } else if (ageInDays > 7) { str = datetime.toLocaleDateString([], { month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', }) // more than 1 day old? } else if (ageInDays > 1) { str = datetime.toLocaleDateString([], { weekday: 'short', hour: 'numeric', minute: 'numeric', }) // some time today? } else if (ageInDays > 0) { str = datetime.toLocaleTimeString([], { timeStyle: 'short', }) // in the future? } else { str = datetime.toLocaleDateString([], { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', }) } return str } Inspired from: https://alexwlchan.net/2020/05/human-friendly-dates-in-javascript/ Tested using Node.js A: Don't know how to do locale, but javascript is a client side technology. usersLocalTime = new Date(); will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.
{ "language": "en", "url": "https://stackoverflow.com/questions/85116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "202" }
Q: Running multiple sites from a single Python web framework I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I've also seen some brutish if and elif statements for every site as shown in the following code, which I would like to avoid. if site == 'site1': ... elif site == 'site2: ... What are some good and clever ways of running multiple sites from a single, common Python web framework (i.e., Pylons, TurboGears, etc)? A: Using Django on apache with mod_python, I host multiple (unrelated) django sites simply with the following apache config: <VirtualHost 1.2.3.4> DocumentRoot /www/site1 ServerName site1.com <Location /> SetHandler python-program SetEnv DJANGO_SETTINGS_MODULE site1.settings PythonPath "['/www'] + sys.path" PythonDebug On PythonInterpreter site1 </Location> </VirtualHost> <VirtualHost 1.2.3.4> DocumentRoot /www/site2 ServerName site2.com <Location /> SetHandler python-program SetEnv DJANGO_SETTINGS_MODULE site2.settings PythonPath "['/www'] + sys.path" PythonDebug On PythonInterpreter site2 </Location> </VirtualHost> No need for multiple apache instances or proxy servers. Using a different PythonInterpreter directive for each site (the name you enter is arbitrary) keeps the namespaces separate. A: I use CherryPy as my web server (which comes bundled with Turbogears), and I simply run multiple instances of the CherryPy web server on different ports bound to localhost. Then I configure Apache with mod_proxy and mod_rewrite to transparently forward requests to the proper port based on the HTTP request. A: Using multiple server instances on local ports is a good idea, but you don't need a full featured web server to redirect HTTP requests. I would use pound as a reverse proxy to do the job. It is small, fast, simple and does exactly what we need here. WHAT POUND IS: * *a reverse-proxy: it passes requests from client browsers to one or more back-end servers. *a load balancer: it will distribute the requests from the client browsers among several back-end servers, while keeping session information. *an SSL wrapper: Pound will decrypt HTTPS requests from client browsers and pass them as plain HTTP to the back-end servers. *an HTTP/HTTPS sanitizer: Pound will verify requests for correctness and accept only well-formed ones. *a fail over-server: should a back-end server fail, Pound will take note of the fact and stop passing requests to it until it recovers. *a request redirector: requests may be distributed among servers according to the requested URL. A: Django has this built in. See the sites framework. As a general technique, include a 'host' column in your database schema attached to the data you want to be host-specific, then include the Host HTTP header in the query when you are retrieving data.
{ "language": "en", "url": "https://stackoverflow.com/questions/85119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to make thread sleep less than a millisecond on Windows On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only Sleep with millisecond granularity. On Unix, I can use the use the select system call to create a microsecond sleep which is pretty straightforward: int usleep(long usec) { struct timeval tv; tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, 0, &tv); } How can I achieve the same on Windows? A: This indicates a mis-understanding of sleep functions. The parameter you pass is a minimum time for sleeping. There's no guarantee that the thread will wake up after exactly the time specified. In fact, threads don't "wake up" at all, but are rather chosen for execution by the OS scheduler. The scheduler might choose to wait much longer than the requested sleep duration to activate a thread, especially if another thread is still active at that moment. A: Generally a sleep will last at least until the next system interrupt occurs. However, this depends on settings of the multimedia timer resources. It may be set to something close to 1 ms, some hardware even allows to run at interrupt periods of 0.9765625 (ActualResolution provided by NtQueryTimerResolution will show 0.9766 but that's actually wrong. They just can't put the correct number into the ActualResolution format. It's 0.9765625ms at 1024 interrupts per second). There is one exception wich allows us to escape from the fact that it may be impossible to sleep for less than the interrupt period: It is the famous Sleep(0). This is a very powerful tool and it is not used as often as it should! It relinquishes the reminder of the thread's time slice. This way the thread will stop until the scheduler forces the thread to get cpu service again. Sleep(0) is an asynchronous service, the call will force the scheduler to react independent of an interrupt. A second way is the use of a waitable object. A wait function like WaitForSingleObject() can wait for an event. In order to have a thread sleeping for any time, also times in the microsecond regime, the thread needs to setup some service thread which will generate an event at the desired delay. The "sleeping" thread will setup this thread and then pause at the wait function until the service thread will set the event signaled. This way any thread can "sleep" or wait for any time. The service thread can be of big complexity and it may offer system wide services like timed events at microsecond resolution. However, microsecond resolution may force the service thread to spin on a high resolution time service for at most one interrupt period (~1ms). If care is taken, this can run very well, particulary on multi-processor or multi-core systems. A one ms spin does not hurt considerably on multi-core system, when the affinity mask for the calling thread and the service thread are carefully handled. Code, description, and testing can be visited at the Windows Timestamp Project A: As several people have pointed out, sleep and other related functions are by default dependent on the "system tick". This is the minimum unit of time between OS tasks; the scheduler, for instance, will not run faster than this. Even with a realtime OS, the system tick is not usually less than 1 ms. While it is tunable, this has implications for the entire system, not just your sleep functionality, because your scheduler will be running more frequently, and potentially increasing the overhead of your OS (amount of time for the scheduler to run, vs. amount of time a task can run). The solution to this is to use an external, high-speed clock device. Most Unix systems will allow you to specify to your timers and such a different clock to use, as opposed to the default system clock. A: As Joel says, you can't meaningfully 'sleep' (i.e. relinquish your scheduled CPU) for such short periods. If you want to delay for some short time, then you need to spin, repeatedly checking a suitably high-resolution timer (e.g. the 'performance timer') and hoping that something of high priority doesn't pre-empt you anyway. If you really care about accurate delays of such short times, you should not be using Windows. A: What are you waiting for that requires such precision? In general if you need to specify that level of precision (e.g. because of a dependency on some external hardware) you are on the wrong platform and should look at a real time OS. Otherwise you should be considering if there is an event you can synchronize on, or in the worse case just busy wait the CPU and use the high performance counter API to measure the elapsed time. A: If you want so much granularity you are in the wrong place (in user space). Remember that if you are in user space your time is not always precise. The scheduler can start your thread (or app), and schedule it, so you are depending by the OS scheduler. If you are looking for something precise you have to go: 1) In kernel space (like drivers) 2) Choose an RTOS. Anyway if you are looking for some granularity (but remember the problem with user space ) look to QueryPerformanceCounter Function and QueryPerformanceFrequency function in MSDN. A: Use the high resolution multimedia timers available in winmm.lib. See this for an example. A: Actually using this usleep function will cause a big memory/resource leak. (depending how often called) use this corrected version (sorry can't edit?) bool usleep(unsigned long usec) { struct timeval tv; fd_set dummy; SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); FD_ZERO(&dummy); FD_SET(s, &dummy); tv.tv_sec = usec / 1000000ul; tv.tv_usec = usec % 1000000ul; bool success = (0 == select(0, 0, 0, &dummy, &tv)); closesocket(s); return success; } A: #include <Windows.h> static NTSTATUS(__stdcall *NtDelayExecution)(BOOL Alertable, PLARGE_INTEGER DelayInterval) = (NTSTATUS(__stdcall*)(BOOL, PLARGE_INTEGER)) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtDelayExecution"); static NTSTATUS(__stdcall *ZwSetTimerResolution)(IN ULONG RequestedResolution, IN BOOLEAN Set, OUT PULONG ActualResolution) = (NTSTATUS(__stdcall*)(ULONG, BOOLEAN, PULONG)) GetProcAddress(GetModuleHandle("ntdll.dll"), "ZwSetTimerResolution"); static void SleepShort(float milliseconds) { static bool once = true; if (once) { ULONG actualResolution; ZwSetTimerResolution(1, true, &actualResolution); once = false; } LARGE_INTEGER interval; interval.QuadPart = -1 * (int)(milliseconds * 10000.0f); NtDelayExecution(false, &interval); } Works very well for sleeping extremely short times. Remember though that at a certain point the actual delays will never be consistent because the system can't maintain consistent delays of such a short time. A: I have the same problem and nothing seems to be faster than a ms, even the Sleep(0). My problem is the communication between a client and a server application where I use the _InterlockedExchange function to test and set a bit and then I Sleep(0). I really need to perform thousands of operations per second this way and it doesn't work as fast as I planned. Since I have a thin client dealing with the user, which in turn invokes an agent which then talks to a thread, I will move soon to merge the thread with the agent so that no event interface will be required. Just to give you guys an idea how slow this Sleep is, I ran a test for 10 seconds performing an empty loop (getting something like 18,000,000 loops) whereas with the event in place I only got 180,000 loops. That is, 100 times slower! A: Try using SetWaitableTimer... A: Yes, you need to understand your OS' time quantums. On Windows, you won't even be getting 1ms resolution times unless you change the time quantum to 1ms. (Using for example timeBeginPeriod()/timeEndPeriod()) That still won't really guarantee anything. Even a little load or a single crappy device driver will throw everything off. SetThreadPriority() helps, but is quite dangerous. Bad device drivers can still ruin you. You need an ultra-controlled computing environment to make this ugly stuff work at all. A: Like everybody mentioned, there is indeed no guarantees about the sleep time. But nobody wants to admit that sometimes, on an idle system, the usleep command can be very precise. Especially with a tickless kernel. Windows Vista has it and Linux has it since 2.6.16. Tickless kernels exists to help improve laptops batterly life: c.f. Intel's powertop utility. In that condition, I happend to have measured the Linux usleep command that respected the requested sleep time very closely, down to half a dozen of micro seconds. So, maybe the OP wants something that will roughly work most of the time on an idling system, and be able to ask for micro second scheduling! I actually would want that on Windows too. Also Sleep(0) sounds like boost::thread::yield(), which terminology is clearer. I wonder if Boost-timed locks have a better precision. Because then you could just lock on a mutex that nobody ever releases, and when the timeout is reached, continue on... Timeouts are set with boost::system_time + boost::milliseconds & cie (xtime is deprecated). A: If your goal is to "wait for a very short amount of time" because you are doing a spinwait, then there are increasing levels of waiting you can perform. void SpinOnce(ref Int32 spin) { /* SpinOnce is called each time we need to wait. But the action it takes depends on how many times we've been spinning: 1..12 spins: spin 2..4096 cycles 12..32: call SwitchToThread (allow another thread ready to go on time core to execute) over 32 spins: Sleep(0) (give up the remainder of our timeslice to any other thread ready to run, also allows APC and I/O callbacks) */ spin += 1; if (spin > 32) Sleep(0); //give up the remainder of our timeslice else if (spin > 12) SwitchTothread(); //allow another thread on our CPU to have the remainder of our timeslice else { int loops = (1 << spin); //1..12 ==> 2..4096 while (loops > 0) loops -= 1; } } So if your goal is actually to wait only for a little bit, you can use something like: int spin = 0; while (!TryAcquireLock()) { SpinOne(ref spin); } The virtue here is that we wait longer each time, eventually going completely to sleep. A: Just use Sleep(0). 0 is clearly less than a millisecond. Now, that sounds funny, but I'm serious. Sleep(0) tells Windows that you don't have anything to do right now, but that you do want to be reconsidered as soon as the scheduler runs again. And since obviously the thread can't be scheduled to run before the scheduler itself runs, this is the shortest delay possible. Note that you can pass in a microsecond number to your usleep, but so does void usleep(__int64 t) { Sleep(t/1000); } - no guarantees to actually sleeping that period. A: Sleep function that is way less than a millisecond-maybe I found that sleep(0) worked for me. On a system with a near 0% load on the cpu in task manager, I wrote a simple console program and the sleep(0) function slept for a consistent 1-3 microseconds, which is way less than a millisecond. But from the above answers in this thread, I know that the amount sleep(0) sleeps can vary much more wildly than this on systems with a large cpu load. But as I understand it, the sleep function should not be used as a timer. It should be used to make the program use the least percentage of the cpu as possible and execute as frequently as possible. For my purposes, such as moving a projectile across the screen in a videogame much faster than one pixel a millisecond, sleep(0) works, I think. You would just make sure the sleep interval is way smaller than the largest amount of time it would sleep. You don't use the sleep as a timer but just to make the game use the minimum amount of cpu percentage possible. You would use a separate function that has nothing to do is sleep to get to know when a particular amount of time has passed and then move the projectile one pixel across the screen-at a time of say 1/10th of a millisecond or 100 microseconds. The pseudo-code would go something like this. while (timer1 < 100 microseconds) { sleep(0); } if (timer2 >=100 microseconds) { move projectile one pixel } //Rest of code in iteration here I know the answer may not work for advanced issues or programs but may work for some or many programs. A: If the machine is running Windows 10 version 1803 or later then you can use CreateWaitableTimerExW with the CREATE_WAITABLE_TIMER_HIGH_RESOLUTION flag. A: On Windows the use of select forces you to include the Winsock library which has to be initialized like this in your application: WORD wVersionRequested = MAKEWORD(1,0); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); And then the select won't allow you to be called without any socket so you have to do a little more to create a microsleep method: int usleep(long usec) { struct timeval tv; fd_set dummy; SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); FD_ZERO(&dummy); FD_SET(s, &dummy); tv.tv_sec = usec/1000000L; tv.tv_usec = usec%1000000L; return select(0, 0, 0, &dummy, &tv); } All these created usleep methods return zero when successful and non-zero for errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/85122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "64" }
Q: Best way to set up CruiseControl for IIS 5.1 dev box and IIS6 server Can anyone point me in the right direction on this. From reading the FAQs at cruisecontrol, it appears that you should develop in the same environment as you produce. But i have Windows XP (which only runs IIS 5.1) on my dev machine and the server is 2003. A: We have a similar setup that we have been using successfully over a year now. Our CC.Net server is on a Windows 2003 server and all development happens on Windows XP/Vista machines. Code checked into SVN is pulled down onto the Windows 2003 server, built and pushed onto our hosting boxes.
{ "language": "en", "url": "https://stackoverflow.com/questions/85129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add an event to a class Say I have a class named Frog, it looks like: public class Frog { public int Location { get; set; } public int JumpCount { get; set; } public void OnJump() { JumpCount++; } } I need help with 2 things: * *I want to create an event named Jump in the class definition. *I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps. A: Here is a sample of how to use a normal EventHandler, or a custom delegate. Note that ?. is used instead of . to insure that if the event is null, it will fail cleanly (return null) public delegate void MyAwesomeEventHandler(int rawr); public event MyAwesomeEventHandler AwesomeJump; public event EventHandler Jump; public void OnJump() { AwesomeJump?.Invoke(42); Jump?.Invoke(this, EventArgs.Empty); } Note that the event itself is only null if there are no subscribers, and that once invoked, the event is thread safe. So you can also assign a default empty handler to insure the event is not null. Note that this is technically vulnerable to someone else wiping out all of the events (using GetInvocationList), so use with caution. public event EventHandler Jump = delegate { }; public void OnJump() { Jump(this, EventArgs.Empty); } A: public event EventHandler Jump; public void OnJump() { EventHandler handler = Jump; if (null != handler) handler(this, EventArgs.Empty); } then Frog frog = new Frog(); frog.Jump += new EventHandler(yourMethod); private void yourMethod(object s, EventArgs e) { Console.WriteLine("Frog has Jumped!"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/85137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: C# Code Formatter for Linux and/or MonoDevelop MonoDevelop 1.0 doesn't appear to have a code-formatter like Eclipse does for Java. Is there a preferred shell script (or MonoDevelop add-in?) that you've found to work well? A: At the moment, source code formatting in MonoDevelop is marked as a future enhancement: https://bugzilla.novell.com/show_bug.cgi?id=321946 In the meantime, you may want to check out Artistic Style for C# formatting: http://astyle.sourceforge.net/ I'm planning to see how this might be wired up as an external tool within MonoDevelop. If I get to that, I will edit my answer with the information. UPDATE: I don't have enough reputation to leave a comment, so I'll make one here: Nice job, Dustin, and patch for MonoDevelop too :-) I wonder how recent the version is that is included with Ubuntu... Either way, I'm glad you found something that works for you. A: Thanks, Brandon. I submitted a patch to MonoDevelop. The issue with MonoDevelop add-ins is that there is a mono compiler bug that doesn't handle anonymous delegates correctly. (bug report: https://bugzilla.novell.com/show_bug.cgi?id=394347) The patch/workaround is to just cast the anonymous delegate to the proper delegate type. (bug report & patch: https://bugzilla.novell.com/show_bug.cgi?id=369538) I'm running with the patched version now and am able to execute AStyle on the currently edited document by simply creating a new External Tool setting with the following settings: TITLE: A_Style (put in an underscore _ to enable hotkeys) COMMAND: astyle ARGUMENTS: ${ItemPath} Then, just execute it using Tools->AStyle (or ALT-T, S) 9/25/08 Edit -- I just put up a blog posting on how to patch MonoDevelop 1.0 and get it working with AStyle: http://dustinbreese.blogspot.com/2008/09/auto-formatting-code-in-monodevelop-10.html A: It's a nice programming exercise to write your own formatter . I wrote one for C++ , and it was a nice challenge . You could learn a lot by writing it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/85139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: FormsAuthentication selective to url Is there a way to implement forms authentication, but only for a specific URL. For example, I would want the formsAuthentication to protect the site on staging.mydomain.com but not hinder access to www.mydomain.com if the web.config accidentally got moved over to the production site. A: This can be achieved, but you'll have to implement your own IHttpModule for it. Alas FormsAuthenticationModule is sealed, meaning that you would have to start from scratch, but Reflector can be a great help there. A: we have used a simple workaround in the past. We set the default Login page to be a simple page that is accessible to anonymous users, lets call it checkDomain.aspx In that page, we do a quick check of the domain and based on that we redirect users to the login.aspx page in the staging site, or to the original requested url in the production site. this wasnt pretty but it was quick and easy to implement for a short period of time when we feared something like that could happen. A: Forms auth is implemented on the web site instance. Its not going to work that way. A: The web.config is where you can manage what FormsAuthentication does. So, the answer is kind of in your question and @Andrew is right. However, you might be able to do something in your global.asax to recognize the server or domain that the site is running on and disable FormsAuthentication. Maybe create a user that has access to everything and manually set a FormsAuthenticationTicket to that user on session start if the domain is www.mydomain.com. This is a bit hackish and I would suggest coming up with an out of band way to control your web.config instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/85142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best resource for learning .NET generics? I've never used any of the .NET generics in my work, but I understand that they are fairly popular. Does anyone have any good links or book suggestions for learning them? As a bonus; I only vaguely understand what .NET generic collections are and what they do...does anyone have any practical examples of how they might be used to greater advantage than the normal collections in .NET? A: * *http://www.informit.com/articles/article.aspx?p=605369 *http://www.codeproject.com/KB/cs/genericcache.aspx A: CLR via C# by Jeffrey Richter goes into depth about generics, and is one of the priceless resources every .NET developer should own and read. A: The obvious choice.. MSDN C# Generics A: If you've ever used C++ templates, then .Net generics are nearly the same thing. They even use a similar <T> syntax. Even if you don't know any C++ you're probably making this harder than you need to, especially with regard to the collections. They're just like any other collection, but when you create them you supply a type name inside the <<>'s so the compiler knows what kind of item they hold. A: C# 3.0 in a Nutshell is a fantastic reference book with examples just big enought to grasp the concept without feeling bloated. A: I found WROX's Professional .NET 2.0 Generics very useful as it contains lots of real world examples. Generics could be confusing to the beginner but they could be a very useful/powerful/time saving tool in the hands of an experienced developer. Personally, I find .NET Generics most useful in simplifying the defining and use of collections. Also the use of generics could lead to more efficient code as it could minimize the performance hit usually associated with boxing/unboxing type conversions. A: It's best to follow some Microsoft training on the subject. If you are looking for books, the following would be ideal: http://www.microsoft.com/MSPress/books/9469.aspx A: My vote is- mostly you can just avoid them :) The main advantage for generics is to save casting, if you end up doing casting internally that doesn't make any sense. If you try to look into this issue you would found that mostly the candidates for generics are really those collections/sets which could create native storage internally for such benefit. Most other components, on the other hand, gain little/no performance, and degrades the flexibility significantly comparing to an interface inheritance implementation. If casting annoys you so much, maybe time for you to consider dynamic languages like IronPython :) And- if you really come across a scenario you think generic make sense, post it out as another question, the brains here could look together and solve it case by case :) Update: Yep compiler checking is nice, but check Castle Project's source, you can see many situations where a generic type gets into the way because you can't do casting- making things like IBusinessObject is a lot more flexible than BusinessObject- because you can't cast something inherit from BusinessObject back to BusinessObject and expects to access a function inherited. Usually I saw code end up as BusinessObjectBase -> BusinessObject ->Your actual class. That's why I kinda feel its not always beneficial to use generics- and I was one of those who did abuse such implementation and end up having tons of funny function with generic typing, not nice at all. Update #2: Boxing/Unboxing just means the requirement to cast the object when you use an abstract type (like object) to store value and use a strong typed value to store it back again (which requires casting), not much difference I can see apart from the collection situation I stated. AND code like this still does boxing: public T GetValue<T>() { return (T) ...; } Thats the generic abuse I have seen most often. People think they are dealing with native type here, in fact they are not. Instead they just make the casting into generic syntax. What really make sense is this: public class MyList<T> { private List<T> _list; ... public T GetValue(int index) { return _list[index]; } Then thats again back to our collection storage. Thats why I said after collection storage I don't see a lot of chance generic helps. Referred from this tutorial: http://en.csharp-online.net/Understanding_Generics—Revisiting_Boxing_and_Unboxing
{ "language": "en", "url": "https://stackoverflow.com/questions/85147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: A sample for jQuery based WYSIWYG Editor demonstrate OOP javascript Want a WYSIWYG jQuery Editor as an example to illustrate how to use jQuery to built OOP javascript component. P.S. It is so good stackoverflow can use markdown... Would be a heaven if users would love such thing too A: jHtmlArea - WYSIWYG HTML Editor for jQuery A simple, light weight, extensible WYSIWYG HTML Editor built on top of jQuery. This component allows you to easily display a WYSIWYG HTML Editor in place of any TextArea DOM Elements on the page. The minified script alone is 7kb, and with css and image files it's a total of 15kb. This project also include Visual Studio JavaScript Intellisense support. (source: codeplex.com) A: http://projects.bundleweb.com.ar/jWYSIWYG/ looks outdated, better try this link to jwysiwyg A: jwysiwyg looks good but there's no useful documentation at all! A: Check CleEditor http://premiumsoftware.net/cleditor/ CLEditor supports the following browsers on both the mac and pc: IE 6.0+, FF 1.5+, Safari 4+, Chrome 5+ and Opera 10+. All testing is done using jQuery 1.4.2. CLEditor provides a rich plugin development environment, allowing you to customize its user interface and functionality to fit your needs. A: http://wmd-editor.com/features#compatibility or maybe if you just have time to write/modify for your own parse (as i will do) use this: http://markitup.jaysalvat.com A: The WYSIWYG which can accept formatted text copied from Microsoft Word, are... * *CLEditor *jHTML Area *NicEdit *Xinha *jWYSIWYG I chose CLEdit, because the code is clean, and it allows me to decide how I want images to be aligned, and it doesn't have bugs like NicEdit. On NicEdit, it produces DOUBLE line breaks when HTML code is copied from other sites into the editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/85155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Time Parsing in Flex Is there any way to parse a string in the format HH:MM into a Date (or other) object using the standard libraries? I know that I can parse something like "9/17/2008 10:30" into a Date object using var date:Date = new Date(Date.parse("9/17/2008 10:30"); But I want to parse just 10:30 by itself. The following code will not work. var date:Date = new Date(Date.parse("10:30"); I know I can use a custom RegEx to do this fairly easily, but it seems like this should be possible using the existing Flex API. A: If you have to use the exact format you specified, then you need to parse it yourself. Here is a simple example (not tested): var str:String = "9/17/2008 10:30" var items:Array = str.split(" "); var dateElements:Array = items[0].split("/"); var timeElements:Array = items[1].split(":"); var n:Date = new Date(dateElements[2], dateElements[0], dateElements[1]. timeElements[0], timeElements[1]); If the time is not expressed in 24 clock, then there is no way to check for AM or PM (code will assume AM). A: As a simple and free solution, you could use some static methods of the DateField: * *DateField.stringToDate(valueString:String, inputFormat:String):Date *DateField.dateToString(value:Date, outputFattern:String):String But unfortunately they don't support hours/minutes/seconds (just the date). In your specific case: the Date object always contains also a "date" information.. if it isn't important, couldn't you simply concatenate a standard date string before parsing? A: Have you considered prepending "01/01/2000 " to the time string and then applying Date? Alternately there's probably a tokenizer that will take the input and split it up at the : giving you an array of strings you can convert to integers. A tokenizer isn't hard to write, either, and can be fun if one doesn't exist in flex. -Adam A: To answer your specific question: no, there's no library function to do what you want to do, but then there's no library function for parsing dates on the ISO format, on the German format, on the Swedish format, dates where the years are in roman numerals etc. Why not use regular expressions? That's what they are for.
{ "language": "en", "url": "https://stackoverflow.com/questions/85159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Fix argument handling in SQL Server 2005 Mgmt Studio custom Keyboard Accelerator shortcuts? I've long been a fan of Stored Procedure Keyboard Accelerators, as described in this article. When we moved from SQL 2000 to 2005, though, and from Query Analyzer to Management Studio, the handling of the arguments changed. In QA, comma-separated arguments were automatically read as two separate arguments. In SSMS -- at least for me -- it's being read as one argument, with commas in it. Similarly, if I pass in a single argument with single quotes in it, I get a syntax error, unless I escape the quotes (' -> ''). In the article linked above, the author implies that this should not be the case for SSMS, but even with her exact example, comma-separated arguments are still being interpreted as one argument on every SSMS installation I've tried it on (3 of them), running against every SQL Server installation I've tried (4 of them). E.g., typing the following into SSMS, Person,4 then selecting it and running the shortcut, I get the error message "Invalid object name 'Person,4'. Does anybody have any idea how to fix this? Does anybody even use these shortcuts? I've Googled this problem several times over the past two years, and have had no luck. Edit: May be an issue with a specific build of SSMS. I have a follow-up post below. A: I had never tried this until I read your question and then read the article you referenced, so take this with a grain of salt. That said, I am able to get the process to work on my computer using SSMS, and I am also able to duplicate the error you described. To get this to work as expected I created the sproc in the master database, assigned the keyboard shortcut and restarted SSMS. I then typed the databasename.schema_name.table_name in single quotes followed by a comma and then an integer value (the sproc I tested was the GetRows sample in the article). I was still connected to the master database. This worked without incident. To get the same error that you mentioned, I removed either the reference to the schema name or database name and received the same error you did. Perhaps you need to add the database name and schema name before the table name? A: Tim's suggestion didn't solve my problem on my development PC, but it did convince me to try again from a different PC. When using a different PC's SSMS to log into the development PC's database and trying exactly what Tim describes, I'm having the same behavior Tim describes. I was also able to re-replicate the argument parsing issue on the other PCs I had tried in the past. I'm hoping Tim can let me know what's the version and build number on his SSMS installation, because my current theory is that the problem is just from the specific build that my coworkers and I have on our dev PCs -- the version string is "Microsoft SQL Server Management Studio 9.00.1399.00". All of our installs of that version took place well over a year ago, so I don't know that I can trace back what disk it's from. The one that is NOT having the problem is actually our development server, which has "Microsoft SQL Server Management Studio 9.00.3042.00" installed. I don't know if this might be something I can make go away by patching or something, but it currently looks like 1399 reads the entire selection as a single argument, while 3042 does some pre-parsing. I've also recently found that when I pass in a string that contains "--" (comment token) in 3042, everything after the "--" is ignored, while in 1399, it's all included in the first argument. A: I am using SSMS version 9.00.3042.00 as well, which probably explains why it is working on my machine. A: Agree with Tim. I have just upgraded to SQL Server 05 sp2 and I confirm that this bug gets fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/85179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I traced a Stored Procedure as shown in the SQL Server 2005 Profiler. It's not found but works. Why? This is pretty weird. I have my Profiler open and it obviously shows that a stored procedure is called. I open the database and the SP list, but the SP doesn't exist. However, there's another SP whose name is the same except it has a prefix 'x' Is SQL Server 2005 mapping the SP name to a different one for security purposes? EDIT: I found out it's a Synonym, whatever that is. A: In general, when you know an object exists because it's been used in a query, and you can't find it in the object tree in Management Studio, you can do this to find it. select * from sys.objects where name = 'THE_NAME_YOU_WANT' I just checked, and it works with Synonyms. A: Possibly silly questions, but just in case... have you refreshed the SP list? Have you checked for a stored procedure of that name under a different owner? If you created the stored procedure without specifying the owner then it could be in the list under your ownership (or not at all if the list is filtered to only "dbo" for example). A: You may not have permission to see all the objects in the database A: Adding to the previous answers, it could also be under "System Stored Procedures", and if the name of the stored procedure begins with "sp_", it could also be in the master database. A: The stored procedure will be inside the database you have selected at time of stored procedure creation. So search inside the database from which it is extracting data, otherwise it will be inside the master database. If still you are not able to find then first number solution is best one. i.e. select * from sys.objects where name = 'name of stored procedure'
{ "language": "en", "url": "https://stackoverflow.com/questions/85181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windsor Container: How to force dispose of an object? I have an object that implements IDisposable that is registered with the Windsor Container and I would like to dispose of it so it's Dispose method is called and next time Resolve is called it fetches a new instance. Does container.Release(obj); automatically call Dispose() immediately? Or do I need to do obj.Dispose(); container.Release(obj); Couldn't find anything in the documentation on what exactly Release does EDIT: See my answer below for the results of tests I ran. Now the question becomes, how do I force the container to release an instance of a component with a singleton lifecycle? This only needs to be done in one place and writing a custom lifecycle seems far too heavyweight, is there no built in way of doing it? A: It depends on the lifestyle of the component you specified when you added it to the container. You would use Release() If the lifestyle is Pooled. This puts the component back in the pool for the next retrieval (the object is not destroyed, so disposing would be bad) if the lifestyle is transient, a new object is created when you get the component. In this case the disposal is up to you, and you do not need to call Release If the lifestyle is Thread, the same component is used for each thread, not destroyed. If the lifestyle is Singleton, only one component is created and not detroyed. Most likely, you are using transient components? (if you are concerned about disposing of them in a timely manner) in that case, just wrap it with a using and you're set (or call the dispose yourself somewhere) using(ISomeService service = container.Resolve<ISomeService>()) { // Do stuff here // service.Dispose is automatically called } Edit - Yes, in order to "refresh" or dispose and recreate your singleton you would need to either destroy the container or write a custom lifecycle. Doing a custom lifecycle is not actually that difficult and keeps the logic to do so in one place. A: This is something I think people aren't really aware of when working with the Windsor container - especially the often surprising behavior that disposable transient components are held onto by the container for the lifetime of the kernel until it's disposed unless you release them yourself - though it is documented - take a look here - but to quickly quote: the MicroKernel has a pluggable release policy that can hook up and implement some routing to dispose the components. The MicroKernel comes with three IReleasePolicy implementations: * *AllComponentsReleasePolicy: track all components to enforce correct disposal upon the MicroKernel instance disposal *LifecycledComponentsReleasePolicy: only track components that have a decommission lifecycle associated *NoTrackingReleasePolicy: does not perform any tracking You can also implement your own release policy by using the interface IReleasePolicy. What you might find easier is to change the policy to a NoTrackingReleasePolicy and then handle the disposing yourself - this is potentially risky as well, but if your lifestyles are largely transient (or if when your container is disposed your application is about to close anyway) it's probably not a big deal. Remember however that any components which have already been injected with the singleton will hold a reference, so you could end up causing problems trying to "refresh" your singletons - it seems like a bad practice, and I wonder if perhaps you can avoid having to do this in the first place by improving the way your applications put together. Other approaches are to build a custom lifecycle with it's own decommission implementation (so releasing the singleton would actually dispose of the component, much like the transient lifecycle does). Alternatively another approach is to have a decorator for your service registered in the container with a singleton lifestyle, but your actual underlying service registered in the container with a transient lifestyle - then when you need to refresh the component just dispose of the transient underlying component held by the decorator and replace it with a freshly resolved instance (resolve it using the components key, rather then the service, to avoid getting the decorator) - this avoids issues with other singleton services (which aren't being "refreshed") from holding onto stale services which have been disposed of making them unusable, but does require a bit of casting etc. to make it work. A: Alright, so I've been running tests and it seems like Container.Release() WILL implicitly cause an IDisposable's Dispose() method to execute only if the lifestyle is Transient (this is probably not exactly correct but point is that it wont' do a darn thing if the lifestyle is singleton). Now if you call Container.Dispose() it WILL call the disposable methods also, though unfortunately it will dispose of the whole kernel and you will have to add all components back in: var container = new WindsorContainer(); container.AddComponentWithLifestyle<MyDisposable>(Castle.Core.LifestyleType.Singleton); var obj = container.Resolve<MyDisposable>(); // Create a new instance of MyDisposable obj.DoSomething(); var obj2 = container.Resolve<MyDisposable>(); // Returns the same instance as obj obj2.DoSomething(); container.Dispose(); // Will call the Disposable method of obj // Now the components need to be added back in container.AddComponentWithLifestyle<MyDisposable>(Castle.Core.LifestyleType.Singleton); var obj3 = container.Resolve<MyDisposable>(); // Create a new instance of MyDisposable Fortunately in my case I can afford to just drop all components and I can restore them fairly easily. However this is sub-optimal.
{ "language": "en", "url": "https://stackoverflow.com/questions/85183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: mysqldump equivalent for SQL Server Is there an equivalent schema & data export/dumping tool for SQL Server as there is for MySQL with mysqldump. Trying to relocate a legacy ASP site and I am way out of happy place with working on a windows server. Note: The DTS export utility own seems to export data, without table defs. Using the Enterprise Manager and exporting the db gets closer with exporting the schema & data... but still misses stored procedures. Basically looking for a one does it all solution that grabs everything I need at once. A: Not finding the right tool, I decided to create my own: a sqlserverdump command line utility. Check it out on github. A: To do this really easily with SQL Server 2008 Management Studio: 1.) Right click on the database (not the table) and select Tasks -> Generate Scripts 2.) Click Next on the first page 3.) If you want to copy the whole database, just click next. If you want to copy specific tables, click on "Select Specific Database Objects", select the tables you want, and then click next. 4.) "Save to File" should be selected. IMPORTANT: Click the Advanced button next to "Save to File", find "Types of data to script", and change "Schema only" to "Schema and data" (if you want to create the table) or "Data only" (if you're copying data to an existing table). 5.) Click through the rest and you're done! It will save as a .sql file. A: Even easier is to use the SMO API. It lets you do exactly like mysqldump, and even better. Here is a code example: http://samyem.blogspot.com/2010/01/automate-sql-dumps-for-sqlserver.html A: The easiest way is the sql server database publishing wizard. * *Open source *Free *Does exactly what you want *Developed by microsoft It does not have all the features of mysqldump but it is close enough. http://www.codeplex.com/sqlhost/wiki/view.aspx?title=database%20publishing%20wizard A: The easiest way to move a Database would be to use SQL Server Management Studio to Export the database to another server, or if that doesn't work, make a backup like other's had suggested and restore it elsewhere. If you are looking for a way to dump the table structure to SQL as well as create insert scripts for the data a good free option would be to use amScript and amInsert from http://www.asql.biz/en/Download2005.aspx. If you want a good pay version I would check out Red-Gate SQL Compare and Red-Gate SQL-Data Compare. These tools are probably overkill though and probably a bit pricey if you don't intend to use them a lot. I would think it would mostly be relegated to DBAs. You can look at the Red-Gate tools at http://www.red-gate.com/. A: Well, Mysqldump is a series of SQL statements. You can do this with DTS, but why not just create a backup and restore it on your new machine? If you want to do it via SQL: http://msdn.microsoft.com/en-us/library/aa225964(SQL.80).aspx Or just right click the DB and hit Tasks -> Backup (http://msdn.microsoft.com/en-us/library/ms187510.aspx) A: easiest would be a backup and restore or detach and attach or script out all the tables and BCP out the data then BCP in the data on the new server or use DTS/SSIS to do this A: SQL Enterprise manager or SQL Server Management studio have wizard based approaches, and the latter will generate the scripts so you can see how its done. You could also use the BACKUP and RESTORE commands. More detail here: http://msdn.microsoft.com/en-us/library/ms189826.aspx A: If you can get DTS or Integration Services to connect to both servers, you can use the wizards to 'copy objects' from one server to another. 'Copy Database' requires that the two servers can authenticate with each other, which typically means being on the same domain and that the service runs under a domain logon. Otherwise, you can generate a script for the schema, and you can use an Integration Services/DTS package to export data to a file, then import it on the other. We now generally use SQL Compare and SQL Data Compare. Red Gate's SQL Packager might also be an option. A: Two things a backup/restore won't do: * *Get off of a Microsoft server, which was part of the original question *Help quickly find a structural difference between two DBs that are supposed to have the same structure when one of them is running slowly. Unix diff, or sdiff, ignoring white space but need a way to make input files. A: If you need equivalent SQL statements like CREATE TABLE... & INSERT INTO..., then I recommend you try HeidiSQL. It's a fantastic and free utility that can access Microsoft SQL Server, MySQL and PostgreSQL. It enables you to browse and edit data, create and edit tables, views, procedures, triggers and scheduled events. Also, you can export structure and data to SQL file. http://www.heidisql.com Go to Tools / Export database as SQL and select the schema. Check the box to create the tables and “Insert” data. That’s it. I prefer HeidiSQL to "Microsoft SQL Server Management Studio" or phpMyAdmin... etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/85186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How does the Java 'for each' loop work? Consider: List<String> someList = new ArrayList<String>(); // add "monkey", "donkey", "skeleton key" to someList for (String item : someList) { System.out.println(item); } What would the equivalent for loop look like without using the for each syntax? A: It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below. Normal for loop: void cancelAll(Collection<TimerTask> list) { for (Iterator<TimerTask> i = list.iterator(); i.hasNext();) i.next().cancel(); } Using for-each: void cancelAll(Collection<TimerTask> list) { for (TimerTask t : list) t.cancel(); } for-each is a construct over a collection that implements Iterator. Remember that, your collection should implement Iterator; otherwise you can't use it with for-each. The following line is read as "for each TimerTask t in list." for (TimerTask t : list) There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors). A: Prior to Java 8, you need to use the following: Iterator<String> iterator = someList.iterator(); while (iterator.hasNext()) { String item = iterator.next(); System.out.println(item); } However, with the introduction of Streams in Java 8 you can do same thing in much less syntax. For example, for your someList you can do: someList.stream().forEach(System.out::println); You can find more about streams here. A: As many of other answers correctly state, the for each loop is just syntactic sugar over the same old for loop and the compiler translates it to the same old for loop. javac (OpenJDK) has a switch, -XD-printflat, which generates a Java file with all the syntactic sugar removed. The complete command looks like this: javac -XD-printflat -d src/ MyFile.java //-d is used to specify the directory for output java file So let’s remove the syntactical sugar To answer this question, I created a file and wrote two versions of for each, one with array and another with a list. My Java file looked like this: import java.util.*; public class Temp{ private static void forEachArray(){ int[] arr = new int[]{1,2,3,4,5}; for(int i: arr){ System.out.print(i); } } private static void forEachList(){ List<Integer> list = Arrays.asList(1,2,3,4,5); for(Integer i: list){ System.out.print(i); } } } When I compiled this file with above switch, I got the following output. import java.util.*; public class Temp { public Temp() { super(); } private static void forEachArray() { int[] arr = new int[]{1, 2, 3, 4, 5}; for (/*synthetic*/ int[] arr$ = arr, len$ = arr$.length, i$ = 0; i$ < len$; ++i$) { int i = arr$[i$]; { System.out.print(i); } } } private static void forEachList() { List list = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5)}); for (/*synthetic*/ Iterator i$ = list.iterator(); i$.hasNext(); ) { Integer i = (Integer)i$.next(); { System.out.print(i); } } } } You can see that along with the other syntactic sugar (Autoboxing), for each loops got changed to simple loops. A: It would look something like this. Very crufty. for (Iterator<String> i = someList.iterator(); i.hasNext(); ) System.out.println(i.next()); There is a good writeup on for each in the Sun documentation. A: As so many good answers said, an object must implement the Iterable interface if it wants to use a for-each loop. I'll post a simple example and try to explain in a different way how a for-each loop works. The for-each loop example: public class ForEachTest { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); for (String str : list) { System.out.println(str); } } } Then, if we use javap to decompile this class, we will get this bytecode sample: public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=4, args_size=1 0: new #16 // class java/util/ArrayList 3: dup 4: invokespecial #18 // Method java/util/ArrayList."<init>":()V 7: astore_1 8: aload_1 9: ldc #19 // String 111 11: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z 16: pop 17: aload_1 18: ldc #27 // String 222 20: invokeinterface #21, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z 25: pop 26: aload_1 27: invokeinterface #29, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator; As we can see from the last line of the sample, the compiler will automatically convert the use of for-each keyword to the use of an Iterator at compile time. That may explain why object, which doesn't implement the Iterable interface, will throw an Exception when it tries to use the for-each loop. A: The Java for each loop (aka enhanced for loop) is a simplified version of a for loop. The advantage is that there is less code to write and less variables to manage. The downside is that you have no control over the step value and no access to the loop index inside the loop body. They are best used when the step value is a simple increment of 1 and when you only need access to the current loop element. For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element. There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops. Enhanced for loops follow this order of execution: 1) loop body 2) repeat from step 1 until entire array or collection has been traversed Example – Integer Array int [] intArray = {1, 3, 5, 7, 9}; for(int currentValue : intArray) { System.out.println(currentValue); } The currentValue variable holds the current value being looped over in the intArray array. Notice there’s no explicit step value – it’s always an increment by 1. The colon can be thought of to mean “in”. So the enhanced for loop declaration states: loop over intArray and store the current array int value in the currentValue variable. Output: 1 3 5 7 9 Example – String Array We can use the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the current String value in the currentString variable. String [] myStrings = { "alpha", "beta", "gamma", "delta" }; for(String currentString : myStrings) { System.out.println(currentString); } Output: alpha beta gamma delta Example – List The enhanced for loop can also be used to iterate over a java.util.List as follows: List<String> myList = new ArrayList<String>(); myList.add("alpha"); myList.add("beta"); myList.add("gamma"); myList.add("delta"); for(String currentItem : myList) { System.out.println(currentItem); } The loop declaration states: loop over myList List of Strings and store the current List value in the currentItem variable. Output: alpha beta gamma delta Example – Set The enhanced for loop can also be used to iterate over a java.util.Set as follows: Set<String> mySet = new HashSet<String>(); mySet.add("alpha"); mySet.add("alpha"); mySet.add("beta"); mySet.add("gamma"); mySet.add("gamma"); mySet.add("delta"); for(String currentItem : mySet) { System.out.println(currentItem); } The loop declaration states: loop over mySet Set of Strings and store the current Set value in the currentItem variable. Notice that since this is a Set, duplicate String values are not stored. Output: alpha delta beta gamma Source: Loops in Java – Ultimate Guide A: The construct for each is also valid for arrays. e.g. String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" }; for (String fruit : fruits) { // fruit is an element of the `fruits` array. } which is essentially equivalent of for (int i = 0; i < fruits.length; i++) { String fruit = fruits[i]; // fruit is an element of the `fruits` array. } So, overall summary: [nsayer] The following is the longer form of what is happening: for(Iterator<String> i = someList.iterator(); i.hasNext(); ) { String item = i.next(); System.out.println(item); } Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for( : ) idiom, since the actual Iterator is merely inferred. [Denis Bueno] It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax. A: public static Boolean Add_Tag(int totalsize) { List<String> fullst = new ArrayList<String>(); for(int k=0; k<totalsize; k++) { fullst.addAll(); } } A: The for-each loop in Java uses the underlying iterator mechanism. So it's identical to the following: Iterator<String> iterator = someList.iterator(); while (iterator.hasNext()) { String item = iterator.next(); System.out.println(item); } A: As defined in JLS, a for-each loop can have two forms: * *If the type of expression is a subtype of Iterable then translation is as: List<String> someList = new ArrayList<String>(); someList.add("Apple"); someList.add("Ball"); for (String item : someList) { System.out.println(item); } // Is translated to: for(Iterator<String> stringIterator = someList.iterator(); stringIterator.hasNext(); ) { String item = stringIterator.next(); System.out.println(item); } *If the expression necessarily has an array type T[] then: String[] someArray = new String[2]; someArray[0] = "Apple"; someArray[1] = "Ball"; for(String item2 : someArray) { System.out.println(item2); } // Is translated to: for (int i = 0; i < someArray.length; i++) { String item2 = someArray[i]; System.out.println(item2); } Java 8 has introduced streams which perform generally better with a decent size dataset. We can use them as: someList.stream().forEach(System.out::println); Arrays.stream(someArray).forEach(System.out::println); A: The Java for-each idiom can only be applied to arrays or objects of type *Iterable. This idiom is implicit as it truly backed by an Iterator. The Iterator is programmed by the programmer and often uses an integer index or a node (depending on the data structure) to keep track of its position. On paper it is slower than a regular for-loop, a least for "linear" structures like arrays and Lists but it provides greater abstraction. A: It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax. A: A foreach loop syntax is: for (type obj:array) {...} Example: String[] s = {"Java", "Coffe", "Is", "Cool"}; for (String str:s /*s is the array*/) { System.out.println(str); } Output: Java Coffe Is Cool WARNING: You can access array elements with the foreach loop, but you can NOT initialize them. Use the original for loop for that. WARNING: You must match the type of the array with the other object. for (double b:s) // Invalid-double is not String If you want to edit elements, use the original for loop like this: for (int i = 0; i < s.length-1 /*-1 because of the 0 index */; i++) { if (i==1) //1 because once again I say the 0 index s[i]="2 is cool"; else s[i] = "hello"; } Now if we dump s to the console, we get: hello 2 is cool hello hello A: The Java "for-each" loop construct will allow iteration over two types of objects: * *T[] (arrays of any type) *java.lang.Iterable<T> The Iterable<T> interface has only one method: Iterator<T> iterator(). This works on objects of type Collection<T> because the Collection<T> interface extends Iterable<T>. A: In Java 8 features you can use this: List<String> messages = Arrays.asList("First", "Second", "Third"); void forTest(){ messages.forEach(System.out::println); } Output First Second Third A: The for-each loop, added in Java 5 (also called the "enhanced for loop"), is equivalent to using a java.util.Iterator--it's syntactic sugar for the same thing. Therefore, when reading each element, one by one and in order, a for-each should always be chosen over an iterator, as it is more convenient and concise. For-each for (int i : intList) { System.out.println("An element in the list: " + i); } Iterator Iterator<Integer> intItr = intList.iterator(); while (intItr.hasNext()) { System.out.println("An element in the list: " + intItr.next()); } There are situations where you must use an Iterator directly. For example, attempting to delete an element while using a for-each can (will?) result in a ConcurrentModificationException. For-each vs. for-loop: Basic differences The only practical difference between for-loop and for-each is that, in the case of indexable objects, you do not have access to the index. An example when the basic for-loop is required: for (int i = 0; i < array.length; i++) { if(i < 5) { // Do something special } else { // Do other stuff } } Although you could manually create a separate index int-variable with for-each, int idx = -1; for (int i : intArray) { idx++; ... } ...it is not recommended, since variable-scope is not ideal, and the basic for loop is simply the standard and expected format for this use case. For-each vs. for-loop: Performance When accessing collections, a for-each is significantly faster than the basic for loop's array access. When accessing arrays, however--at least with primitive and wrapper-arrays--access via indexes is dramatically faster. Timing the difference between iterator and index access for primitive int-arrays Indexes are 23-40 percent faster than iterators when accessing int or Integer arrays. Here is the output from the testing class at the bottom of this post, which sums the numbers in a 100-element primitive-int array (A is iterator, B is index): [C:\java_code\]java TimeIteratorVsIndexIntArray 1000000 Test A: 358,597,622 nanoseconds Test B: 269,167,681 nanoseconds B faster by 89,429,941 nanoseconds (24.438799231635727% faster) [C:\java_code\]java TimeIteratorVsIndexIntArray 1000000 Test A: 377,461,823 nanoseconds Test B: 278,694,271 nanoseconds B faster by 98,767,552 nanoseconds (25.666236154695838% faster) [C:\java_code\]java TimeIteratorVsIndexIntArray 1000000 Test A: 288,953,495 nanoseconds Test B: 207,050,523 nanoseconds B faster by 81,902,972 nanoseconds (27.844689860906513% faster) [C:\java_code\]java TimeIteratorVsIndexIntArray 1000000 Test A: 375,373,765 nanoseconds Test B: 283,813,875 nanoseconds B faster by 91,559,890 nanoseconds (23.891659337194227% faster) [C:\java_code\]java TimeIteratorVsIndexIntArray 1000000 Test A: 375,790,818 nanoseconds Test B: 220,770,915 nanoseconds B faster by 155,019,903 nanoseconds (40.75164734599769% faster) [C:\java_code\]java TimeIteratorVsIndexIntArray 1000000 Test A: 326,373,762 nanoseconds Test B: 202,555,566 nanoseconds B faster by 123,818,196 nanoseconds (37.437545972215744% faster) I also ran this for an Integer array, and indexes are still the clear winner, but only between 18 and 25 percent faster. For collections, iterators are faster than indexes For a List of Integers, however, iterators are the clear winner. Just change the int-array in the test-class to: List<Integer> intList = Arrays.asList(new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100}); And make the necessary changes to the test-function (int[] to List<Integer>, length to size(), etc.): [C:\java_code\]java TimeIteratorVsIndexIntegerList 1000000 Test A: 3,429,929,976 nanoseconds Test B: 5,262,782,488 nanoseconds A faster by 1,832,852,512 nanoseconds (34.326681820485675% faster) [C:\java_code\]java TimeIteratorVsIndexIntegerList 1000000 Test A: 2,907,391,427 nanoseconds Test B: 3,957,718,459 nanoseconds A faster by 1,050,327,032 nanoseconds (26.038700083921256% faster) [C:\java_code\]java TimeIteratorVsIndexIntegerList 1000000 Test A: 2,566,004,688 nanoseconds Test B: 4,221,746,521 nanoseconds A faster by 1,655,741,833 nanoseconds (38.71935684115413% faster) [C:\java_code\]java TimeIteratorVsIndexIntegerList 1000000 Test A: 2,770,945,276 nanoseconds Test B: 3,829,077,158 nanoseconds A faster by 1,058,131,882 nanoseconds (27.134122749113843% faster) [C:\java_code\]java TimeIteratorVsIndexIntegerList 1000000 Test A: 3,467,474,055 nanoseconds Test B: 5,183,149,104 nanoseconds A faster by 1,715,675,049 nanoseconds (32.60101667104192% faster) [C:\java_code\]java TimeIteratorVsIndexIntList 1000000 Test A: 3,439,983,933 nanoseconds Test B: 3,509,530,312 nanoseconds A faster by 69,546,379 nanoseconds (1.4816434912159906% faster) [C:\java_code\]java TimeIteratorVsIndexIntList 1000000 Test A: 3,451,101,466 nanoseconds Test B: 5,057,979,210 nanoseconds A faster by 1,606,877,744 nanoseconds (31.269164666060377% faster) In one test they're almost equivalent, but with collections, iterator wins. *This post is based on two answers I wrote on Stack Overflow: * *Uses and syntax for for-each loop in Java *Should I use an Iterator or a forloop to iterate? Some more information: Which is more efficient, a for-each loop, or an iterator? The full testing class I created this compare-the-time-it-takes-to-do-any-two-things class after reading this question on Stack Overflow: import java.text.NumberFormat; import java.util.Locale; /** &lt;P&gt;{@code java TimeIteratorVsIndexIntArray 1000000}&lt;/P&gt; @see &lt;CODE&gt;&lt;A HREF=&quot;https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java&quot;&gt;https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java&lt;/A&gt;&lt;/CODE&gt; **/ public class TimeIteratorVsIndexIntArray { public static final NumberFormat nf = NumberFormat.getNumberInstance(Locale.US); public static final void main(String[] tryCount_inParamIdx0) { int testCount; // Get try-count from a command-line parameter try { testCount = Integer.parseInt(tryCount_inParamIdx0[0]); } catch(ArrayIndexOutOfBoundsException | NumberFormatException x) { throw new IllegalArgumentException("Missing or invalid command line parameter: The number of testCount for each test. " + x); } //Test proper...START int[] intArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100}; long lStart = System.nanoTime(); for(int i = 0; i < testCount; i++) { testIterator(intArray); } long lADuration = outputGetNanoDuration("A", lStart); lStart = System.nanoTime(); for(int i = 0; i < testCount; i++) { testFor(intArray); } long lBDuration = outputGetNanoDuration("B", lStart); outputGetABTestNanoDifference(lADuration, lBDuration, "A", "B"); } private static final void testIterator(int[] int_array) { int total = 0; for(int i = 0; i < int_array.length; i++) { total += int_array[i]; } } private static final void testFor(int[] int_array) { int total = 0; for(int i : int_array) { total += i; } } //Test proper...END //Timer testing utilities...START public static final long outputGetNanoDuration(String s_testName, long l_nanoStart) { long lDuration = System.nanoTime() - l_nanoStart; System.out.println("Test " + s_testName + ": " + nf.format(lDuration) + " nanoseconds"); return lDuration; } public static final long outputGetABTestNanoDifference(long l_aDuration, long l_bDuration, String s_aTestName, String s_bTestName) { long lDiff = -1; double dPct = -1.0; String sFaster = null; if(l_aDuration > l_bDuration) { lDiff = l_aDuration - l_bDuration; dPct = 100.00 - (l_bDuration * 100.0 / l_aDuration + 0.5); sFaster = "B"; } else { lDiff = l_bDuration - l_aDuration; dPct = 100.00 - (l_aDuration * 100.0 / l_bDuration + 0.5); sFaster = "A"; } System.out.println(sFaster + " faster by " + nf.format(lDiff) + " nanoseconds (" + dPct + "% faster)"); return lDiff; } //Timer testing utilities...END } A: The concept of a foreach loop as mentioned in Wikipedia is highlighted below: Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. So the concept of a foreach loop describes that the loop does not use any explicit counter which means that there is no need of using indexes to traverse in the list thus it saves user from off-by-one error. To describe the general concept of this off-by-one error, let us take an example of a loop to traverse in a list using indexes. // In this loop it is assumed that the list starts with index 0 for(int i=0; i<list.length; i++){ } But suppose if the list starts with index 1 then this loop is going to throw an exception as it will found no element at index 0 and this error is called an off-by-one error. So to avoid this off-by-one error the concept of a foreach loop is used. There may be other advantages too, but this is what I think is the main concept and advantage of using a foreach loop. A: In Java 8, they introduced forEach. Using it List, Maps can be looped. Loop a List using for each List<String> someList = new ArrayList<String>(); someList.add("A"); someList.add("B"); someList.add("C"); someList.forEach(listItem -> System.out.println(listItem)) or someList.forEach(listItem-> { System.out.println(listItem); }); Loop a Map using for each Map<String, String> mapList = new HashMap<>(); mapList.put("Key1", "Value1"); mapList.put("Key2", "Value2"); mapList.put("Key3", "Value3"); mapList.forEach((key,value)->System.out.println("Key: " + key + " Value : " + value)); or mapList.forEach((key,value)->{ System.out.println("Key : " + key + " Value : " + value); }); A: Here's an equivalent expression. for(Iterator<String> sit = someList.iterator(); sit.hasNext(); ) { System.out.println(sit.next()); } A: Using older Java versions, including Java 7, you can use a foreach loop as follows. List<String> items = new ArrayList<>(); items.add("A"); items.add("B"); items.add("C"); items.add("D"); items.add("E"); for(String item : items) { System.out.println(item); } The following is the very latest way of using a for each loop in Java 8 (loop a List with forEach + lambda expression or method reference). Lambda // Output: A,B,C,D,E items.forEach(item->System.out.println(item)); Method reference // Output: A,B,C,D,E items.forEach(System.out::println); For more information, refer to "Java 8 forEach examples". A: Here is an answer which does not assume knowledge of Java Iterators. It is less precise, but it is useful for education. While programming we often write code that looks like the following: char[] grades = .... for(int i = 0; i < grades.length; i++) { // for i goes from 0 to grades.length System.out.print(grades[i]); // Print grades[i] } The foreach syntax allows this common pattern to be written in a more natural and less syntactically noisy way. for(char grade : grades) { // foreach grade in grades System.out.print(grade); // print that grade } Additionally this syntax is valid for objects such as Lists or Sets which do not support array indexing, but which do implement the Java Iterable interface. A: for (Iterator<String> itr = someList.iterator(); itr.hasNext(); ) { String item = itr.next(); System.out.println(item); } A: for (Iterator<String> i = someIterable.iterator(); i.hasNext();) { String item = i.next(); System.out.println(item); } Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred. As was noted by Denis Bueno, this code works for any object that implements the Iterable interface. Also, if the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. See the Java Language Specification. A: Also note that using the "foreach" method in the original question does have some limitations, such as not being able to remove items from the list during the iteration. The new for-loop is easier to read and removes the need for a separate iterator, but is only really usable in read-only iteration passes. A: An alternative to forEach in order to avoid your "for each": List<String> someList = new ArrayList<String>(); Variant 1 (plain): someList.stream().forEach(listItem -> { System.out.println(listItem); }); Variant 2 (parallel execution (faster)): someList.parallelStream().forEach(listItem -> { System.out.println(listItem); }); A: This looks crazy but hey it works List<String> someList = new ArrayList<>(); //has content someList.forEach(System.out::println); This works. Magic A: I think this will work: for (Iterator<String> i = someList.iterator(); i.hasNext(); ) { String x = i.next(); System.out.println(x); } A: The code would be: import java.util.ArrayList; import java.util.List; public class ForLoopDemo { public static void main(String[] args) { List<String> someList = new ArrayList<String>(); someList.add("monkey"); someList.add("donkey"); someList.add("skeleton key"); // Iteration using For Each loop System.out.println("Iteration using a For Each loop:"); for (String item : someList) { System.out.println(item); } // Iteration using a normal For loop System.out.println("\nIteration using normal For loop: "); for (int index = 0; index < someList.size(); index++) { System.out.println(someList.get(index)); } } } A: Using forEach: int[] numbers = {1,2,3,4,5}; Arrays.stream(numbers).forEach(System.out::println); Response: 1 2 3 4 5 The process finished with exit code 0 PS: You need a Array (int[] numbers), and import java.util.Arrays;
{ "language": "en", "url": "https://stackoverflow.com/questions/85190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1701" }
Q: Best way to version control T-SQL? Possible Duplicate: Stored procedures/DB schema in source control What's the best way to version control my tables, views, sprocs, etc? Preferably automated or at least semi-automated :) Thanks A: I asked this one yesterday and got some nice responses: Stored procedures/DB schema in source control A: The articles from K Scott Allen say it all: http://odetocode.com/Blogs/scott/archive/2008/01/31/11710.aspx A: Write migration scripts for all db changes and keep them in a repository. Enforce a policy of making all changes to the db only by running a script; that way there is a record of what has been done, and a way to revert it. Investigate whether there's a migrations framework available for your favorite language/db combination. A: I use Visual Studio 2008 Pro create Database projects (Other project types -> Database). We already use SVN as a code repository, so a project with a bunch of .sql files representing your stored procedures is just another thing to put in the repository - you can see diffs/history etc. This works the same with VSS or any other repository you use. The nice thing about Database projects is that your project will remember your connection string, and all you have to do is right click on a .sql file (or select all of them at once!) and select run to update it in the db. This makes it easy to update your .sql files from the repository and run them all to update all your stored procedures, verifying your database is updated in seconds. You can also select create a LINQ project (Visual C# -> Database) and store all your LINQ code in your repository. Hope that helps! A: If you were super lazy you could use the SMO (SQL Server Management Objects) or if using SQL Server prior to 2005 the DMO (distributed managmeent objects) to script out all tables/views/stored procedures daily and then compare the script to the script in source control and if there are any changes check the new version in. You won't be able to necessarily have as pretty of a script as if you just created all db changes in scripts, but at least you can recreate all tables/stored procedures/views. For example, in my table creation scripts there are often comments. Here is an article to get you started on scripting: http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated. Again, this is mainly if you are too lazy to bother with version control and it won't help if you change something twice in one day. Also any data migration scripts still have to be saved and checked in because this won't pick up ad hoc SQL, only database objects. A: I'm using Visual Studio Database edition which can export the schema from SQL Server in to a Visual Studio project. This is then stored in Source Control and can be deployed where ever needed. The VS Database project is just a bunch of scripts though and it's a clunky way of working. A more robust method would be to use a database migration framework and if you're working with .Net check out this blog post for a good description http://flux88.com/NETDatabaseMigrationToolRoundup.aspx. Update As mentioned in the comments, this page is no more. So here is the last known snapshot from wayback machine http://web.archive.org/web/20080828232742/http://flux88.com/NETDatabaseMigrationToolRoundup.aspx A: Try Randolph, One of the best SQL Version control tools I know. A: I have written a DDL trigger which logs all the changes done to the definition of SQL objects (triggers, tables, SP, view etc). I could very well invoke extended SP from the trigger and store the details in another Database and use that as repository. But if your team is really disciplined any source control should do the trick. The trigger is used as an audit mechanism and it's ideal for teams which are geographically scattered.
{ "language": "en", "url": "https://stackoverflow.com/questions/85195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Linking .Net Assemblies This is all hypothetical, so please bear with me. Say I'm writing a tool in C# called Foo. The output is foo.exe. I've found some really great library that I like to use called Bar, which I can reference as bar.dll in my project. When I build my project, I have foo.exe and bar.dll in my output directory. Good so far. What I'd like to do is link foo.exe and bar.dll so they are one assembly, foo.exe. I would prefer to be able to do this in VS2008, but if I have to resort to a command-line tool like al.exe I don't mind so much. A: Set up a post-build event under Project Properties: ilmerge /out:$(TargetDir)foo.exe $(TargetPath) $(TargetDir)bar.dll A: Check out the ILMerge tool found here. A: There's ILMerge. Link A: Thanks everyone who answered! I ended up with NuGenUnify which provides a GUI wrapper for ilmerge.
{ "language": "en", "url": "https://stackoverflow.com/questions/85222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to manually parse a floating point number from a string Of course most languages have library functions for this, but suppose I want to do it myself. Suppose that the float is given like in a C or Java program (except for the 'f' or 'd' suffix), for example "4.2e1", ".42e2" or simply "42". In general, we have the "integer part" before the decimal point, the "fractional part" after the decimal point, and the "exponent". All three are integers. It is easy to find and process the individual digits, but how do you compose them into a value of type float or double without losing precision? I'm thinking of multiplying the integer part with 10^n, where n is the number of digits in the fractional part, and then adding the fractional part to the integer part and subtracting n from the exponent. This effectively turns 4.2e1 into 42e0, for example. Then I could use the pow function to compute 10^exponent and multiply the result with the new integer part. The question is, does this method guarantee maximum precision throughout? Any thoughts on this? A: All of the other answers have missed how hard it is to do this properly. You can do a first cut approach at this which is accurate to a certain extent, but until you take into account IEEE rounding modes (et al), you will never have the right answer. I've written naive implementations before with a rather large amount of error. If you're not scared of math, I highly recommend reading the following article by David Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic. You'll get a better understanding for what is going on under the hood, and why the bits are laid out as such. My best advice is to start with a working atoi implementation, and move out from there. You'll rapidly find you're missing things, but a few looks at strtod's source and you'll be on the right path (which is a long, long path). Eventually you'll praise insert diety here that there are standard libraries. /* use this to start your atof implementation */ /* atoi - christopher.watford@gmail.com */ /* PUBLIC DOMAIN */ long atoi(const char *value) { unsigned long ival = 0, c, n = 1, i = 0, oval; for( ; c = value[i]; ++i) /* chomp leading spaces */ if(!isspace(c)) break; if(c == '-' || c == '+') { /* chomp sign */ n = (c != '-' ? n : -1); i++; } while(c = value[i++]) { /* parse number */ if(!isdigit(c)) return 0; ival = (ival * 10) + (c - '0'); /* mult/accum */ if((n > 0 && ival > LONG_MAX) || (n < 0 && ival > (LONG_MAX + 1UL))) { /* report overflow/underflow */ errno = ERANGE; return (n > 0 ? LONG_MAX : LONG_MIN); } } return (n>0 ? (long)ival : -(long)ival); } A: The "standard" algorithm for converting a decimal number to the best floating-point approximation is William Clinger's How to read floating point numbers accurately, downloadable from here. Note that doing this correctly requires multiple-precision integers, at least a certain percentage of the time, in order to handle corner cases. Algorithms for going the other way, printing the best decimal number from a floating-number, are found in Burger and Dybvig's Printing Floating-Point Numbers Quickly and Accurately, downloadable here. This also requires multiple-precision integer arithmetic See also David M Gay's Correctly Rounded Binary-Decimal and Decimal-Binary Conversions for algorithms going both ways. A: You could ignore the decimal when parsing (except for its location). Say the input was: 156.7834e10... This could easily be parsed into the integer 1567834 followed by e10, which you'd then modify to e6, since the decimal was 4 digits from the end of the "numeral" portion of the float. Precision is an issue. You'll need to check the IEEE spec of the language you're using. If the number of bits in the Mantissa (or Fraction) is larger than the number of bits in your Integer type, then you'll possibly lose precision when someone types in a number such as: 5123.123123e0 - converts to 5123123123 in our method, which does NOT fit in an Integer, but the bits for 5.123123123 may fit in the mantissa of the float spec. Of course, you could use a method that takes each digit in front of the decimal, multiplies the current total (in a float) by 10, then adds the new digit. For digits after the decimal, multiply the digit by a growing power of 10 before adding to the current total. This method seems to beg the question of why you're doing this at all, however, as it requires the use of the floating point primitive without using the readily available parsing libraries. Anyway, good luck! A: Yes, you can decompose the construction into floating point operations as long as these operations are EXACT, and you can afford a single final inexact operation. Unfortunately, floating point operations soon become inexact, when you exceed precision of mantissa, the results are rounded. Once a rounding "error" is introduced, it will be cumulated in further operations... So, generally, NO, you can't use such naive algorithm to convert arbitrary decimals, this may lead to an incorrectly rounded number, off by several ulp of the correct one, like others have already told you. BUT LET'S SEE HOW FAR WE CAN GO: If you carefully reconstruct the float like this: if(biasedExponent >= 0) return integerMantissa * (10^biasedExponent); else return integerMantissa / (10^(-biasedExponent)); there is a risk to exceed precision both when cumulating the integerMantissa if it has many digits, and when raising 10 to the power of biasedExponent... Fortunately, if first two operations are exact, then you can afford a final inexact operation * or /, thanks to IEEE properties, the result will be rounded correctly. Let's apply this to single precision floats which have a precision of 24 bits. 10^8 > 2^24 > 10^7 Noting that multiple of 2 will only increase the exponent and leave the mantissa unchanged, we only have to deal with powers of 5 for exponentiation of 10: 5^11 > 2^24 > 5^10 Though, you can afford 7 digits of precision in the integerMantissa and a biasedExponent between -10 and 10. In double precision, 53 bits, 10^16 > 2^53 > 10^15 5^23 > 2^53 > 5^22 So you can afford 15 decimal digits, and a biased exponent between -22 and 22. It's up to you to see if your numbers will always fall in the correct range... (If you are really tricky, you could arrange to balance mantissa and exponent by inserting/removing trailing zeroes). Otherwise, you'll have to use some extended precision. If your language provides arbitrary precision integers, then it's a bit tricky to get it right, but not that difficult, I did this in Smalltalk and blogged about it at http://smallissimo.blogspot.fr/2011/09/clarifying-and-optimizing.html and http://smallissimo.blogspot.fr/2011/09/reviewing-fraction-asfloat.html Note that these are simple and naive implementations. Fortunately, libc is more optimized. A: I would directly assemble the floating point number using its binary representation. Read in the number one character after another and first find all digits. Do that in integer arithmetic. Also keep track of the decimal point and the exponent. This one will be important later. Now you can assemble your floating point number. The first thing to do is to scan the integer representation of the digits for the first set one-bit (highest to lowest). The bits immediately following the first one-bit are your mantissa. Getting the exponent isn't hard either. You know the first one-bit position, the position of the decimal point and the optional exponent from the scientific notation. Combine them and add the floating point exponent bias (I think it's 127, but check some reference please). This exponent should be somewhere in the range of 0 to 255. If it's larger or smaller you have a positive or negative infinite number (special case). Store the exponent as it into the bits 24 to 30 of your float. The most significant bit is simply the sign. One means negative, zero means positive. It's harder to describe than it really is, try to decompose a floating point number and take a look at the exponent and mantissa and you'll see how easy it really is. Btw - doing the arithmetic in floating point itself is a bad idea because you will always force your mantissa to be truncated to 23 significant bits. You won't get a exact representation that way. A: My first thought is to parse the string into an int64 mantissa and an int decimal exponent using only the first 18 digits of the mantissa. For example, 1.2345e-5 would be parsed into 12345 and -9. Then I would keep multiplying the mantissa by 10 and decrementing the exponent until the mantissa was 18 digits long (>56 bits of precision). Then I would look the decimal exponent up in a table to find a factor and binary exponent that can be used to convert the number from decimal n*10^m to binary p*2^q form. The factor would be another int64 so I'd multiply the mantissa by it such that I obtained the top 64-bits of the resulting 128-bit number. This int64 mantissa can be cast to a float losing only the necessary precision and the 2^q exponent can be applied using multiplication with no loss of precision. I'd expect this to be very accurate and very fast but you may also want to handle the special numbers NaN, -infinity, -0.0 and infinity. I haven't thought about the denormalized numbers or rounding modes. A: For that you have to understand the standard IEEE 754 in order for proper binary representation. After that you can use Float.intBitsToFloat or Double.longBitsToDouble. http://en.wikipedia.org/wiki/IEEE_754 A: If you want the most precise result possible, you should use a higher internal working precision, and then downconvert the result to the desired precision. If you don't mind a few ULPs of error, then you can just repeatedly multiply by 10 as necessary with the desired precision. I would avoid the pow() function, since it will produce inexact results for large exponents. A: It is not possible to convert any arbitrary string representing a number into a double or float without losing precision. There are many fractional numbers that can be represented exactly in decimal (e.g. "0.1") that can only be approximated in a binary float or double. This is similar to how the fraction 1/3 cannot be represented exactly in decimal, you can only write 0.333333... If you don't want to use a library function directly why not look at the source code for those library functions? You mentioned Java; most JDKs ship with source code for the class libraries so you could look up how the java.lang.Double.parseDouble(String) method works. Of course something like BigDecimal is better for controlling precision and rounding modes but you said it needs to be a float or double. A: Using a state machine. It's fairly easy to do, and even works if the data stream is interrupted (you just have to keep the state and the partial result). You can also use a parser generator (if you're doing something more complex). A: I agree with terminus. A state machine is the best way to accomplish this task as there are many stupid ways a parser can be broken. I am working on one now, I think it is complete and it has I think 13 states. The problem is not trivial. I am a hardware engineer interested designing floating point hardware. I am on my second implementation. I found this today http://speleotrove.com/decimal/decarith.pdf which on page 18 gives some interesting test cases. Yes, I have read Clinger's article, but being a simple minded hardware engineer, I can't get my mind around the code presented. The reference to Steele's algorithm as asnwered in Knuth's text was helpful to me. Both input and output are problematic. All of the aforementioned references to various articles are excellent. I have yet to sign up here just yet, but when I do, assuming the login is not taken, it will be broh. (broh-dot). Clyde
{ "language": "en", "url": "https://stackoverflow.com/questions/85223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Which language is useful to create a report for a valid C program Can anyone suggest me a helpful programming language which can be used to create a tool which will analyse the given C program and generate a txt report or html report containing information about the given program (function list, variable list etc). The program I intend to build is similar to doxygen but i want it for my personal use. A: ctags, perhaps? Ctags generates an index (or tag) file of language objects found in source files that allows these items to be quickly and easily located by a text editor or other utility. A tag signifies a language object for which an index entry is available (or, alternatively, the index entry created for that object). A: Both Python and Perl have excellent string processing capabilities. I'd suggest using something like ctags to parse the program, and just create a script to read the ctags file and output in txt/html. The file format used by ctags is well-defined so that other programs can read it. See http://ctags.sourceforge.net for more information on ctags itself and the file it uses. A: You're opening a big can of worms, this isn't an effective use of your time, blah blah blah, etc. Moving on to an answer, if you're talking about anything beyond trivial analysis and you need accuracy, you will need to parse the C source code. You can do that in any language, but you will almost certainly want to generate your parser from a high-level grammar. There are any number of tools for that. A modern and particularly powerful parser generator is ANTLR; there are a number of ANTLR grammars for C, including easier-to-work-with subsets. A: Look into scripting languages. I'd recommend Python or Perl. A: Haskell has a relatively recent language-c project http://www.sivity.net/projects/language.c which allows the analysis of C code. If you are familiar with Haskell, then it might be worth a look. Even if you are not, it might be interesting to have a go. A: If it's a programming language you want then I'd say something which is known for string processing power so that would mean perl. However the task you require can be rather complicated since you need to 'know' the language, so you would require to follow the same steps the compiler does, being lexical and grammatical analyses on the language (think flex, think yacc) in order to truly 'know' what meaning those strings have. Perhaps the best starting point is to take a look at doxygen and try to reuses as much of the work done there as possible A: Lex/yacc are appropriate for building parsers. A: pycparser is a complete parser for ANSI C89/C90 written in pure Python. It's being widely used to analyze C source code for various needs. It comes with some example code, such as listing all the function definitions in files, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/85230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JConsole Config in JBoss' run.bat, add: set JAVA_OPTS=%JAVA_OPTS% -Dcom.sun.management.jmxremote - Dcom.sun.management.jmxremote.port=9987 - Dcom.sun.management.jmxremote.ssl=false - Dcom.sun.management.jmxremote.authenticate=false To start jconsole: JDK/bin>jconsole localhost:9987 A: Yes, that should work. If it doesn't, then use 'ps' (or your platform's equivalent) to check whether those arguments are making it on the JVM's command line. Was that the question?
{ "language": "en", "url": "https://stackoverflow.com/questions/85254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you know when to use design patterns? Anyone can read the GoF book to learn what design patterns are and how to use them, but what is the process for figuring out when a design pattern solves a problem? Does the knowledge of the pattern drive the design, or is there a way to figure out how a pattern can be used to change a design? In other words, are there patterns for Patterns? A: Design Patterns? You're soaking in them! There's nothing special about design patterns, they are merely patterns of design. All development uses design patterns. There are a certain set of design patterns in object oriented programming which are considered generally desirable and have become the canonical Design Patterns. But there are also many undesirable or otherwise indifferent design patterns (such as design anti-patterns) as well as undiscovered and/or undocumented patterns. You can't avoid using patterns when programming. But you can become more aware of the patterns you are using and of when certain patterns are useful and when they are not. Studying the canonical Design Patterns from the GoF book will help, as will learning about code smells and refactoring. There's no one right answer for when a particular design or design pattern should be used, you need to build up experience in using and implementing them in order to know when and where to use which pattern. A: Experience. Learn the patterns and real-world examples of their uses. Every time you have a design decision to make, think if a pattern you know would apply to it. Over time, you get better and you discover new ways to apply the patterns to a wider range of problems. A: Another great book I found was: Refactoring to Patterns By showing when, where and how you can alter existing code to patterns, it gave me a much better understanding of the concepts, and an ability to identify where they can be used. A: How did you learn when to use an if statement? I liken it to that because its a larger construct that you need to know the ins and outs of before you can use it effectively. An if statement solves a class of problems needing branching. A bridge pattern solves a class of problems. I really don't view them any differently. A: Design patterns are supposed to provide a structure in which problems can be solved. When solving a real problem, you have to consider many tiny variations of a solution to that problem to see whether any fits a design pattern. In particular, you will probably need to generalise your problem, or its solution, in order to make a design pattern fit. The answer is, it's an art. Knowing the design patterns is certainly an important step. One way to get used to this sort of thing is to study applications of design patterns, not just the patterns. Seeing many different applications of one pattern can help you over time to get better at mapping a task onto a pattern. A: I would highly recommend reading Head First Design Patterns from O'Reilly. This explains how these patterns can be used in the real world. I'd also add that don't try design too much with patterns in mind. More, look for "code smells" which a pattern might help solve. A: If you know the patterns, then they become tools in your toolbox. When you look at a task, you select from your tools. At that point you should have a pretty good idea which tool is the best fit for a given problem. This is where formulas stop working and you actually do engineering work. A: Rian van der Merwe wrote an excellent article on this for Smashing Magazine in June 2012. Here are some salient bullet points. Design patterns are useful for two reasons: * *Patterns save time because we don’t have to solve a problem that’s already been solved. *Patterns make the Web easier to use because, as adoption increases among designers, users get used to how things work, which in turn reduces their cognitive load when encountering common design elements. van der Merwe recommends that we consider breaking patterns when: * *The new way empirically improves usability, or *The established way becomes outdated. A: The concept of a design pattern has been taken from structural engineering, as with many practices in software engineering. If you consider building a structure, there are decisions that need to be made on how to build that structure to achieve the goals set out. When making those decisions, you will have a set of requirements to work from. It may be something as simple as Bridge must be able to support X tons at one time, or have a particular tensile strength to allow enough movement in wind etc. An architect would use prior knowledge of other builds to make those design choices. He/She would be very unlikely to try to solve the problem from scratch. Software Engineering and Design Patterns are exactly the same. They are simply common solutions to common problems. If you know the design patterns, then when you are working through a design, and particular part of a system requires something that fits a design pattern you have, then use it. Don't try to fit a system round a design pattern, fit design patterns in to your system (where they fit). Just try to think of them as a set of solutions to reduce the amount of design work you need to do, and be cautious of over-engineering your solutions to cram in as many design patterns as you can. This will just serve to make your solution unmaintainable and probably quite buggy. A: I agree that just learning the patterns is not enough. The problem with most books is that they do not provide real-world examples. I've heard that Head First Design Patterns, as some suggested earlier, is a good one. Another thing is that most books are intentionally not language-specific, which may be both a good or a bad thing for you. However important is to understand a pattern in general, it is equally important to know how to implement it well. I've come across a book called C# 3.0 Design Patterns which devotes just about equal ink to both of these unseparable aspects. A: I had this same question when I first encountered design patterns. I appreciated the concepts, but didn't know when or how to apply them. My initial approach was to look for applicability during the design phase. Once you have a block diagram and semi-clear responsibilities for each block, its not too hard to take the responsibilities and cross reference them with a decent reference book. Several good ones have been mentioned here, but the GoF one should be on your list. The next step is to look for improvements in the design based on what you see in the patterns. A: There's a core concept underlying patterns that most people don't grok. Don't think of them as data structures, or algorithms. Instead, think of your code as people sending messages, like passing notes or sending letters, to each other. Each object is a 'person'. The way that you'd organize the 'people' and the patterns they use to send messages to each other are the patterns. A: Turn the question over: the pattern mtch you should be making is "what pattern fits my problem". Consider a really simple pattern, finding an element in an array. in C, it's something like TYPE_t ary[SIZE] = // ... gets initialized somehow size_t ix ; // Your index variable for(ix=0; ix < SIZE; ix++){ if (ary[ix] == item) { return ix ; } } You don't look at the code and think "where can I use that", you look at the problem and say "do I know how to find an element in an array?" With more extensive patterns is really works the same way. You need to have many many copies of a data structure that doesn't change often --- that makes you think "Flyweight." You want something that lives on both sides of a network boundary, you think Proxy. When you study patterns, especially the GoF, ask yourself "what situations call for this pattern? Have I seen this pattern before? What could I have used this for in previous work? Where can I find an example of this in my own life?" A: A design pattern is a generic description on how to solve a common problem. There're 2 things we should pay attention to: First, it is a Generic description; it's not the concrete solution, and it's not a complete recipe either, it's just a description on how the solution would look like in order to approach a common problem. Second, the problem is question is a common problem:, that means this problem has been encountered many times before, and over time people developed a description for how an ideal solution can be applied to this commonly repeated problem. So, if you're encountering a new problem that's not common, try not to use design patterns to solve it, or at least don't make design patterns your tool to just solve any kind of problem you face.
{ "language": "en", "url": "https://stackoverflow.com/questions/85272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "71" }
Q: How do I derive a Voronoi diagram given its point set and its Delaunay triangulation? I'm working on a game where I create a random map of provinces (a la Risk or Diplomacy). To create that map, I'm first generating a series of semi-random points, then figuring the Delaunay triangulations of those points. With that done, I am now looking to create a Voronoi diagram of the points to serve as a starting point for the province borders. My data at this point (no pun intended) consists of the original series of points and a collection of the Delaunay triangles. I've seen a number of ways to do this on the web, but most of them are tied up with how the Delaunay was derived. I'd love to find something that doesn't need to be integrated to the Delaunay, but can work based off the data alone. Failing that, I'm looking for something comprehensible to a relative geometry newbie, as opposed to optimal speed. Thanks! A: If optimal speed is not a consideration, the following psuedo code will generate a Voronoi diagram the hard way: for yloop = 0 to height-1 for xloop = 0 to width-1 // Generate maximal value closest_distance = width * height for point = 0 to number_of_points-1 // calls function to calc distance point_distance = distance(point, xloop, yloop) if point_distance < closest_distance closest_point = point end if next // place result in array of point types points[xloop, yloop] = point next next Assuming you have a 'point' class or structure, if you assign them random colours, then you'll see the familiar voronoi pattern when you display the output. A: After trying to use this thread as a source for answers to my own similar question, I found that Fortune's algorithm — likely because it is the most popular & therefore most documented — was the easiest to understand. The Wikipedia article on Fortune's algorithm keeps fresh links to source code in C, C#, and Javascript. All of them were top-notch and came with beautiful examples. A: The Voronoi diagram is just the dual graph of the Delaunay triangulation. * *So, the edges of the Voronoi diagram are along the perpendicular bisectors of the edges of the Delaunay triangulation, so compute those lines. *Then, compute the vertices of the Voronoi diagram by finding the intersections of adjacent edges. *Finally, the edges are then the subsets of the lines you computed which lie between the corresponding vertices. Note that the exact code depends on the internal representation you're using for the two diagrams. A: Each of your Delaunay triangles contains a single point of the Voronoi diagram. You can compute this point by finding the intersection of the three perpendicular bisectors for each triangle. Your Voronoi diagram will connect this set of points, each with it's nearest three neighbors. (each neighbor shares a side of the Delaunay triangle) How do you plan on approaching the edge cases?
{ "language": "en", "url": "https://stackoverflow.com/questions/85275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How do I enable more than 8-bit colors in Terminal.app? In the Vim and Emacs terminal apps, the color schemes look horrid. How do I enable the colors to be as vibrant as the GUI version (or more than 8 colors for that matter)? Should I just give up, and move over to their respective GUI applications? And if so, which? A: You can't have more colors in the terminal, because there are only ANSI codes for 8 colors (16 if you count bold/light). If you want to customize the colors, you can use the TerminalColours plugin from http://ciaranwal.sh/2007/11/01/customising-colours-in-leopard-terminal Personally, I prefer to use the so-called Carbon Emacs on my Mac. There are several builds available; Google is your friend. I get mine from http://www.porkrind.org/emacs/ A: You are possibly being inhibited by the fact you are running in a VT100/WhateverItsCalled compatible terminal and it just doesn't have more than about 16 foreground and 16 background colours. If it did, the lovely library "CaCa" ( ColourAsciiColourArt ) would be much more pleasing to watch than it is. If you want more colours, you simply have to use more modern technology, and this generally means using X ( unless your loving pain and want to use directfb/framebuffer/svgalib ). For vim, there is GVim ( GTK+Vim ). Emacs GUI version however displeases me much, but I'm not an emacs user. A: Aquamacs and MacVim A: Sounds like you want MacVim
{ "language": "en", "url": "https://stackoverflow.com/questions/85277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the value of an anonymous unattached block in C#? In C# you can make a block inside of a method that is not attached to any other statement. public void TestMethod() { { string x = "test"; string y = x; { int z = 42; int zz = z; } } } This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block. Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings. A: An example would be if you wanted to reuse a variable name, normally you can't reuse variable names This is not valid int a = 10; Console.WriteLine(a); int a = 20; Console.WriteLine(a); but this is: { int a = 10; Console.WriteLine(a); } { int a = 20; Console.WriteLine(a); } The only thing I can think of right now, is for example if you were processing some large object, and you extracted some information out of it, and after that you were going to perform a bunch of operations, you could put the large object processing in a block, so that it goes out of scope, then continue with the other operations { //Process a large object and extract some data } //large object is out of scope here and will be garbage collected, //you can now perform other operations with the extracted data that can take a long time, //without holding the large object in memory //do processing with extracted data A: It's a by-product of a the parser rule that statement is either a simple statement or a block. i.e. a block can be used wherever a single statement can. e.g. if (someCondition) SimpleStatement(); if (SomeCondition) { BlockOfStatements(); } Others have pointed out that variable declarations are in scope until the end of the containing block. It's good for temporary vars to have a short scope, but I've never had to use a block on it's own to limit the scope of a variable. Sometimes you use a block underneath a "using" statement for that. So generally it's not valuable. A: Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects. Ray Hayes points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit. A: As far as I can see, it'd only be useful from an organizational standpoint. I can't really conceive of any logical value in doing that. Perhaps someone will have a proper example. A: This allows you to create a scope block anywhere. It's not that useful on it's own, but can make logic simpler: switch( value ) { case const1: int i = GetValueSomeHow(); //do something return i.ToString(); case const2: int i = GetADifferentValue(); //this will throw an exception - i is already declared ... In C# we can use a scope block so that items declared under each case are only in scope in that case: switch( value ) { case const1: { int i = GetValueSomeHow(); //do something return i.ToString(); } case const2: { int i = GetADifferentValue(); //no exception now return SomeFunctionOfInt( i ); } ... This can also work for gotos and labels, not that you often use them in C#. A: The one practical reason for it to exist is if you want to restrict the scope of some variable when there is no compelling need to introduce any other reason for the block. In actual practice, this is virtually never useful. Personally, my guess is that from a language/compiler point of view it's easier to say that you can put a block anywhere a statement is expected, and they simply didn't go out of their way to prevent you from using it without an if/for/method declaration/ etc. Consider the beginning this recent blog post from Eric Lippert. An if statement isn't followed by either a single statement or a number of statements enclosed on curly braces, it's simply followed by a single statement. Anytime you enclose 0 to N statements in curly braces you make that section of code equivalent (from the point of view of the language parser) one statement. This same practice applies to all looping structures as well, although as the main point of the blog post explains, it doesn't apply to try/catch/finally blocks. When addressing blocks from that point of view the question then becomes, "Is there a compelling reason to prevent blocks from being used anywhere a single statement could be used?" and the answer is, "No". A: One reason for doing this is that the variables 'z' and 'zz' would not be available to code below the end of that inner block. When you do this in Java, the JVM pushes a stack frame for the inner code, and those values can live on the stack. When the code exits the block, the stack frame is popped and those values go away. Depending on the types involved, this can save you from having to use heap and/or garbage collection. A: In C# -- like c/c++/java -- braces denote a scope. This dictates the lifetime of a variable. As the closing brace is reached, the variable becomes immediately available for a garbage collection. In c++, it would cause a class's destructor to be called if the var represented an instance. As for usage, the only possible use is to free up a large object but tbh, setting it to null would have the same effect. I suspect the former usage is probably just to keep c++ programmers moving to managed code somewhat in familiar and comfortable territory. If really want to call a "destructor" in c#, you typically implement the IDisposable interface and use the "using (var) {...}" pattern. Oisin A: Even if it was actually useful for any reason (e.g. variable scope control), I would discourage you from such construct from the standpoint of good old code readibility. A: There is no value to this other than semantic and for scope and garbage collection, none of which is significant in this limited example. If you think it makes the code clearer, for yourself and/or others, then you certainly could use it. However, the more accepted convention for semantic clarification in code generally would use line breaks only with option in-line comments: public void TestMethod() { //do something with some strings string x = "test"; string y = x; //do something else with some ints int z = 42; int zz = z; }
{ "language": "en", "url": "https://stackoverflow.com/questions/85282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to avoid garbage collection in real time .NET application? I'm writting a financial C# application which receive messages from the network, translate them into different object according to the message type and finaly apply the application business logic on them. The point is that after the business logic is applied, I'm very sure I will never need this instance again. Rather than to wait for the garbage collector to free them, I'd like to explicitly "delete" them. Is there a better way to do so in C#, should I use a pool of object to reuse always the same set of instance or is there a better strategy. The goal being to avoid the garbage collection to use any CPU during a time critical process. A: Attempting to second-guess the garbage collector is generally a very bad idea. On Windows, the garbage collector is a generational one and can be relied upon to be pretty efficient. There are some noted exceptions to this general rule - the most common being the occurrence of a one-time event that you know for a fact will have caused a lot of old objects to die - once objects are promoted to Gen2 (the longest lived) they tend to hang around. In the case you mention, you sound as though you are generating a number of short-lived objects - these will result in Gen0 collections. These happen relatively often anyway, and are the most efficient. You could avoid them by having a reusable pool of objects, if you prefer, but it is best to ascertain for certain if GC is a performance problem before taking such action - the CLR profiler is the tool for doing this. It should be noted that the garbage collector is different on different .NET frameworks - on the compact framework (which runs on the Xbox 360 and on mobile platforms) it is a non-generational GC and as such you must be much more careful about what garbage your program generates. A: Forcing a GC.Collect() is generally a bad idea, leave the GC to do what it does best. It sounds like the best solution would be to use a pool of objects that you can grow if necessary - I've used this pattern successfully. This way you avoid not only the garbage collection but the regular allocation cost as well. Finally, are you sure that the GC is causing you a problem? You should probably measure and prove this before implementing any perf-saving solutions - you may be causing yourself unnecessary work! A: "The goal being to avoid the garbage collection to use any CPU during a time critical process" Q: If by time critical, you mean you're listening to some esoteric piece of hardware, and you can't afford to miss the interrupt? A: If so then C# isn't the language to use, you want Assembler, C or C++ for that. Q: If by time Critical, you mean while there are lots of messages in the pipe, and you don't want to let the Garbage collector slow things down? A: If so you are worrying needlessly. By the sounds of things your objects are very short lived, this means the garbage collector will recycle them very efficiently, without any apparent lag in performance. However, the only way to know for sure is test it, set it up to run overnight processing a constant stream of test messages, I'll be stunned if you your performance stats can spot when the GC kicks in (and even if you can spot it, I'll be even more surprised if it actually matters). A: Get a good understanding and feel on how the Garbage Collector behaves, and you will understand why what you are thinking of here is not recommended. unless you really like the CLR to spend time rearranging objects in memory alot. * *http://msdn.microsoft.com/en-us/magazine/bb985010.aspx *http://msdn.microsoft.com/en-us/magazine/bb985011.aspx A: How intensive is the app? I wrote an app that captures 3 sound cards (Managed DirectX, 44.1KHz, Stereo, 16-bit), in 8KB blocks, and sends 2 of the 3 streams to another computer via TCP/IP. The UI renders an audio level meter and (smooth) scrolling title/artist for each of the 3 channels. This runs on PCs with XP, 1.8GHz, 512MB, etc. The App uses about 5% of the CPU. I stayed clear of manually calling GC methods. But I did have to tune a few things that were wasteful. I used RedGate's Ant profiler to hone in on the wasteful portions. An awesome tool! I wanted to use a pool of pre-allocated byte arrays, but the managed DX Assembly allocates byte buffers internally, then returns that to the App. It turned out that I didn't have to. A: Don't delete them right away. Calling the garbage collector for each object is a bad idea. Normally you really don't want to mess with the garbage collector at all, and even time critical processes are just race conditions waiting to happen if they're that sensitive. But if you know you'll have busy vs light load periods for your app, you might try a more general GC.Collect() when you reach a light period to encourage cleanup before the next busy period. A: If it is absolutely time critical then you should use a deterministic platform like C/C++. Even calling GC.Collect() will generate CPU cycles. Your question starts off with the suggestion that you want to save memory but getting rid of objects. This is a space critical optimization. You need to decide what you really want because the GC is better at optimizing this situation than a human. A: From the sound of it, it seems like you're talking about deterministic finalization (destructors in C++), which doesn't exist in C#. The closest thing that you will find in C# is the Disposable pattern. Basically you implement the IDisposable interface. The basic pattern is this: public class MyClass: IDisposable { private bool _disposed; public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } protected virtual void Dispose( bool disposing ) { if( _disposed ) return; if( disposing ) { // Dispose managed resources here } _disposed = true; } } A: Look here: http://msdn.microsoft.com/en-us/library/bb384202.aspx You can tell the garbage collector that you're doing something critical at the moment, and it will try to be nice to you. A: You hit in yourself -- use a pool of objects and reuse those objects. The semantics of the calls to those object would need to be hidden behind a factory facade. You'll need to grow the pool in some pre-defined way. Perhaps double the size everytime it hits the limit -- a high water algorithm, or a fixed percentage. I'd really strongly advise you not to call GC.Collect(). When the load on your pool gets low enough you could shrink the pool and that will eventually trigger a garbage collection -- let the CLR worry about it. A: You could have a limited amount of instances of each type in a pool, and reuse the already done with instances. The size of the pool would depend on the amount of messages you'll be processing. A: Instead of creating a new instance of an object every time you get a message, why don't you reuse objects that have already been used? This way you won't be fighting against the garbage collector and your heap memory won't be getting fragmented.** For each message type, you can create a pool to hold the instances that are not in use. Whenever you receive a network message, you look at the message type, pull a waiting instance out of the appropriate pool and apply your business logic. After that, you put that instance of the message object back into it's pool. You will most likely want to "lazy load" your pool with instances so your code scales easily. Therefore, your pool class will need to detect when a null instance has been pulled and fill it up before handing it out. Then when the calling code puts it back in the pool it's a real instance. ** "Object pooling is a pattern to use that allows objects to be reused rather than allocated and deallocated, which helps to prevent heap fragmentation as well as costly GC compactions." http://geekswithblogs.net/robp/archive/2008/08/07/speedy-c-part-2-optimizing-memory-allocations---pooling-and.aspx A: In theory the GC shouldn't run if your CPU is under heavy load or unless it really needs to. But if you have to, you may want to just keep all of your objects in memory, perhaps a singleton instance, and never clean them up unless you're ready. That's probably the only way to guarantee when the GC runs.
{ "language": "en", "url": "https://stackoverflow.com/questions/85283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Handling and storing elapsed time I'm having problems deciding on what is the best way is to handle and store time measurements. I have an app that has a textbox that allows the users to input time in either hh:mm:ss or mm:ss format. So I was planning on parsing this string, tokenizing it on the colons and creating TimeSpan (or using TimeSpan.Parse() and just adding a "00:" to the mm:ss case) for my business logic. Ok? How do I store this as in a database though? What would the field type be? DateTime seems wrong. I don't want a time of 00:54:12 to be stored as 1901-01-01 00:54:12 that seems a bit poor? A: TimeSpan has an Int64 Ticks property that you can store instead, and a constructor that takes a Ticks value. A: I think the simplest is to just convert user input into a integer number of seconds. So 54:12 == 3252 seconds, so store the 3252 in your database or wherever. Then when you need to display it to the user, you can convert it back again. A: For periods less than a day, just use seconds as other have said. For longer periods, it depends on your db engine. If SQL Server, prior to version 2008 you want a datetime. It's okay- you can just ignore the default 1/1/1900 date they'll all have. If you are fortunate enough to have sql server 2008, then there are separate Date and Time datatypes you can use. The advantage with using a real datetime/time type is the use of the DateDiff function for comparing durations. A: Most databases have some sort of time interval type. The answer depends on which database you're talking about. For Oracle, it's just a floating point NUMBER that represents the number of days (including fractional days). You can add/subtract that to/from any DATE type and you get the right answer. A: As an integer count of seconds (or Milliseconds as appropriate) A: Are you collecting both the start time and stop time? If so, you could use the "timestamp" data type, if your DBMS supports that. If not, just as a date/time type. Now, you've said you don't want the date part to be stored - but consider the case where the time period spans midnight - you start at 23:55:01 and end at 00:05:14, for example - unless you also have the date in there. There are standard build in functions to return the elapsed time (in seconds) between two date-time values. A: Go with integers for seconds or minutes. Seconds is probably better. you'll never kick yourself for choosing something with too much precision. Also, for your UI, consider using multiple text inputs you don't have to worry about the user actually typing in the ":" properly. It's also much easier to add other constraints such as the minute and second values conting containing 0-59. A: and int type should do it, storing it as seconds and parsing it back and forth http://msdn.microsoft.com/en-us/library/ms187745.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/85307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Customizing Search Results Display in Sharepoint Services 3.0 Wiki I'm looking at using a Windows SharePoint Services 3.0 wiki as a metadata repository. We basically want a community-driven dictionary and for various reasons we're using Sharepoint instead of say MediaWiki. What can I do to customize or completely replace searchresults.aspx? Features I'd add if I knew how: * *Automatically load the #1 hit if it is a 100% match to the search term *Show the first few lines of each result as a preview so users don't have to click through to bad results *Add a "Page doesn't exist, click here to create it" link in cases where there's not a 100% match I've got Sharepoint Designer installed and it looks like I'll be able to use it to upload any custom .aspx files I create but I don't see that it will give me access to searchresults.aspx. Note: Since I plan to access this search tool from an external site via URL parameters it should be fine to leave the existing searchresults.aspx unchanged and just load this solution as a complementary search option. A: Yes, everything is possible but you will need to customize it a little bit. I would recommend you to build a custom web part to display your results. Here is a nice article to start with: http://msdn.microsoft.com/en-us/library/ms584220.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/85336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best general SVN Ignore Pattern? What is the best (or as good as possible) general SVN ignore pattern to use? There are a number of different IDE, editor, compiler, plug-in, platform, etc. specific files and some file types that "overlap" (i.e. desirable for some types projects and not for others). There are however, a large number of file types that you just never want included in source control automatically regardless the specifics of your development environment. The answer to this question would serve as a good starting point for any project - only requiring them to add the few environment specific items they need. It could be adapted for other Version Control Systems (VCS) as well. A: Used for my Visual Studio projects */bin */obj *.user *.suo You can expand more file types from there. A: Based on Burly's ignore pattern, I have added ReSharper to the ignore list Formatted for copy and paste: *.o *.lo .la ## .*.rej .rej .~ ~ .# .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk .msi .res *.pch *.suo *.exp ~. cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user _ReSharper.* *.resharper.user Formatted for readability: *.o *.lo .la ## .*.rej .rej .~ ~ .# .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk .msi .res *.pch *.suo *.exp ~. cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user _ReSharper.* *.resharper.user A: My ignore pattern for Visual Studio: */bin */obj */Release */Debug *.suo *.err *.log *.obj *.bin *.dll *.exe *.LOG *.user *.pdb [tT]emp [tT]empPE Ankh.Load thumbs.db *.resharper *.vspscc *.vsssccc *.scc */_ReSharper* */_ReSharper.* bin obj *.resharperoptions *.db *.bak *_ReSharper* *.snk logs output TestResults *.crunchsolution.* *.crunchproject.* Formatted for readability */bin */obj */Release */Debug *.suo *.err *.log *.obj *.bin *.dll *.exe *.LOG *.user *.pdb [tT]emp [tT]empPE Ankh.Load thumbs.db *.resharper *.vspscc *.vsssccc *.scc */_ReSharper* */_ReSharper.* bin obj *.resharperoptions *.db *.bak *_ReSharper* *.snk logs output TestResults *.crunchsolution.* *.crunchproject.* A: Visual Studio (VC++) users definitely need to exclude the .ncb files A: I'll add my own two cents to this question: I use the following SVN ignore pattern with TortoiseSVN and Subversion CLI for native C++, C#/VB.NET, and PERL projects on both Windows and Linux platforms. It works well for me! Formatted for copy and paste: *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk *.msi* .res *.pch *.suo *.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user *.generated.cs Formatted for readability: *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk *.msi* .res *.pch *.suo *.exp *.*~ *.~* ~*.* cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user *.generated.cs A: Every time I come across a file I generally do not want in the repository, I update the pattern. I believe there is no "best" pattern - it always depends on the language and environment you develop in. Moreover, you're not very likely to think of all the possible "ignorable" filetypes - you'll always encounter a filetype you simply forgot to include. Thats why updating the pattern as you go works the best. A: Windows users might want to throw in desktop.ini and thumbs.db. A: Mac users probably want to throw in .DS_Store. In addition, if there are dev's using Emacs or Vim, you probably want to add ~~ and ##. A: For Eclipse, I use: bin .* .* gets all the project configuration. You almost never want to check in a 'hidden' directory or file, but if it comes up, you can still svn add it. A: Since you may be using third party libs and dll's as part of the project(s) then I don't see the wisdom in blocking *.lib and *.dll from the repository. These are the things that are meant to be stored in the repository. A: Visual Studio 2010 users should add ipch (a folder which contains C++ precompiled headers) and *.sdf (huge files used by intellisense for any kind of project). A: The pattern depends on which operating system you're using. On Linux, you'll want to block **.o*, **.so*, **.a*, and **.la* to begin with. You may also want to block **~* (backup file from editing) and #*# (emacs backup from a crash). On Windows, you'll want **.obj*, **.lib*, and **.dll* at the very least. Any other files you need to block depend on your IDE, editor, and compiler. A: Gotta add Resharper to the mix if you use one. another one to look out for is Ankh*.* A: Don't forget NCrunch temporary files: *.crunchsolution.* *.crunchproject.* A: And core dumps (cygwin, linux) *.stackdump core.* A: gitignore.io provides configurable patterns for git. They provide a readable list, which you need to reformat for SVN. For instance, requesting MicrosoftOffice and Windows returns # Created by https://www.gitignore.io/api/microsoftoffice,windows ### MicrosoftOffice ### *.tmp # Word temporary ~$*.doc* # Excel temporary ~$*.xls* # Excel Backup File *.xlk # PowerPoint temporary ~$*.ppt* # Visio autosave temporary files *.~vsdx ### Windows ### # Windows image file caches Thumbs.db ehthumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msm *.msp # Windows shortcuts *.lnk A: gitignore.io provides configurable patterns for git. They provide a readable list, which you need to reformat for SVN. For instance, requesting MicrosoftOffice and Windows returns # Created by https://www.gitignore.io/api/microsoftoffice,windows ### MicrosoftOffice ### *.tmp # Word temporary ~$*.doc* # Excel temporary ~$*.xls* # Excel Backup File *.xlk # PowerPoint temporary ~$*.ppt* # Visio autosave temporary files *.~vsdx ### Windows ### # Windows image file caches Thumbs.db ehthumbs.db # Folder config file Desktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msm *.msp # Windows shortcuts *.lnk It seems that it can be directly used as svn:global-ignore
{ "language": "en", "url": "https://stackoverflow.com/questions/85353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "179" }
Q: Most common cause of "java.lang.NullPointerException" when dealing with XMLs? My strongest lead is that the code who deals with the incoming XMLs is actually receiving an invalid/incomplete file hence failing the DOM parsing. Any suggestions? A: Incomplete file is definitely the place to start looking. I'd print out the file right before the point you parse it to see what's getting sent to the parser. If it's incomplete it will be obvious. If it's invalid, you'll have a little searching to do. A: My first guess would be that the DOM-using code is treating elements that are marked as optional in the DTD as compulsory. Edited to add: What I mean is that unless you validate against a DTD, you cannot expect something like the following (example using dom4j) to return anything but null. doc.selectSingleNode("//some/element/in/a/structure"); The same is of course true if you're stringing element navigation calls together, or generally don't check return values before using them. A: You should have a stack trace pointing to where you NPE is thrown. That should narrow down the number of variables that can be null. Rather than getting the debugger or printf out, I suggest adding appropriate checks and throwing an exception where as soon as the error can be detected. It's a good habit to get into to avoid mysterious problems later. A: Ideally you should be running your java application inside a debugger, thus when an uncaught exception is thrown you can examine the callstack, variables, etc and see exactly what line caused the crash, and perhaps which data is null that got used. If you can't use a debugger for whatever reason, then compile your application with debugging support, and add an exception handler for this particular error, and print out the stack trace. Again, this will show exactly what line in what file caused the crash.
{ "language": "en", "url": "https://stackoverflow.com/questions/85370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Floor a date in SQL server In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year? Let's say that I have a date of 2008-09-17 12:56:53.430, then the output of flooring should be: * *Year: 2008-01-01 00:00:00.000 *Month: 2008-09-01 00:00:00.000 *Day: 2008-09-17 00:00:00.000 *Hour: 2008-09-17 12:00:00.000 *Minute: 2008-09-17 12:56:00.000 *Second: 2008-09-17 12:56:53.000 A: I've used @Portman's answer many times over the years as a reference when flooring dates and have moved its working into a function which you may find useful. I make no claims to its performance and merely provide it as a tool for the user. I ask that, if you do decide to upvote this answer, please also upvote @Portman's answer, as my code is a derivative of his. IF OBJECT_ID('fn_FloorDate') IS NOT NULL DROP FUNCTION fn_FloorDate SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[fn_FloorDate] ( @Date DATETIME = NULL, @DatePart VARCHAR(6) = 'day' ) RETURNS DATETIME AS BEGIN IF (@Date IS NULL) SET @Date = GETDATE(); RETURN CASE WHEN LOWER(@DatePart) = 'year' THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0) WHEN LOWER(@DatePart) = 'month' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0) WHEN LOWER(@DatePart) = 'day' THEN DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0) WHEN LOWER(@DatePart) = 'hour' THEN DATEADD(HOUR, DATEDIFF(HOUR, 0, @Date), 0) WHEN LOWER(@DatePart) = 'minute' THEN DATEADD(MINUTE, DATEDIFF(MINUTE, 0, @Date), 0) WHEN LOWER(@DatePart) = 'second' THEN DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', @Date), '2000-01-01') ELSE DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0) END; END Usage: DECLARE @date DATETIME; SET @date = '2008-09-17 12:56:53.430'; SELECT @date AS [Now],--2008-09-17 12:56:53.430 dbo.fn_FloorDate(@date, 'year') AS [Year],--2008-01-01 00:00:00.000 dbo.fn_FloorDate(default, default) AS [NoParams],--2013-11-05 00:00:00.000 dbo.fn_FloorDate(@date, default) AS [ShouldBeDay],--2008-09-17 00:00:00.000 dbo.fn_FloorDate(@date, 'month') AS [Month],--2008-09-01 00:00:00.000 dbo.fn_FloorDate(@date, 'day') AS [Day],--2008-09-17 00:00:00.000 dbo.fn_FloorDate(@date, 'hour') AS [Hour],--2008-09-17 12:00:00.000 dbo.fn_FloorDate(@date, 'minute') AS [Minute],--2008-09-17 12:56:00.000 dbo.fn_FloorDate(@date, 'second') AS [Second];--2008-09-17 12:56:53.000 A: In SQL Server here's a little trick to do that: SELECT CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME) You cast the DateTime into a float, which represents the Date as the integer portion and the Time as the fraction of a day that's passed. Chop off that decimal portion, then cast that back to a DateTime, and you've got midnight at the beginning of that day. This is probably more efficient than all the DATEADD and DATEDIFF stuff. It's certainly way easier to type. A: The CONVERT() function can do this as well, depending on what style you use. A: Expanding upon the Convert/Cast solution, in Microsoft SQL Server 2008 you can do the following: cast(cast(getdate() as date) as datetime) Just replace getdate() with any column which is a datetime. There are no strings involved in this conversion. This is ok for ad-hoc queries or updates, but for key joins or heavily used processing it may be better to handle the conversion within the processing or redefine the tables to have appropriate keys and data. In 2005, you can use the messier floor: cast(floor(cast(getdate() as float)) as datetime) I don't think that uses string conversion either, but I can't speak to comparing actual efficiency versus armchair estimates. A: The key is to use DATEADD and DATEDIFF along with the appropriate SQL timespan enumeration. declare @datetime datetime; set @datetime = getdate(); select @datetime; select dateadd(year,datediff(year,0,@datetime),0); select dateadd(month,datediff(month,0,@datetime),0); select dateadd(day,datediff(day,0,@datetime),0); select dateadd(hour,datediff(hour,0,@datetime),0); select dateadd(minute,datediff(minute,0,@datetime),0); select dateadd(second,datediff(second,'2000-01-01',@datetime),'2000-01-01'); select dateadd(week,datediff(week,0,@datetime),-1); --Beginning of week is Sunday select dateadd(week,datediff(week,0,@datetime),0); --Beginning of week is Monday Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor. A: Too bad it's not Oracle, or else you could use trunc() or to_char(). But I had similar issues with SQL Server and used the CONVERT() and DateDiff() methods, as referenced here A: There are several ways to skin this cat =) select convert(datetime,convert(varchar,CURRENT_TIMESTAMP,101)) A: Since PostgreSQL is also a "SQL Server", I'll mention date_trunc() Which does exactly what you're asking gracefully. For example: select date_trunc('hour',current_timestamp); date_trunc ------------------------ 2009-02-18 07:00:00-08 (1 row) A: DateAdd along with DateDiff can help to do many different tasks. For example, you can find last day of any month as well can find last day of previous or next month. ----Last Day of Previous Month SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) LastDay_PreviousMonth ----Last Day of Current Month SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) LastDay_CurrentMonth ----Last Day of Next Month SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)) LastDay_NextMonth Source
{ "language": "en", "url": "https://stackoverflow.com/questions/85373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: World's First Computer Programming _Language_? OK -- a bit of an undefined question (is the pattern of plugs in an Eniac plugboard a language ??) but contenders include: * *Konrad Zuse's PlanKalkül (1940s) - never implemented (generally accepted as the first). *Whatever Ada Lovelace (1840s) programmed in (not Ada) -- if she is the first programmer, as everyone says, she must have used the first programming language, no? Again probably never implemented - but did Babbage have anything that could be called a language? *Turing's description of his Turing machine (1936 paper). In the paper he actually writes programs and simulates their execution mathematically - that makes it as good as (and earlier than) PlanKalkül in my book. *Autocode for the Machester Mark 1 computer (1952) -- compiled, high level, beats Fortan to the punch (?). Mr Turing again (!). *Fortran (Early 1950's) - beats out Lisp by a couple of years and undoubtedly passes the sniff test. But was it earlier than Mark 1 autocode ?? A: Since Ada Lovelace is widely regarded as the first programmer, I'd investigate what she called the set of symbols she was using. Update: You can read the notation that Lovelace used in her Notes on Sketch of The Analytical Engine Invented by Charles Babbage By L. F. MENABREA. Lovelace was the translator, but her notes describing the programming of the Analytical Engine ended up being about four times longer than the original publication. A: I think we need to agree on a definition of "programming language" to answer this question in any useful way. Is directly manipulating machine code a programming language? A: Konrad Zuse's PlanKalkül (1940s) - never implemented There was actually an implementation of the language published by Rojas et al. somewhere around the year 2000. A: DNA -- or does it have to involve silicon computers? ;-) Well, if you go down that road then the correct answer has to be RNA which existed before DNA. But then, do we have a Blind Programmer? ;-) A: In the beginning there was Ada Lovelace , Then Bill said 'Let there be C#' And there was light !! A: The PBS series Connections made the argument that the holes punched in tiles to control the patterns created on looms (circa 1700s??) were the first programming "language". These were followed by player piano scrolls: Codes, on paper, which are read by, and control the operation of a machine. That's a programming language, isn't it? A: DNA -- or does it have to involve silicon computers? ;-) A: Assuming a definition of "programming language" as "a textual notation used to describe/control the intended behavior of a digital computer", I think there's only one possible answer: raw (numerical) machine code. Many of the other answers (e.g. recipes for cooking) are clever, but aren't about programming per se, but about description/control in a different context or more general sense. A: I would say that the first programming language actually used was the machine language of the first stored program computer, which I believe was Baby: http://www.computer50.org/ A: The language the analytical engine would have used was its own machine code, entered via punch cards indicating the operation to be performed and the columns (effectively registers) to perform it to. See these notes for some details. A: Programming, at least in the declarative sense, comes down to combinations of sequence, alternation, and repetition. One might consider recipe authors as programmers, and therefore very early ones. Think about a recipe: it contains sequence (slice this, then chop that, then heat so and so...), alternation (if you want it moist then bake for 40 minutes, else if you want it "cakey" bake for 55 minutes), and repetition (while not stiff kneed the dough, repeat stirring until the batter is smooth). Recipes go back thousands of years.
{ "language": "en", "url": "https://stackoverflow.com/questions/85374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SharePoint - How do insert new items using the list web service? I have a list with 2 text fields, and a choice field. How do I use the Lists.asmx web service to insert a new item? I can make a web reference to the lists.asmx service, so you can assume that this is known. I would like a complete example including code and the XML for the CAML query. Ideally the sample would use C#. A: Using the Lists web service to insert item into a SharePoint list can indeed be tricky. Since this method is of the form: XML in, XML out, it can be hard to get the parameters right. First you should take a look at the list definition. It can be retrieved with the method GetList(), as shown below: XmlNode listXml = sharePointLists.GetList(listName); File.WriteAllText("listdefinition.xml", listXml.OuterXml); Important here are the names of the fields and their data types. Field names will never be the same as the ones you see in the SharePoint GUI. A good example is the Title field which is used for the first field of the list. Now that you know that, you can create the query to go to SharePoint. An example: <Batch OnError="Continue"> <Method ID="1" Cmd="New"> <Field Name="Title">Abcdef</Field> <Field Name="Project_x0020_code">999050</Field> <Field Name="Status">Open</Field> </Method> </Batch> The Batch element is the root element of the XML. Inside you can put different Methods. These should get a unique ID (which is used to report errors back to you) and a command, which can for instance be "New" or "Update". Inside the Method, you put Field elements that specify the value for each field. For instance, the Title field gets the value "Abcdef". Be careful to use the exact name as it is returned by GetList(). To execute the query on SharePoint, use the UpdateListItems() method: XmlNode result = sharePointLists.UpdateListItems(listDefinition.Name, updates); The return value is an XML fragment containing the status of each update. For instance: <Results xmlns="http://schemas.microsoft.com/sharepoint/soap/"> <Result ID="1,New"> <ErrorCode>0x00000000</ErrorCode> <z:row ows_ContentTypeId="0x010036F3F587127F1A44B8BA3FEFED4733C6" ows_Title="Abcdef" ows_Project_x0020_code="999050" ows_Status="Open" ows_LinkTitleNoMenu="Abcdef" ows_LinkTitle="Abcdef" ows_ID="1005" ... xmlns:z="#RowsetSchema" /> </Result> </Results> You can parse this and look at the ErrorCode to see which methods failed. In practice I have created a wrapper class that takes care of all the dirty details for me. Unfortunately this is owned by my employer so I cannot share it with you. This wrapper class is part of an internal utility that is used to retrieve information from our project database and post it to SharePoint. Since it was developed during company time, I'm not allowed to post it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/85392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to change default delete date in lotus notes for emails? I am using Lotus Notes as my email client, and how to change the defailt email delete date to something new so my older emails don't get deleted after pre-defined date? A: go to TOOLS -> Change Delete Date , you can put any number of days to change the default delete date of selected email. A: Lotus Notes email does not automatically delete email - There is no "default delete date". It does have a setting to automatically delete email from your Trash folder after a specified amount of hours (but mail only gets put in the Trash if you delete it). You can find this setting by clicking More >> Preferences... "Delete documents in my Trash folder after __ hours"
{ "language": "en", "url": "https://stackoverflow.com/questions/85403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating a PDF document based on a Microsoft Word Template I need to take a Word document that is a template of sorts...collect user input to populate specific fields in that template..then generate a PDF file that includes the completed template as well as a few other document types. Does anyone have a good suggestion on a component to achieve this? Preferably one that does not require Microsoft Office to be installed on the web server. A: Try Aspose Words for .net. From their website: "Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word." Utilizing Aspose Words with Aspose PDF permits you to output to PDF. One thing you do NOT want to do is install MS Word on your production server. Loading those objects is SLOW and EATS memory. You won't be able to use the CutePDF Writer unless you also install MS Word on the server. Yeck. A: Is there a reason to use Word? If you start with a PDF with Form fields, you can either allow the user to fill out the fields, or do it programatically with iTextSharp's PDF stamper. If you need to use MSOffice 2000/2003 components programmatically, you can try Office Web Components. They do need to be installed on the server, but can be used by .NET and Com apps to interact with office file types. More info here...http://en.wikipedia.org/wiki/Office_Web_Components If you dig about on an office CD you should find the OWC installer for your version. I haven't worked with 2007, but I assume there is something similar available. iTextSharp and OWC are no-cost, check the licensing for more details. A: Hmmm...You might be able to employ CutePDF printer in a creative way to solve this problem. Essentially, it takes anything that can be fed through a standard print driver and makes a PDF out of it. It's free. A: Try using The Apache POI API to populate the fields. It can get into Word documents and access their elements. As for the Word -> PDF step, I'd also recommend evaluating the Aspose solution. It may even be able to perform both steps. Its not free, however. A: My first thought for a "doc template" + merge to pdf solution would be to start with open office formats. - the odt file (open document template) is xml-based - so you could even use perl, to do the merge, then call writer's doc 2 pdf (I have no idea if they have an API, but one could find out in less than a day - even if one had to examine the source.) and converting your "word" dot to a writer odt file is just a "file save as" operation in OoWriter. A: If you use Aspose.Words, then your input document/template can be in one of the several supported formats including DOC, DOCX. Then you can insert data into the document in a number of ways. You can use bookmarks in a document and just set their text. Or better yet use the reporting engine we provide. It allows to use standard MS Word MERGEFIELD fields plus adds capabilities for repeating regions and even nested. E.g. you can design an invoice (with parent/child data) template in MS Word and then populate from a .NET DataSet in one line of code. Also, you only need Aspose.Words to produce PDF (a year ago you needed both Aspose.Words and Aspose.Pdf). You can also easily save the exactly the same looking document to DOC, DOC, DOCX and a few other formats. I'm on the Aspose.Words dev team. A: Have a look at the Muhimbi PDF Converter Web Services. It runs on Windows as a service, but can be accessed from any non-Windows web services capable environment including Java and .NET. Although this solutions requires MS-Office to be installed on a server (not necessarily the same server as your application), it is very robust and provides perfect conversion fidelity. To generate or Modify MS-Word files I recommend using the free Open XML SDK for Microsoft Office. Eric White maintains a really good Blog about it. Disclaimer, I worked on this product. Having said that, it works great.
{ "language": "en", "url": "https://stackoverflow.com/questions/85404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do you port a virtual machine from VMWare to VirtualBox? I've been using VMWare for a while and am very happy with it, but I would like to compare it with VirtualBox. Apparently the disk images are compatible, and I have successfully booted my Fedora based VM created by VMWare in VirtualBox... but the network is completely unavailable. How do you port a virtual machine from VMWare to VirtualBox and keep all the capabilities intact? A: have you tried going into the options in virtual box and changing the network adapter to the VB one? VB is a bit different in it's virtual adapters, you might have to create a new one attached to the nic and then specify that one as the primary nic. A: If the network is unavailable, you may want to check your VirtualBox configuration and make sure you have a network card configured. If you do, then the next stop would be the OS running in the virtual machine. An unfortunate fact of some operating systems is that they don't always appreciate hardware changes. If the OS is not auto-detecting the change to the network card, you may need to reconfigure it to support the new card. Another possibility is that you were using a fixed IP address. VirtualBox uses a couple of schemes for networking that are a bit different than VMWare. You may need to change the IP inside the VM to match the expected subnet. Outside the VM, you need to use either a bridged networking device or configure ports virtual ports through the NAT system if you want to gain access to your Virtual Machine. A: Are you sure that network is completly unavailable? VirtualBox is known to have a problem with ICMP support so you won't be able to ping any host from the guest OS. I ran into the same problem yesterday and the network was actually working.
{ "language": "en", "url": "https://stackoverflow.com/questions/85414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rich Edit Control in raw Win32 Is the documentation for Rich Edit Controls really as bad (wrong?) as it seems to be? Right now I'm manually calling LoadLibrary("riched20.dll") in order to get a Rich Edit Control to show up. The documentation for Rich Edit poorly demonstrates this in the first code sample for using Rich Edit controls. It talks about calling InitCommonControlsEx() to add visual styles, but makes no mention of which flags to pass in. Is there a better way to load a Rich Edit control? http://msdn.microsoft.com/en-us/library/bb787877(VS.85).aspx Here's the only code I could write to make it work: #include "Richedit.h" #include "commctrl.h" INITCOMMONCONTROLSEX icex; icex.dwSize = sizeof(INITCOMMONCONTROLSEX); icex.dwICC = ICC_USEREX_CLASSES; //Could be 0xFFFFFFFF and it still wouldn't work InitCommonControlsEx(&icex); //Does nothing for Rich Edit controls LoadLibrary("riched20.dll"); //Manually? For real? hWndRichEdit = CreateWindowEx( ES_SUNKEN, RICHEDIT_CLASS, "", WS_BORDER | WS_VISIBLE | WS_CHILD, 2, 2, 100, 24, hWnd, (HMENU) ID_RICH_EDIT, hInst, NULL); A: Using MFC, RichEdit controls just work. Loading with InitCommonControlsEx() - ICC_USEREX_CLASSES doesn't load RichEdit AFAIK, you don't need it as it only does the 'standard' common controls, which don't include richedit. Apparently you only need to call this to enable 'visual styles' in Windows, not to get RichEdits working. If you're using 2008, you want to include Msftedit.dll and use the MSFTEDIT_CLASS instead (MS are rubbish for backward compatibilty sometimes). The docs do suggest you're doing it right for Win32 programming. A: Many years ago, I ran into this same issue, and yes, the answer was to load the .dll manually. The reason, as far as I can remember, is that the RichEdit window class is registered in DllMain of riched20.dll. A: Isn't there an import library (maybe riched20.lib) that you can link to. Then you won't have to load it "manually" at run time. That's how all the standard controls work. VS automatically adds a reference to user32.lib when you create a project. A: I think you have to call CoInitializeEx before you create any of the common controls. The LoadLibrary is not needed. If you link with the correct .lib file the exe-loader will take care of such details for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/85427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Code Outlining, Classic ASP and Visual Studio 2005 Is there a way to enable code outlining for Classic ASP in Visual Studio 2005? It outlines the HTML code pretty well and I get a big outline between <% and %>, but nothing for the code itself. A: Visual Studio 2008 SP1 has re-added support for classic ASP, but I don't believe either version supports the type of outlining you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/85434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sharepoint Item Level Access & performance i have created a workflow activity that do give the item creater of a specific list full control on the item and set everyone else to read only access (permission) someone told me that doing it this way (if i have a lot of users) the performance will go down dramatically is that correct ?!! if yes what is the best solution to create a list where any one can create new items but after the item is created only the creater can edit it and the rest of the users can read it only A: The accepted answer is not actually answering the question correctly... You should not use a workflow to do this, if you want people to be able to edit items they create and only read ones they did not, use "List->Settings->Advanced Settings->Item-level Permissions", and this is available for document libraries (since they inherit from SPLIST) it just does not show up in their "Advanced Settings" in the UI. You can set the ReadSecurity property to 1 and the WriteSecurity property to 2 on the Document Library. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist.writesecurity.aspx A: Performance degradation will happen when you use large ACLs for each list item. Just make sure that item-level permissions basically have the minimum entries. For example: * *The user that has permissions to edit that item *A single security group that contains all the users with only Reader permissions. So, can Sharepoint offer these default permissions OOB? Not that I'm aware of. The only option that I can think of is using workflows that set these permissions dinamycally when the document is uploaded. If you want to avoid performance degradation just make sure that you never display (or iterate using the object model) more than 2000 of those items in a Fine Grained Permissions list. THAT would definitely cause major performance issues. A: Yes, you might solve this with workflows but that might be a bit clumsy and it might slow your server. The better option is to use List Settings > Advanced Settings > Item-level Permissions. This feature is not available for Document and Form Libraries. A: It is true that a list that contains a large number of items with custom permissions applied, will slown down your server. This is document in the official Microsoft paper Plan for software boundaries. The recommended/magic number is 2000. Going further won't break anything, but it could be that you will run into performance issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/85444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server 2005 Linked Server to DB2 Performance issue I have a SQL Server 2005 machine with a JDE DB2 set up as a linked server. For some reason the performance of any queries from this box to the db2 box are horrible. For example. The following takes 7 mins to run from Management Studio SELECT * FROM F42119 WHERE SDUPMJ >= 107256 Whereas it takes seconds to run in iSeries Navigator Any thoughts? I'm assuming some config issue. A: In certain searches SQL Server will decide to pull the entire table down to itself and sort and search the data within SQL Server instead of sending the query to the remote server. This is usually a problem with collation settings. Make sure the provider has the following options set: Data Access, Collation Compatible, Use Remote Collation Then create a new Linked Server using the provider and select the following provider options Dynamic Parameters, Nested Queries, Allow In Process After setting the options change the query slightly to get a new query plan. A: It might be a memory issue on your SQL Server machine. I recently learned that linked server queries use memory allocation by the OS. Whereas native SQL Server queries use memory pre-allocated by SQL Server. If your SQL Server machine is configured to use 90% or more of the server's memory, I would scale that back a bit. Maybe 60% is the right place to be. Another thing to check is the SQL Server processor priority. Make sure "Boost SQL Server priority" is not enabled. I assume you are going through ODBC for access. Remember that you are not writing native db2 queries here, but instead ODBC sql queries. If you only need read-only data, you may want to try configuring your ODBC datasource to read-only mode (if that is an option). A: In a project with DB2 integration, I replaced every query via direct select or view by stored procedures calling the OPENQUERY function. My interpretation is that SqlServer fetches the whole table before applying the WHERE conditions, whereas OPENQUERY passes the SQL statement directly to the db driver. Anyway, performance was acceptable after the modifications. A: My first thought would go to the drivers. Years ago I had to link DB2 to SQL Server 2000 and it was extremely difficult to find the correct combination of drivers and setup parameters that would work... So maybe I'm biased because of that, but I would try upgrading or downgrading the driver or changing the setup so that the DB2 driver can run INPROC (if it's not already doing so). A: I've had several issues with DB2 as a linked a server. I do not know if it will address your problems, but here is what fixed mine: 1) Enabled lazy close support and pre-fetch during EXECUTE in the ODBC settings 2) Add "FOR FETCH ONLY" on all selects 3) Query using the SELECT * FROM OPENROWSET(LinkedServerName, 'SQL Command') method
{ "language": "en", "url": "https://stackoverflow.com/questions/85450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python's time.clock() vs. time.time() accuracy? Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy? for example: start = time.clock() ... do something elapsed = (time.clock() - start) vs. start = time.time() ... do something elapsed = (time.time() - start) A: The difference is very platform-specific. clock() is very different on Windows than on Linux, for example. For the sort of examples you describe, you probably want the "timeit" module instead. A: The short answer is: most of the time time.clock() will be better. However, if you're timing some hardware (for example some algorithm you put in the GPU), then time.clock() will get rid of this time and time.time() is the only solution left. Note: whatever the method used, the timing will depend on factors you cannot control (when will the process switch, how often, ...), this is worse with time.time() but exists also with time.clock(), so you should never run one timing test only, but always run a series of test and look at mean/variance of the times. A: I use this code to compare 2 methods .My OS is windows 8 , processor core i5 , RAM 4GB import time def t_time(): start=time.time() time.sleep(0.1) return (time.time()-start) def t_clock(): start=time.clock() time.sleep(0.1) return (time.clock()-start) counter_time=0 counter_clock=0 for i in range(1,100): counter_time += t_time() for i in range(1,100): counter_clock += t_clock() print "time() =",counter_time/100 print "clock() =",counter_clock/100 output: time() = 0.0993799996376 clock() = 0.0993572257367 A: time.clock() was removed in Python 3.8 because it had platform-dependent behavior: * *On Unix, return the current processor time as a floating point number expressed in seconds. *On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number print(time.clock()); time.sleep(10); print(time.clock()) # Linux : 0.0382 0.0384 # see Processor Time # Windows: 26.1224 36.1566 # see Wall-Clock Time So which function to pick instead? * *Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this. * *Use time.process_time() *Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time. * *Use time.perf_counter() * *time.time() also measures wall-clock time but can be reset, so you could go back in time *time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter() A: On Unix time.clock() measures the amount of CPU time that has been used by the current process, so it's no good for measuring elapsed time from some point in the past. On Windows it will measure wall-clock seconds elapsed since the first call to the function. On either system time.time() will return seconds passed since the epoch. If you're writing code that's meant only for Windows, either will work (though you'll use the two differently - no subtraction is necessary for time.clock()). If this is going to run on a Unix system or you want code that is guaranteed to be portable, you will want to use time.time(). A: Others have answered re: time.time() vs. time.clock(). However, if you're timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the timeit module. A: clock() -> floating point number Return the CPU time or real time since the start of the process or since the first call to clock(). This has as much precision as the system records. time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. Usually time() is more precise, because operating systems do not store the process running time with the precision they store the system time (ie, actual time) A: One thing to keep in mind: Changing the system time affects time.time() but not time.clock(). I needed to control some automatic tests executions. If one step of the test case took more than a given amount of time, that TC was aborted to go on with the next one. But sometimes a step needed to change the system time (to check the scheduler module of the application under test), so after setting the system time a few hours in the future, the TC timeout expired and the test case was aborted. I had to switch from time.time() to time.clock() to handle this properly. A: Short answer: use time.clock() for timing in Python. On *nix systems, clock() returns the processor time as a floating point number, expressed in seconds. On Windows, it returns the seconds elapsed since the first call to this function, as a floating point number. time() returns the the seconds since the epoch, in UTC, as a floating point number. There is no guarantee that you will get a better precision that 1 second (even though time() returns a floating point number). Also note that if the system clock has been set back between two calls to this function, the second function call will return a lower value. A: To the best of my understanding, time.clock() has as much precision as your system will allow it. A: As of 3.3, time.clock() is deprecated, and it's suggested to use time.process_time() or time.perf_counter() instead. Previously in 2.7, according to the time module docs: time.clock() On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. Additionally, there is the timeit module for benchmarking code snippets. A: Depends on what you care about. If you mean WALL TIME (as in, the time on the clock on your wall), time.clock() provides NO accuracy because it may manage CPU time. A: time() has better precision than clock() on Linux. clock() only has precision less than 10 ms. While time() gives prefect precision. My test is on CentOS 6.4, python 2.6 using time(): 1 requests, response time: 14.1749382019 ms 2 requests, response time: 8.01301002502 ms 3 requests, response time: 8.01491737366 ms 4 requests, response time: 8.41021537781 ms 5 requests, response time: 8.38804244995 ms using clock(): 1 requests, response time: 10.0 ms 2 requests, response time: 0.0 ms 3 requests, response time: 0.0 ms 4 requests, response time: 10.0 ms 5 requests, response time: 0.0 ms 6 requests, response time: 0.0 ms 7 requests, response time: 0.0 ms 8 requests, response time: 0.0 ms A: As others have noted time.clock() is deprecated in favour of time.perf_counter() or time.process_time(), but Python 3.7 introduces nanosecond resolution timing with time.perf_counter_ns(), time.process_time_ns(), and time.time_ns(), along with 3 other functions. These 6 new nansecond resolution functions are detailed in PEP 564: time.clock_gettime_ns(clock_id) time.clock_settime_ns(clock_id, time:int) time.monotonic_ns() time.perf_counter_ns() time.process_time_ns() time.time_ns() These functions are similar to the version without the _ns suffix, but return a number of nanoseconds as a Python int. As others have also noted, use the timeit module to time functions and small code snippets. A: Right answer : They're both the same length of a fraction. But which faster if subject is time ? A little test case : import timeit import time clock_list = [] time_list = [] test1 = """ def test(v=time.clock()): s = time.clock() - v """ test2 = """ def test(v=time.time()): s = time.time() - v """ def test_it(Range) : for i in range(Range) : clk = timeit.timeit(test1, number=10000) clock_list.append(clk) tml = timeit.timeit(test2, number=10000) time_list.append(tml) test_it(100) print "Clock Min: %f Max: %f Average: %f" %(min(clock_list), max(clock_list), sum(clock_list)/float(len(clock_list))) print "Time Min: %f Max: %f Average: %f" %(min(time_list), max(time_list), sum(time_list)/float(len(time_list))) I am not work an Swiss labs but I've tested.. Based of this question : time.clock() is better than time.time() Edit : time.clock() is internal counter so can't use outside, got limitations max 32BIT FLOAT, can't continued counting if not store first/last values. Can't merge another one counter... A: Comparing test result between Ubuntu Linux and Windows 7. On Ubuntu >>> start = time.time(); time.sleep(0.5); (time.time() - start) 0.5005500316619873 On Windows 7 >>> start = time.time(); time.sleep(0.5); (time.time() - start) 0.5
{ "language": "en", "url": "https://stackoverflow.com/questions/85451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "451" }
Q: Limiting results of System.Data.Linq.Table I am trying to inherit from my generated datacontext in LinqToSQL - something like this public class myContext : dbDataContext { public System.Data.Linq.Table<User>() Users { return (from x in base.Users() where x.DeletedOn.HasValue == false select x); } } But my Linq statement returns IQueryable which cannot cast to Table - does anyone know a way to limit the contents of a Linq.Table - I am trying to be certain that anywhere my Users table is accessed, it doesn't return those marked deleted. Perhaps I am going about this all wrong - any suggestions would be greatly appreciated. Hal A: Another approach would to be use views.. CREATE VIEW ActiveUsers as SELECT * FROM Users WHERE IsDeleted = 0 As far as linq to sql is concerned, that is just the same as a table. For any table that you needed the DeletedOn filtering, just create a view that uses the filter and use that in place of the table in your data context. A: You could use discriminator column inheritance on the table, ie. a DeletedUsers table and ActiveUsers table where the discriminator column says which goes to which. Then in your code, just reference the Users.OfType ActiveUsers, which will never include anything deleted. As a side note, how the heck do you do this with markdown? Users.OfType<ActiveUsers> I can get it in code, but not inline A: Encapsulate your DataContext so that developers don't use Table in their queries. I have an 'All' property on my repositories that does a similar filtering to what you need. So then queries are like: from item in All where ... select item and all might be: public IQueryable<T> All { get { return MyDataContext.GetTable<T>.Where(entity => !entity.DeletedOn.HasValue); } } A: You can use a stored procedure that returns all the mapped columns in the table for all the records that are not marked deleted, then map the LINQ to SQL class to the stored procedure's results. I think you just drag-drop the stored proc in Server Explorer on to the class in the LINQ to SQL designer. A: What I did in this circumstance is I created a repository class that passes back IQueryable but basically is just from t in _db.Table select t; this is usually referenced by tableRepository.GetAllXXX(); but you could have a tableRepository.GetAllNonDeletedXXX(); that puts in that preliminary where clause to take out the deleted rows. This would allow you to get back the deleted ones, the undeleted ones and all rows using different methods. A: Perhaps my comment to Keven sheffield's response may shed some light on what I am trying to accomplish: I have a similar repository for most of my data access, but I am trying to be able to traverse my relationships and maintain the DeletedOn logic, without actually calling any additional methods. The objects are interrogated (spelling fixed) by a StringTemplate processor which can't call methods (just props/fields). I will ultimately need this DeletedOn filtering for all of the tables in my application. The inherited class solution from Scott Nichols should work (although I will need to derive a class and relationships for around 30 tables - ouch), although I need to figure out how to check for a null value in my Derived Class Discriminator Value property. I may just end up extended all my classes specifically for the StringTemplate processing, explicitly adding properties for the relationships I need, I would just love to be able to throw StringTemplate a [user] and have it walk through everything. A: There are a couple of views we use in associations and they still appear just like any other relationship. We did need to add the associations manually. The only thing I can think to suggest is to take a look at the properties and decorated attributes generated for those classes and associations. Add a couple tables that have the same relationship and compare those to the view that isn't showing up. Also, sometimes the refresh on the server explorer connection doesn't seem to work correctly and the entities aren't created correctly initially, unless we remove them from the designer, close the project, then reopen the project and add them again from the server explorer. This is assuming you are using Visual Studio 2008 with the linq to sql .dbml designer. A: I found the problem that I had with the relationships/associations not showing in the views. It seems that you have to go through each class in the dbml and set a primary key for views as it is unable to extract that information from the schema. I am in the process of setting the primary keys now and am planning to go the view route to isolate only non-deleted items. Thanks and I will update more later.
{ "language": "en", "url": "https://stackoverflow.com/questions/85457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to combine a series of PDFs into one using Ruby? I have a series of PDFs named sequentially like so: * *01_foo.pdf *02_bar.pdf *03_baz.pdf *etc. Using Ruby, is it possible to combine these into one big PDF while keeping them in sequence? I don't mind installing any necessary gems to do the job. If this isn't possible in Ruby, how about another language? No commercial components, if possible. Update: Jason Navarrete's suggestion lead to the perfect solution: Place the PDF files needing to be combined in a directory along with pdftk (or make sure pdftk is in your PATH), then run the following script: pdfs = Dir["[0-9][0-9]_*"].sort.join(" ") `pdftk #{pdfs} output combined.pdf` Or I could even do it as a one-liner from the command-line: ruby -e '`pdftk #{Dir["[0-9][0-9]_*"].sort.join(" ")} output combined.pdf`' Great suggestion Jason, perfect solution, thanks. Give him an up-vote people. A: You can do this by converting to PostScript and back. PostScript files can be concatenated trivially. For example, here's a Bash script that uses the Ghostscript tools ps2pdf and pdf2ps: #!/bin/bash for file in 01_foo.pdf 02_bar.pdf 03_baz.pdf; do pdf2ps $file - >> temp.ps done ps2pdf temp.ps output.pdf rm temp.ps I'm not familiar with Ruby, but there's almost certainly some function (might be called system() (just a guess)) that will invoke a given command line. A: If you have ghostscript on your platform, shell out and execute this command: gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf <your source pdf files> A: I tried the pdftk solution and had problems on both SnowLeopard and Tiger. Installing on Tiger actually wreaked havoc on my system and left me unable to run script/server, fortunately it’s a machine retired from web development. Subsequently found another option: - joinPDF. Was an absolutely painless and fast install and it works perfectly. Also tried GhostScript and it failed miserably (could not read the fonts and I ended up with PDFs that had images only). But if you’re looking for a solution to this problem, you might want to try joinPDF. A: A Ruby-Talk post suggests using the pdftk toolkit to merge the PDFs. It should be relatively straightforward to call pdftk as an external process and have it handle the merging. PDF::Writer may be overkill because all you're looking to accomplish is a simple append. A: I don't think Ruby has tools for that. You might check ImageMagick and Cairo. ImageMagick can be used for binding multiple pictures/documents together, but I'm not sure about the PDF case. Then again, there are surely Windows tools (commercial) to do this kind of thing. I use Cairo myself for generating PDF's. If the PDF's are coming from you, maybe that would be a solution (it does support multiple pages). Good luck! A: I'd suggest looking at the code for PDFCreator (VB, if I'm not mistaken, but that shouldn't matter since you'd just be implementing similar code in another language), which uses GhostScript (GNU license). Or just dig straight into GhostScript itself; there's also a facade layer available called GhostPDF, which may do what you want. If you can control GhostScript with VB, you can do it with C, which means you can do it with Ruby. Ruby also has IO.popen, which allows you to call out to external programs that can do this. A: Any Ruby code to do this in a real application is probably going to be painfully slow. I would try and hunt down unix tools to do the job. This is one of the beauties of using Mac OS X, it has very fast PDF capabilities built-in. The next best thing is probably a unix tool. Actually, I've had some success with rtex. If you look here you'll find some information about it. It is much faster than any Ruby library that I've used and I'm pretty sure latex has a function to bring in PDF data from other sources.
{ "language": "en", "url": "https://stackoverflow.com/questions/85459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: MVC C# custom MvcRouteHandler - How to? Does anyone have experiences in providing a custom MvcRouteHandler? In my application I'd like to implement a globalization-pattern like http://mydomain/en/about or http://mydomain/de/about. As for persistance, I'd like to have a cookie read as soon as a request arrives and if there is a language setting in this cookie apply it (so a user arriving at http://mydomain/ would be transferred to http://mydomain/en/ for example). If there is no cookie present, I'd like to get the first language the browser supports, apply this one and store it in this cookie. I guess this can't be done with the standard routing mechanism mvc provides in it's initial project template. In a newsgroup I got the tip to have a look at the MvcRouteHandler and implement my own. But its hard to find a sample on how to do that. Any ideas? A: I don't believe a custom route handler is required for what you are doing. For your "globalized" URIs, a regular MVC route, with a constraint that the "locale" parameter must be equal to "en", "de", etc., will do. The constraint will prevent non-globalized URIs from matching the route. For a "non-globalized" URI, make a "catch-all" route which simply redirects to the default or cookie-set locale URI. Place the "globalized" route above the "catch-all" route in Global.asax, so that "already-globalized" URIs don't fall through to the redirection. You would need to make a new route handler if you want a certain URI pattern to trigger something that is not an action on a controller. But I don't think that's what you're dealing with, here. A: You should be able to do this with ASP.NET MVC's default template, I'm doing something similar. Just build your routes as {language}/{controller}/{action}/{id} Just set a default route that goes to a controller that checks for the language cookie, and redirects the user based on that cookie.
{ "language": "en", "url": "https://stackoverflow.com/questions/85470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C# Unsafe/Fixed Code Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. Consider this code... fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } compared to simply using... Array.Copy(source, target, source.Length); The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx. The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head? A: reinterpret_cast style behaviour If you are bit manipulating then this can be incredibly useful many high performance hashcode implementations use UInt32 for the hash value (this makes the shifts simpler). Since .Net requires Int32 for the method you want to quickly convert the uint to an int. Since it matters not what the actual value is, only that all the bits in the value are preserved a reinterpret cast is desired. public static unsafe int UInt32ToInt32Bits(uint x) { return *((int*)(void*)&x); } note that the naming is modelled on the BitConverter.DoubleToInt64Bits Continuing in the hashing vein, converting a stack based struct into a byte* allows easy use of per byte hashing functions: // from the Jenkins one at a time hash function private static unsafe void Hash(byte* data, int len, ref uint hash) { for (int i = 0; i < len; i++) { hash += data[i]; hash += (hash << 10); hash ^= (hash >> 6); } } public unsafe static void HashCombine(ref uint sofar, long data) { byte* dataBytes = (byte*)(void*)&data; AddToHash(dataBytes, sizeof(long), ref sofar); } unsafe also (from 2.0 onwards) lets you use stackalloc. This can be very useful in high performance situations where some small variable length array like temporary space is needed. All of these uses would be firmly in the 'only if your application really needs the performance' and thus are inappropriate in general use, but sometimes you really do need it. fixed is necessary for when you wish to interop with some useful unmanaged function (there are many) that takes c-style arrays or strings. As such it is not only for performance reasons but correctness ones when in interop scenarios. A: Unsafe is useful for (for example) getting pixel data out of an image quickly using LockBits. The performance improvement over doing this using the managed API is several orders of magnitude. A: It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory. If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call. A: We had to use a fixed when an address gets passed to a legacy C DLL. Since the DLL maintained an internal pointer across function calls, all hell would break loose if the GC compacted the heap and moved stuff around. A: I've used unsafe-blocks to manipulate Bitmap-data. Raw pointer-access is significantly faster than SetPixel/GetPixel. unsafe { BitmapData bmData = bm.LockBits(...) byte *bits = (byte*)pixels.ToPointer(); // Do stuff with bits } "fixed" and "unsafe" is typically used when doing interop, or when extra performance is required. Ie. String.CopyTo() uses unsafe and fixed in its implementation. A: I believe unsafe code is used if you want to access something outside of the .NET runtime, ie. it is not managed code (no garbage collection and so on). This includes raw calls to the Windows API and all that jazz. A: This tells me the designers of the .NET framework did a good job of covering the problem space--of making sure the "managed code" environment can do everything a traditional (e.g. C++) approach can do with its unsafe code/pointers. In case it cannot, the unsafe/fixed features are there if you need them. I'm sure someone has an example where unsafe code is needed, but it seems rare in practice--which is rather the point, isn't it? :)
{ "language": "en", "url": "https://stackoverflow.com/questions/85479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: How can I return the content of an XML field as a recordset? Say I've got this table (SQL Server 2005): Id => integer MyField => XML Id MyField 1 < Object>< Type>AAA< /Type>< Value>10< /Value>< /Object>< Object>< Type>BBB< /Type><Value>20< /Value>< /Object> 2 < Object>< Type>AAA< /Type>< Value>15< /Value>< /Object> 3 < Object>< Type>AAA< /Type>< Value>20< /Value>< /Object>< Object>< Type>BBB< /Type>< Value>30< /Value>< /Object> I need a TSQL query which would return something like this: Id AAA BBB 1 10 20 2 15 NULL 3 20 30 Note that I won't know if advance how many 'Type' (eg AAA, BBB, CCC,DDD, etc.) there will be in the xml string. A: You will need to use the XML querying in sql server to do that. somethings like select id, MyField.query('/Object/Type[.="AAA"]/Value') as AAA, MyField.query('/Object/Type[.="BBB"]/Value) AS BBB not sure if that's 100% correct xquery syntax, but it's going to be something like that. A: One possible option is to use the XMLDataDocument. Using this class you can retrieve the data as XML load it into the XmlDataDocument and then use the Dataset property to access it as if it were a standard dataset. A: You'll need to use CROSS APPLY. Here's an example based on your request: declare @y table (rowid int, xmlblock xml) insert into @y values(1,'<Object><Type>AAA</Type><Value>10</Value></Object><Object><Type>BBB</Type><Value>20</Value></Object>') insert into @y values(2,'<Object><Type>AAA</Type><Value>15</Value></Object>') insert into @y values(3,'<Object><Type>AAA</Type><Value>20</Value></Object><Object><Type>BBB</Type><Value>30</Value></Object>') select y.rowid, t.b.value('Type[1]', 'nvarchar(5)'), t.b.value('Value[1]', 'int') from @y y CROSS APPLY XmlBlock.nodes('//Object') t(b) Oh, and your example XML is invalid, the first row is missing the opening Value element for Type BBB.
{ "language": "en", "url": "https://stackoverflow.com/questions/85481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding a SVN repository in Eclipse I'm trying to add an SVN repository to Eclipse. I've installed Subclipse, and it seems to be working fine. But, when I try to "add a new SVN repository", I input this, for example: http://svn.python.org/projects/peps/trunk I get this: Error validating location: "org.tigris.subversion.javahl.ClientException: RA layer request failed svn: OPTIONS of 'http://svn.python.org/projects/peps/trunk': could not connect to server (http://svn.python.org) " Keep location anyway? I know that my Eclipse can connect to the Internet, because I downloaded Subclipse earlier (I had to change my proxy settings). I get a similar message for other SVN locations I've tried to add. What is the solution? A: At my day job I sit behind a corporate firewall protecting and caching web traffic (among other things). For the most part it stays out of the way. But sometimes it rears its ugly head and stands firmly in the path of what I am trying to do. Earlier this week I was trying to look at a cool new general validation system for ColdFusion called Validat, put out by the great guys at Alagad. They don't have a download on the RIAForge site yet, but the files are available via SVN. I loaded up the subclipse plugin into my Eclipse, restarted and began adding the Validat SVN repository. I started getting errors abou the "RA layer request failed" and "svn: PROPFIND request failed on /Validat/trunk", followed by an error about not being able to connect to the SVN server. I already had Eclipse setup with my proxy settings, so I thought I was doing something wrong or Alagad didn't actually have the subversion repository up-and-available. After going home that night, I tried it from home and wa-la it worked. Stupid proxy server! So the subclipse plugin won't use the Eclipse proxy settings. (Can that be fixed please!). After digging around the subclipse help site and being redirected to the collab.net help, then unproductively searching through the eclipse workspace, plugins, and configuration folders for the settings file, I was finally able to figure out how to set up subclipse to use the proxy server. In my Windows development environment, I opened the following file: C:\Documents and Settings\MyUserId\Application Data\Subversion\servers in my favorite text editor. Near the bottom of that file is a [global] section with http-proxy-host and http-proxy-port settings. I uncommented those two lines, modified them for my corporate proxy server, went back to the SVN Repository view in Eclipse, refreshed the Validat repository and Boom! it worked! from http://www.mkville.com/blog/index.cfm/2007/11/8/Using-Subclipse-Behind-a-Proxy-Server A: Try to connect to the repository using command line SVN to see if you get a similar error. $ svn checkout http://svn.python.org/projects/peps/trunk If you keep getting the error, it is probably an issue with your proxy server. I have found that I can't check out internet based SVN projects at work because the firewall blocks most HTTP commands. It only allows GET, POST and others necessary for browsing. A: I doubt that Subclipse and then SVN can use your Eclipse proxy settings. You'll probably need to set the proxy for your SVN program itself. Trying to check out the files using SVN from the command line should tell you if that works. If SVN can't connect either then put the proxy settings in your servers file in your Subversion settings folder (in your home folder). If it can't do it even with the proxy settings set, then your firewall is probably blocking the methods and protocols that Subversion needs to use to download the files. A: When trying to connect to the Collabnet subversion from eclipse I was also getting the same error as 'Peter Hilton' described in his original post. I changed the settings of Active Provided from 'Native' to 'manual' in windows->Preferences->General->Network Connections. This worked for me. I think this was a proxy problem but with my old settints eclipse was connecting to the internet from where i DOWNLOADED THE subversion plugins. A: It is probably of little help to you, but I enter that URL into Subclipse and the repository adds fine and I can browse and Show History on it. Do you perhaps need to configure a proxy? You have to configure that in the Subversion runtime configuration area as Subclipse uses the Subversion libraries to connect to the server. A: This is a dead topic, but the solution is to install a client adapter along with Subclipse. Take a look at this, and install SVN Client Adapter, SVNKit Adapter, and SVNKit Library. Then check under Window -> Preference -> Team -> SVN and make sure there is an entry for SVN Interface. And for future reference, if you can connect to the repository through the command line, then it must be a problem with the IDE. A: It worked for me, In eclipse: Window > Preference > Team > SVN: select SVNKit (Pure Java) instead JavaHL(JNI) A: Do you have any working repositories in this instance of eclipse? I've had problems in the past with the default Subclipse subversion client on Windows, you need to make sure the native subversion client is installed and correctly configured (I've got TortoiseSVN to work in the past) if you want to use the default client adapter. On a recent install I tried the "beta" drivers (I have Eclipse Ganymede and "SVNKit (Pure Java) SVNKit v1.2.0.4502") that you can optionally install with Subclipse and they worked pretty much straight out of the box, although a colleague found he had to go through a few hoops to make sure Eclipse installed them (and their dependancies) correctly. Here are the packages that appear in "Help" -> "Software Updates" -> "Installed Software": Subclipse 1.4.0 Subversion Client Adapter 1.5.0.1 SVNKit Client Adapter 1.5.0.1 SVNKit Library 1.2.0.4502 These are probably a little out of date now, and the latest version will probably work better, but this is what I can see working right now. A: I found this problem when I changed my SVN password. How to resolve First, remove Subversion folder in {Documents and Settings}{user login}\Application Data\Subversion -> It doesn't work After, rename my current user login profile from {Documents and Settings}{user login} to {Documents and Settings}{user login}_bakup and login agian -> It work... I assumed -> SVN or JavaHL bind authorized user with {user login} or keep it in user profile of window. A: I has the same problem. McAFee had blocked the eclipse. solve it in the manager McAFee> Firewall> progamas internet connection to> find the eclipse and allow full access. regards A: I was facing this problem and, as mentioned previously here, I changed the "servers" file under Subversion folder in "C:\Users\userid\AppData\Roaming\Subversion". There, in the file's bottom, there is a [global] section. I removed the comments from http-proxy-host http-proxy-port http-proxy-username http-proxy-password I set those guys and it worked! :-) A: I saw the same error and solved by switching off the proxy settings in TortoiseSVN that I normally need for commits to the company servers. I installed Subclipse to back up my own non-prime-time stuff to a local repository (using VisualSVN). I use Eclipse Galileo 3.3 and Subclipse 1.6.12. A: Necropost, but helpful: I came across this problem with an RA request failed since the files "already existed on the server" but wouldn't sync with my repository. I went to the source on my disk, deleted there, refreshed my Eclipse view, and updated the source. Error gone. A: In my case was an access issue. I needed to change the protocol to svn+ssh instead of http. For example, instead of http://svn.python.org/projects/peps/trunk try svn+ssh://svn.python.org/projects/peps/trunk A: You might want to check if the websecurity of vpn client is the issue. I uninstalled it and it worked fine..Found the solution here https://superuser.com/questions/471089/svn-connection-not-successful A: I have exactly the same issue with you. I have TortoiseSVN installed on my windows, I have also eclipse installed, in the eclipse, I have the subclipse 1.4 installed. here is the issue I have proxy settings, I can open the repo through web browser, for some reason, I cannot open a repo through svn. I tried to change the proxy following the link below Eclipse Kepler not connecting to internet via proxy. It doesn't work. Finally I found out a solution You have to change the proxy setting in TortoiseSVN. After I enable the proxy setting the same with my browser. The issue is gone. here is the link of how to enable proxy setting in TortoiseSVN https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html Seach "Network Settings" on the page above A: In my case, im getting the similar exception when trying to checkout the project from SVN repo it is prompting for the username and password and i was giving the wrong username every time, when i gave the correct username and password its started working fine..... Such a simple and Hardstopping message.....
{ "language": "en", "url": "https://stackoverflow.com/questions/85486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Reverse DNS lookup in perl How do I perform a reverse DNS lookup, that is how do I resolve an IP address to its DNS hostname in Perl? A: perl -MSocket -E 'say scalar gethostbyaddr(inet_aton("69.89.27.250"), AF_INET)' Returns: Can't find string terminator "'" anywhere before EOF at -e line 1. perl -MSocket -E "say scalar gethostbyaddr(inet_aton(\"69.89.27.250\"), AF_INET)" Returns: box250.bluehost.com I have to change the line to use double quotes and then escape out the quotes around the IP address A: If you need more detailed DNS info use the Net::DNS module, here is an example: use Net::DNS; my $res = Net::DNS::Resolver->new; # create the reverse lookup DNS name (note that the octets in the IP address need to be reversed). my $IP = "209.85.173.103"; my $target_IP = join('.', reverse split(/\./, $IP)).".in-addr.arpa"; my $query = $res->query("$target_IP", "PTR"); if ($query) { foreach my $rr ($query->answer) { next unless $rr->type eq "PTR"; print $rr->rdatastr, "\n"; } } else { warn "query failed: ", $res->errorstring, "\n"; } Original Source EliteHackers.info, more details there as well. A: gethostbyaddr and similar calls. See http://perldoc.perl.org/functions/gethostbyaddr.html A: one-liner: perl -MSocket -E 'say scalar gethostbyaddr(inet_aton("79.81.152.79"), AF_INET)' A: use Socket; $iaddr = inet_aton("127.0.0.1"); # or whatever address $name = gethostbyaddr($iaddr, AF_INET); A: There may be an easier way, but for IPv4, if you can perform ordinary DNS lookups, you can always construct the reverse query yourself. For the IPv4 address A.B.C.D, look up any PTR records at D.C.B.A.in-addr.arpa. For IPv6, you take the 128 hex nibbles and flip them around and append ipv6.arpa. and do the same thing. A: If gethostbyaddr doesn't fit your needs, Net::DNS is more flexible. A: This might be useful... $ip = "XXX.XXX.XXX.XXX" # IPV4 address. my @numbers = split (/\./, $ip); if (scalar(@numbers) != 4) { print "$ip is not a valid IP address.\n"; next; } my $ip_addr = pack("C4", @numbers); # First element of the array returned by gethostbyaddr is host name. my ($name) = (gethostbyaddr($ip_addr, 2))[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/85487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: AJAX - How to Pass value back to server First time working with UpdatePanels in .NET. I have an updatepanel with a trigger pointed to an event on a FormView control. The UpdatePanel holds a ListView with related data from a separate database. When the UpdatePanel refreshes, it needs values from the FormView control so that on the server it can use them to query the database. For the life if me, I can't figure out how to get those values. The event I'm triggering from has them, but I want the updatepanel to refresh asynchronously. How do I pass values to the load event on the panel? Googled this ad nauseum and can't seem to get to an answer here. A link or an explanation would be immensely helpful.. Jeff A: make a javascript function that will collect the pieces of form data, and then sends that data to an ASHX handler. the ASHX handler will do some work, and can reply with a response. This is an example I made that calls a database to populate a grid using AJAX calls. There are better libraries for doing AJAX (prototype, ExtJS, etc), but this is the raw deal. (I know this can be refactored to be even cleaner, but you can get the idea well enough) Works like this... * *User enters text in the search box, *User clicks search button, *JavaScript gets form data, *javascript makes ajax call to ASHX, *ASHX receives request, *ASHX queries database, *ASHX parses the response into JSON/Javascript array, *ASHX sends response, *Javascript receives response, *javascript Eval()'s response to object, *javascript iterates object properties and fills grid The html will look like this... <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <script type="text/javascript" src="AjaxHelper.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtSearchValue" runat="server"></asp:TextBox> <input id="btnSearch" type="button" value="Search by partial full name" onclick="doSearch()"/> <igtbl:ultrawebgrid id="uwgUsers" runat="server" //infragistics grid crap </igtbl:ultrawebgrid>--%> </div> </form> </body> </html> The script that fires on click will look like this... //this is tied to the button click. It takes care of input cleanup and calling the AJAX method function doSearch(){ var eleVal; var eleBtn; eleVal = document.getElementById('txtSearchValue').value; eleBtn = document.getElementById('btnSearch'); eleVal = trim(eleVal); if (eleVal.length > 0) { eleBtn.value = 'Searching...'; eleBtn.disabled = true; refreshGridData(eleVal); } else { alert("Please enter a value to search with. Unabated searches are not permitted."); } } //This is the function that will go out and get the data and call load the Grid on AJAX call //return. function refreshGridData(searchString){ if (searchString =='undefined'){ searchString = ""; } var xhr; var gridData; var url; url = "DefaultHandler.ashx?partialUserFullName=" + escape(searchString); xhr = GetXMLHttpRequestObject(); xhr.onreadystatechange = function() { if (xhr.readystate==4) { gridData = eval(xhr.responseText); if (gridData.length > 0) { //clear and fill the grid clearAndPopulateGrid(gridData); } else { //display appropriate message } } //if (xhr.readystate==4) { } //xhr.onreadystatechange = function() { xhr.open("GET", url, true); xhr.send(null); } //this does the grid clearing and population, and enables the search button when complete. function clearAndPopulateGrid(jsonObject) { var grid = igtbl_getGridById('uwgUsers'); var eleBtn; eleBtn = document.getElementById('btnSearch'); //clear the rows for (x = grid.Rows.length; x >= 0; x--) { grid.Rows.remove(x, false); } //add the new ones for (x = 0; x < jsonObject.length; x++) { var newRow = igtbl_addNew(grid.Id, 0, false, false); //the cells should not be referenced by index value, so a name lookup should be implemented newRow.getCell(0).setValue(jsonObject[x][1]); newRow.getCell(1).setValue(jsonObject[x][2]); newRow.getCell(2).setValue(jsonObject[x][3]); } grid = null; eleBtn.disabled = false; eleBtn.value = "Search by partial full name"; } // this function will return the XMLHttpRequest Object for the current browser function GetXMLHttpRequestObject() { var XHR; //the object to return var ua = navigator.userAgent.toLowerCase(); //gets the useragent text try { //determine the browser type if (!window.ActiveXObject) { //Non IE Browsers XHR = new XMLHttpRequest(); } else { if (ua.indexOf('msie 5') == -1) { //IE 5.x XHR = new ActiveXObject("Msxml2.XMLHTTP"); } else { //IE 6.x and up XHR = new ActiveXObject("Microsoft.XMLHTTP"); } } //end if (!window.ActiveXObject) if (XHR == null) { throw "Unable to instantiate the XMLHTTPRequest object."; } } catch (e) { alert("This browser does not appear to support AJAX functionality. error: " + e.name + " description: " + e.message); } return XHR; } //end function GetXMLHttpRequestObject() function trim(stringToTrim){ return stringToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } And the ashx handler looks like this.... Imports System.Web Imports System.Web.Services Imports System.Data Imports System.Data.SqlClient Public Class DefaultHandler Implements System.Web.IHttpHandler Private Const CONN_STRING As String = "Data Source=;Initial Catalog=;User ID=;Password=;" Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/plain" context.Response.Expires = -1 Dim strPartialUserName As String Dim strReturnValue As String = String.Empty If context.Request.QueryString("partialUserFullName") Is Nothing = False Then strPartialUserName = context.Request.QueryString("partialUserFullName").ToString() If String.IsNullOrEmpty(strPartialUserName) = False Then strReturnValue = SearchAndReturnJSResult(strPartialUserName) End If End If context.Response.Write(strReturnValue) End Sub Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String Dim strReturnValue As New StringBuilder() Dim conn As SqlConnection Dim strSQL As New StringBuilder() Dim objParam As SqlParameter Dim da As SqlDataAdapter Dim ds As New DataSet() Dim dr As DataRow 'define sql strSQL.Append(" SELECT ") strSQL.Append(" [id] ") strSQL.Append(" ,([first_name] + ' ' + [last_name]) ") strSQL.Append(" ,[email] ") strSQL.Append(" FROM [person] (NOLOCK) ") strSQL.Append(" WHERE [last_name] LIKE @lastName") 'clean up the partial user name for use in a like search If partialUserName.EndsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then partialUserName = partialUserName & "%" End If If partialUserName.StartsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then partialUserName = partialUserName.Insert(0, "%") End If 'create the oledb parameter... parameterized queries perform far better on repeatable 'operations objParam = New SqlParameter("@lastName", SqlDbType.VarChar, 100) objParam.Value = partialUserName conn = New SqlConnection(CONN_STRING) da = New SqlDataAdapter(strSQL.ToString(), conn) da.SelectCommand.Parameters.Add(objParam) Try 'to get a dataset. da.Fill(ds) Catch sqlex As SqlException 'Throw an appropriate exception if you can add details that will help understand the problem. Throw New DataException("Unable to retrieve the results from the user search.", sqlex) Finally If conn.State = ConnectionState.Open Then conn.Close() End If conn.Dispose() da.Dispose() End Try 'make sure we have a return value If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count <= 0 Then Return String.Empty End If 'This converts the table into JS array. strReturnValue.Append("[") For Each dr In ds.Tables(0).Rows strReturnValue.Append("['" & CStr(dr("username")) & "','" & CStr(dr("userfullname")) & "','" & CStr(dr("useremail")) & "'],") Next strReturnValue.Remove(strReturnValue.Length - 1, 1) strReturnValue.Append("]") 'de-allocate what can be deallocated. Setting to Nothing for smaller types may 'incur performance hit because of a forced allocation to nothing before they are deallocated 'by garbage collection. ds.Dispose() strSQL.Length = 0 Return strReturnValue.ToString() End Function ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class A: Try * *...looking in the Request and Response. *...setting a breakpoint on the Load() method and query Me or this in the watch or immediate window to see if the values you want are maybe just not where you are expecting them? *...Put a (For Each ctl as Control in Me/This.Controls) and inspecting each control that is iterated and see if you are even getting the controls you expect. *... its not in Sender or EventArgs? Try NOT using Update panels.... They can often cause more trouble than they are worth. It may be faster and less headache to use regular AJAX to get it done. A: If you are working with an UpdatePanel just make sure that both controls are inside the panel and it will work as desired.
{ "language": "en", "url": "https://stackoverflow.com/questions/85500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What does the option "convert to web application" do if I select it in visual studio? What does the option “convert to web application” do if I select it in visual studio? If I do convert my site to a web application what are the advantages? Can I go back? A: Also Answered Here so go vote that answer up, not this one. Don't give me credit There are two types of web applications in ASP.NET: The Web Site and Web Application Project. The difference between the two are discussed here: Difference between web site and web applications in Visual Studio 2005 Convert to Website allows you to convert a Web Application Project to a Web Site. Visual Studio 2003 used the Web Application Project style, but initially VS2005 only supported web sites. VS2005 SP1 brought back Web Applications. If you don't want to convert your project to a web site, apply SP1 if you're using VS2005. VS2008 can support either. A: Well, it converts your web site to a web application project. As for the advantages, here is some further reading: MSDN comparison -- Comparing Web Site Projects and Web Application Projects Webcast on ASP.NET -- Web Application Projects vs. Web Site Projects in Visual Studio 2008 "In this webcast, by request, we examine the differences between web application projects and web site projects in Microsoft Visual Studio 2008. We focus specifically on the reasons you would choose one over the other and explain how to make informed decisions when creating a Web solution" The primary difference (to me) between a web application project and a web site is how things gets compiled. In web sites each page has its code-behind compiled into a separate library, whereas in web applications all code-behind gets compiled into a single library. There are advantages and disadvantages to both, it really depends. It's also often a matter of opinion. A: Visual studio 2010 will show this option Even if your project is started as a Project(Not website). This may be an Error from VS 2010.
{ "language": "en", "url": "https://stackoverflow.com/questions/85513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: TileBrush for SIlverlight 2? As you may know, Silverlight does not have the TileBrush found in WPF. Is there a workaround to do tiling? A: According to contributor at Silverlight forum TileBrush in Silverlight (2 and 3) is only a placeholder class ready for future expansion and for WPF compatibility A PixelShader workaround is proposed for now, which description you can find here Someone please edit my post! :-) A: Well, it would appear that Silverlight does support the TileBrush, as referenced on MSDN: System.Windows.Media.TileBrush. It first appears in Silverlight 2.0 Beta 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/85517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PHP DOMDocument stripping HTML tags I'm working on a small templating engine, and I'm using DOMDocument to parse the pages. My test page so far looks like this: <block name="content"> <?php echo 'this is some rendered PHP! <br />' ?> <p>Main column of <span>content</span></p> </block> And part of my class looks like this: private function parse($tag, $attr = 'name') { $strict = 0; /*** the array to return ***/ $out = array(); if($this->totalBlocks() > 0) { /*** a new dom object ***/ $dom = new domDocument; /*** discard white space ***/ $dom->preserveWhiteSpace = false; /*** load the html into the object ***/ if($strict==1) { $dom->loadXML($this->file_contents); } else { $dom->loadHTML($this->file_contents); } /*** the tag by its tag name ***/ $content = $dom->getElementsByTagname($tag); $i = 0; foreach ($content as $item) { /*** add node value to the out array ***/ $out[$i]['name'] = $item->getAttribute($attr); $out[$i]['value'] = $item->nodeValue; $i++; } } return $out; } I have it working the way I want in that it grabs each <block> on the page and injects it's contents into my template, however, it is stripping the HTML tags within the <block>, thus returning the following without the <p> or <span> tags: this is some rendered PHP! Main column of content What am I doing wrong here? :) Thanks A: Nothing: nodeValue is the concatenation of the value portion of the tree, and will never have tags. What I would do to make an HTML fragment of the tree under $node is this: $doc = new DOMDocument(); foreach($node->childNodes as $child) { $doc->appendChild($doc->importNode($child, true)); } return $doc->saveHTML(); HTML "fragments" are actually more problematic than you'd think at first, because they tend to lack things like doctypes and character sets, which makes it hard to deterministically go back and forth between portions of a DOM tree and HTML fragments.
{ "language": "en", "url": "https://stackoverflow.com/questions/85520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Migrating from MySQL to arbitrary standards-compliant SQL2003 server Is there an incantation of mysqldump or a similar tool that will produce a piece of SQL2003 code to create and fill the same databases in an arbitrary SQL2003 compliant RDBMS? (The one I'm trying right now is MonetDB) A: DDL statements are inherently database-vendor specific. Although they have the same basic structure, each vendor has their own take on how to define types, indexes, constraints, etc. DML statements on the other hand are fairly portable. Therefore I suggest: * *Dump the database without any data (mysqldump --no-data) to get the schema *Make necessary changes to get the schema loaded on the other DB - these need to be done by hand (but some search/replace may be possible) *Dump the data with extended inserts off and no create table (--extended-insert=0 --no-create-info) *Run the resulting script against the other DB. This should do what you want. However, when porting an application to a different database vendor, many other things will be required; moving the schema and data is the easy bit. Checking for bugs introduced, different behaviour and performance testing is the hard bit. At the very least test every single query in your application for validity on the new database. Ideally do a lot more. A: This one is kind of tough. Unless you've got a very simple DB structure with vanilla types (varchar, integer, etc), you're probably going to get the best results writing a migration tool. In a language like Perl (via the DBI), this is pretty straight-forward. The program is basically an echo loop that reads from one database and inserts into the other. There are examples of this sort of code that Google knows about. Aside from the obvious problem of moving the data is the more subtle problem of how some datatypes are represented. For instance, MS SQL's datetime field is not in the same format as MySQL's. Other datatypes like BLOBs may have a different capacity in one RDBMs than in another. You should make sure that you understand the datatype definitions of the target DB system very well before porting. The last problem, of course, is getting application-level SQL statements to work against the new system. In my work, that's by far the hardest part. Date math seems especially DB-specific, while annoying things like quoting rules are a constant source of irritation. Good luck with your project. A: From SQL Server 2000 or 2005 you can have it generate scripts for your objects, but I am not sure how well they will transfer to other RDBMS. A: The generate script option is probably the easiest way to go. You'll undoubtedly have to do some search/replace on a few data types though.
{ "language": "en", "url": "https://stackoverflow.com/questions/85522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Faces Servlet threw exception java.lang.StackOverflowError Ok, I've run across my first StackOverflowError since joining this site, I figured this is a must post :-). My environment is Seam 2.0.1.GA, JBoss 4.2.2.GA and I'm using JSF. I am in the process of converting from a facelets view to JSP to take advantage of some existing JSP tags used on our existing site. I changed the faces-config.xml and the web.xml configuration files and started to receive the following error when trying to render a jsp page. Anyone have any thoughts? 2008-09-17 09:45:17,537 DEBUG [org.jboss.seam.contexts.FacesLifecycle] Begin JSF request for /form_home.jsp 2008-09-17 09:45:17,587 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception java.lang.StackOverflowError at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:210) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) at org.apache.catalina.core.ApplicationHttpRequest.getAttribute(ApplicationHttpRequest.java:222) ... My faces-config.xml file is now empty with no FaceletsViewHandler: <?xml version="1.0" encoding="UTF-8"?> <faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> </faces-config> And my Web.xml file: <?xml version="1.0"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Ajax4jsf --> <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>blueSky</param-value> </context-param> <!-- Seam --> <listener> <listener-class>org.jboss.seam.servlet.SeamListener</listener-class> </listener> <filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class> </filter> <filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern> </servlet-mapping> <!-- Seam end --> <!-- JSF --> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.jsp</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> A: I was able to figure out this problem. Apparently you can not configure web.xml to have the same param-value of .jsp for Javax.faces.DEFAULT_SUFFIX as the Faces Servlet url-pattern (*.jsp). If you change your url-pattern to .jspx or to /whateverdirnameyouwant/ the application starts up with no stack overflow errors. (note: the key is that DEFAULT_SUFFIX and Faces Servlet url-pattern cannot be the same regardless of what they are.) Hope this helps anyone else that experiences this specific problem. A: Stack overflows in java are almost always caused by infinite recursion / method calls. In your case given the stack trace, it appears 'getAttribute()' is being called repeatedly until crash. While I'm not intimately familiar with the particular environments you are using, I would suggest checking your .jsp code for any of this type of behaviour (for example two methods that call each other) A: So, I had a similar error. For me, it was that I had a JSF project and I was messing around with the file extensions. To start with, I had all my web files with extension .jsp. This was working, but then I wanted them to be all .jsf, then after that I went all in on using .xhtml. In the process, my web.xml file changed to accomodate xhtml and jsf. Changing the web.xml file was fine. What got me the StackOverflowError was that I had index.xhtml with a ui.include tag pointing to header.jsf. So I had a xhtml file pointing to a jsf file. I had thought that web.xml would be able to handle this, but it did not, I got the StackOverflowError. So, to fix this, now all my JSF files have extension .xhtml, and nested ui:include tags point to .xhtml files. On the flip side, though, the browser url can handle the index.jsp, index.jsf, index.xhtml just fine. So the web.xml (with servlet mappings for jsp, jsf and xhtml) handles the browser url just fine, but not for what my problem above highlighted.
{ "language": "en", "url": "https://stackoverflow.com/questions/85532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to make Swing scroll with "ensureIndexIsVisible"? When I run this code the selected item is not visible. I've already tried to run it in a separate thread with no luck. import javax.swing.JFrame; import java.awt.Container; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.JScrollPane; import java.awt.Dimension; public class ScrollList extends JFrame { int defaultValue; ScrollList() { Container cp = getContentPane(); JList list = createList(); defaultValue = 20; cp.add(createScrollPane(list)); pack(); setVisible(true); list.ensureIndexIsVisible(defaultValue); } JList createList() { Integer[] model = new Integer[73]; JList list = new JList(model); for (int i = 1; i < model.length; i++) model[i] = i; list.setSelectedIndex(defaultValue); return list; } JScrollPane createScrollPane(JList list) { JScrollPane s = new JScrollPane(createList()); s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); s.setPreferredSize(new Dimension(100, 200)); return s; } public static void main(String[] args) { new ScrollList(); } } A: I figured it out!! This is the code: import javax.swing.JFrame; import java.awt.Container; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.JScrollPane; import java.awt.Dimension; public class ScrollList extends JFrame { final int defaultValue = 20; ScrollList() { setDefaultCloseOperation(DISPOSE_ON_CLOSE); Container cp = getContentPane(); JList list = createList(); cp.add(createScrollPane(list)); pack(); list.ensureIndexIsVisible(list.getSelectedIndex()); setVisible(true); } JList createList() { Integer[] model = new Integer[73]; JList list = new JList(model); for (int i = 1; i < model.length; i++) model[i] = i; list.setSelectedIndex(defaultValue); return list; } JScrollPane createScrollPane(JList list) { JScrollPane s = new JScrollPane(list); // MAJOR FIX HERE! s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); s.setPreferredSize(new Dimension(100, 200)); return s; } public static void main(String[] args) { new ScrollList(); } } Instead of using the list that you passed into the createScrollPane() method, you create a new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/85548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When should I use a struct instead of a class? MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class? Some people might have forgotten that: * *structs can have methods. *structs cannot be inherited. I understand the technical differences between structs and classes, I just don't have a good feel for when to use a struct. A: It is an old topic, but wanted to provide a simple benchmark test. I have created two .cs files: public class TestClass { public long ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } and public struct TestStruct { public long ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } Run benchmark: * *Create 1 TestClass *Create 1 TestStruct *Create 100 TestClass *Create 100 TestStruct *Create 10000 TestClass *Create 10000 TestStruct Results: BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18362 Intel Core i5-8250U CPU 1.60GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores .NET Core SDK=3.1.101 [Host] : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT [AttachedDebugger] DefaultJob : .NET Core 3.1.1 (CoreCLR 4.700.19.60701, CoreFX 4.700.19.60801), X64 RyuJIT | Method | Mean | Error | StdDev | Ratio | RatioSD | Rank | Gen 0 | Gen 1 | Gen 2 | Allocated | |--------------- |---------------:|--------------:|--------------:|----------:|--------:|-----:|---------:|------:|------:|----------:| | UseStruct | 0.0000 ns | 0.0000 ns | 0.0000 ns | 0.000 | 0.00 | 1 | - | - | - | - | | UseClass | 8.1425 ns | 0.1873 ns | 0.1839 ns | 1.000 | 0.00 | 2 | 0.0127 | - | - | 40 B | | Use100Struct | 36.9359 ns | 0.4026 ns | 0.3569 ns | 4.548 | 0.12 | 3 | - | - | - | - | | Use100Class | 759.3495 ns | 14.8029 ns | 17.0471 ns | 93.144 | 3.24 | 4 | 1.2751 | - | - | 4000 B | | Use10000Struct | 3,002.1976 ns | 25.4853 ns | 22.5920 ns | 369.664 | 8.91 | 5 | - | - | - | - | | Use10000Class | 76,529.2751 ns | 1,570.9425 ns | 2,667.5795 ns | 9,440.182 | 346.76 | 6 | 127.4414 | - | - | 400000 B | A: I have always used a struct when I wanted to group together a few values for passing things back from a method call, but I won't need to use it for anything after I have read those values. Just as a way to keep things clean. I tend to view things in a struct as "throwaway" and things in a class as more useful and "functional" A: If an entity is going to be immutable, the question of whether to use a struct or a class will generally be one of performance rather than semantics. On a 32/64-bit system, class references require 4/8 bytes to store, regardless of the amount of information in the class; copying a class reference will require copying 4/8 bytes. On the other hand, every distinct class instance will have 8/16 bytes of overhead in addition to the information it holds and the memory cost of the references to it. Suppose one wants an array of 500 entities, each holding four 32-bit integers. If the entity is a structure type, the array will require 8,000 bytes regardless of whether all 500 entities are all identical, all different, or somewhere between. If the entity is a class type, the array of 500 references will take 4,000 bytes. If those references all point to different objects, the objects would require an additional 24 bytes each (12,000 bytes for all 500), a total of 16,000 bytes--twice the storage cost of a struct type. On the other hand, of the code created one object instance and then copied a reference to all 500 array slots, the total cost would be 24 bytes for that instance and 4,000 for the array--a total of 4,024 bytes. A major savings. Few situations would work out as well as the last one, but in some cases it may be possible to copy some references to enough array slots to make such sharing worthwhile. If the entity is supposed to be mutable, the question of whether to use a class or struct is in some ways easier. Assume "Thing" is either a struct or class which has an integer field called x, and one does the following code: Thing t1,t2; ... t2 = t1; t2.x = 5; Does one want the latter statement to affect t1.x? If Thing is a class type, t1 and t2 will be equivalent, meaning t1.x and t2.x will also be equivalent. Thus, the second statement will affect t1.x. If Thing is a structure type, t1 and t2 will be different instances, meaning t1.x and t2.x will refer to different integers. Thus, the second statement will not affect t1.x. Mutable structures and mutable classes have fundamentally different behaviors, though .net has some quirks in its handling of struct mutations. If one wants value-type behavior (meaning that "t2=t1" will copy the data from t1 to t2 while leaving t1 and t2 as distinct instances), and if one can live with the quirks in .net's handling of value types, use a structure. If one wants value-type semantics but .net's quirks would cause lead to broken value-type semantics in one's application, use a class and mumble. A: I am surprised I have not read at any of the previous answer this, which I consider the most crucial aspect : I use structs when I want a type with no identity. For example a 3D point: public struct ThreeDimensionalPoint { public readonly int X, Y, Z; public ThreeDimensionalPoint(int x, int y, int z) { this.X = x; this.Y = y; this.Z = z; } public override string ToString() { return "(X=" + this.X + ", Y=" + this.Y + ", Z=" + this.Z + ")"; } public override int GetHashCode() { return (this.X + 2) ^ (this.Y + 2) ^ (this.Z + 2); } public override bool Equals(object obj) { if (!(obj is ThreeDimensionalPoint)) return false; ThreeDimensionalPoint other = (ThreeDimensionalPoint)obj; return this == other; } public static bool operator ==(ThreeDimensionalPoint p1, ThreeDimensionalPoint p2) { return p1.X == p2.X && p1.Y == p2.Y && p1.Z == p2.Z; } public static bool operator !=(ThreeDimensionalPoint p1, ThreeDimensionalPoint p2) { return !(p1 == p2); } } If you have two instances of this struct you don't care if they are a single piece of data in memory or two. You just care about the value(s) they hold. A: In addition the the excellent answers above: Structures are value types. They can never be set to Nothing. Setting a structure = Nothing , will set all its values types to their default values. A: MSDN has the answer: Choosing Between Classes and Structures. Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria. Do not define a structure unless the type has all of the following characteristics: * *It logically represents a single value, similar to primitive types (integer, double, and so on). *It has an instance size smaller than 16 bytes. *It is immutable. *It will not have to be boxed frequently. A: Bill Wagner has a chapter about this in his book "effective c#" (http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660). He concludes by using the following principle: * *Is the main responsability of the type data storage? *Is its public interface defined entirely by properties that access or modify its data members? *Are you sure your type will never have subclasses? *Are you sure your type will never be treated polymorphically? If you answer 'yes' to all 4 questions: use a struct. Otherwise, use a class. A: when you don't really need behavior, but you need more structure than a simple array or dictionary. Follow up This is how I think of structs in general. I know they can have methods, but I like keeping that overall mental distinction. A: As @Simon said, structs provide "value-type" semantics so if you need similar behavior to a built-in data type, use a struct. Since structs are passed by copy you want to make sure they are small in size, about 16 bytes. A: Hmm... I wouldn't use garbage collection as an argument for/against the use of structs vs classes. The managed heap works much like a stack - creating an object just puts it at the top of the heap, which is almost as fast as allocating on the stack. Additionally, if an object is short-lived and does not survive a GC cycle, deallocation is free as the GC only works with memory that's still accessible. (Search MSDN, there's a series of articles on .NET memory management, I'm just too lazy to go dig for them). Most of the time I use a struct, I wind up kicking myself for doing so, because I later discover that having reference semantics would have made things a bit simpler. Anyway, those four points in the MSDN article posted above seems a good guideline. A: Structs are on the Stack not the Heap so therefore they are thread safe, and should be used when implementing the transfer object pattern, you never want to use objects on the Heap they are volatile, you want in this case to use the Call Stack, this is a basic case for using a struct I am surprised by all the way out answers here, A: ✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects. A: Use a class if: * *Its identity is important. Structures get copied implicitly when being passed by value into a method. *It will have a large memory footprint. *Its fields need initializers. *You need to inherit from a base class. *You need polymorphic behavior; Use a structure if: * *It will act like a primitive type (int, long, byte, etc.). *It must have a small memory footprint. *You are calling a P/Invoke method that requires a structure to be passed in by value. *You need to reduce the impact of garbage collection on application performance. *Its fields need to be initialized only to their default values. This value would be zero for numeric types, false for Boolean types, and null for reference types. * *Note that in C# 6.0 structs can have a default constructor that can be used to initialize the struct’s fields to nondefault values. *You do not need to inherit from a base class (other than ValueType, from which all structs inherit). *You do not need polymorphic behavior. A: Use a struct when you want value-type semantics instead of reference-type. Structs are copy-by-value so be careful! Also see previous questions, e.g. What's the difference between struct and class in .NET? A: I would use structs when: * *an object is supposed to be read only(every time you pass/assign a struct it gets copied). Read only objects are great when it comes to multithreaded processing as they don't requite locking in most cases. *an object is small and short-living. In such a case there is a good chance that the object will be allocated on the stack which is much more efficient than putting it on the managed heap. What is more the memory allocated by the object will be freed as soon as it goes outside its scope. In other words it's less work for Garbage Collector and the memory is used more efficient. A: I think the best answer is simply to use struct when what you need is a collection of properties, class when it's a collection of properties AND behaviors.
{ "language": "en", "url": "https://stackoverflow.com/questions/85553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "334" }
Q: VB.NET 2005 problems with Designer not being able to process a code line I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the "FitTrack"? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors... The error is: Warning 1 The designer cannot process the code at line 27: Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0 A: I would take out the static assignment in the designer to the resource CrystalReport11 and then add a load handler to your form and before setting the ReportSource back to CrystalReport11 do a check If(Not DesignMode) Then Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 Here is a mockup.. Public Sub New() InitializeComponent() AddHandler Me.Load, New EventHandler(AddressOf Form1_Load) End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) If (Not DesignMode) Then Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 End Sub A: I would back up the designer.cs file associated with it (like copy it to the desktop), then edit the designer.cs file and remove the offending lines (keeping track of what they do) and then I'd try to redo those lines via the design mode of that form. A: You should be able to take a backup, clear the lines that are having problems then when you re-open it the designer will fix the code. The key is that you want to let the designer re-generate, then just validate that all needed lines are there. That usually works for me, but you just have to be sure to remove all lines that it doesn't like. A: I do an easy way; Right Click on the report then choose Run Custom Tool. Automatically it fixes all problems and working for me, i solve 52 crystal ReportViewer errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/85559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .Net (dotNet) wrappers for OpenCV? I've seen there are a few of them. opencvdotnet, SharperCV, EmguCV, One on Code Project. Does anyone have any experience with any of these? I played around with the one on Code Project for a bit, but as soon as I tried to do anything complicated I got some nasty uncatchable exceptions (i.e. Msgbox exceptions). Cross platform (supports Mono) would be best. A: I started out with opencvdotnet but it's not really actively developed any more. Further, support for the feature I needed (facedetection) was patchy. I'm using EmguCV now: It wraps a much greater part of the API and the guy behind it is very responsive to suggestions and requests. The code is a joy to look at and is known to work on Mono. I've wrote up a quick getting-started guide on my blog. A: We use OpenCVSharp the google code website is in Japanese but it uses the latest OpenCV builds and impliments IDisposable throughout. It seems to provide more functioanlity than any of the others we have seen to date and is still active. It has quite extensive example programs as well. A: NuGetMustHaves has a good summary of packages on NuGet with their build dates and OpenCV revs. As of 1/24/2023: * *EmguCV is updated for OpenCVv 4.6.0.5131 *OpenCvSharp is updated for OpenCV v4.7.0.20230115 EmguCV and OpenCvSharp are the 2 packages with recent builds and appear to be the better choices going forward. Beware, EmguCV uses a dual GPL3/Commercial license (source) whereas OpenCVSharp uses the BSD 3-Clause License. In other words, OpenCVSharp is free for commercial use but EmguCV is not. EmguCV has superior documentation/examples/support and a bigger development team behind it, though, making the license worthwhile in many cases. It's worth considering what your future use cases are. If you're just looking to get running quickly using a managed language, the wrappers are fine. I started off that way. But as I got into more serious applications, I've found building a python/C++ application has better performance and more potential for reuse of code across platforms. A: I think best wrapper is opencvsharp http://code.google.com/p/opencvsharp/ A: I created a NuGet Package to make easy to start with OpenCv in C#, using EmguCV. Check it out! In Visual Studio search and add the myEmguCV.Net NuGet package. https://www.nuget.org/packages/myEmguCV.Net A: I think it's important to note that the original question was asked in 2008, and OpenCV 2.0 was released in 2009. The version 2.0 release introduced a C++ wrapper which is significantly easier to work with than the older C interface that the OP was confronted with. For my .NET project, I'm leaving all the graphic manipulation in native C++. Try this: create a C++/CLR DLL project which links to the OpenCV libraries. The OpenCV manual describes how to do this for a Windows C++ EXE, the same steps also work for a C++/CLR DLL. Then of course the DLL exports methods which are callable from a .NET EXE. To test it, you should be able to incorporate any of the OpenCV samples into your DLL with a little tweaking. (Add the .CPP file to your project, convert the main() function to a class member, etc. - you know the drill...) A good test candidate might be the "mat_mask_operations" sample. A: SharperCV was our tool of choice, and it doesn't let us down, for our robotics project. Even though it is currently marked as abandoned, the code is in really good shape, requires only minor tweaking to customize it for your need. No msgboxes, and actually very sane exception handling. Not cross-platform, though, due to the interoperability layer. A: I know this question has been answered for a long time, but I would like to add that there is a very good wrapper here. This is the new version of the openCV wrapper that you tried on code project. I've tried it for a couple of days and everything works perfect. Also, I got it working in minutes. I don't know for the compatibility with mono but under Visual Studio 2010, it works like a charm and saved me ton's of time and money (my project is commercial and most of the library are open source with licence that doesn't allow commercial utilisation unless publishing the code)
{ "language": "en", "url": "https://stackoverflow.com/questions/85569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: Search for host with MAC-address using Python I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas? A: You need ARP. Python's standard library doesn't include any code for that, so you either need to call an external program (your OS may have an 'arp' utility) or you need to build the packets yourself (possibly with a tool like Scapy. A: I don't think there is a built in way to get it from Python itself. My question is, how are you getting the IP information from your network? To get it from your local machine you could parse ifconfig (unix) or ipconfig (windows) with little difficulty. A: If you want a pure Python solution, you can take a look at Scapy to craft packets (you need to send ARP request, and inspect replies). Or if you don't mind invoking external program, you can use arping (on Un*x systems, I don't know of a Windows equivalent). A: It seems that there is not a native way of doing this with Python. Your best bet would be to parse the output of "ipconfig /all" on Windows, or "ifconfig" on Linux. Consider using os.popen() with some regexps. A: Depends on your platform. If you're using *nix, you can use the 'arp' command to look up the mac address for a given IP (assuming IPv4) address. If that doesn't work, you could ping the address and then look, or if you have access to the raw network (using BPF or some other mechanism), you could send your own ARP packets (but that is probably overkill). A: You would want to parse the output of 'arp', but the kernel ARP cache will only contain those IP address(es) if those hosts have communicated with the host where the Python script is running. ifconfig can be used to display the MAC addresses of local interfaces, but not those on the LAN. A: Mark Pilgrim describes how to do this on Windows for the current machine with the Netbios module here. You can get the Netbios module as part of the Win32 package available at python.org. Unfortunately at the moment I cannot find the docs on the module. A: as python was not meant to deal with OS-specific issues (it's supposed to be interpreted and cross platform), i would execute an external command to do so: in unix the command is ifconfig if you execute it as a pipe you get the desired result: import os myPipe = os.popen2("/sbin/ifconfig","a") print(myPipe[1].read())
{ "language": "en", "url": "https://stackoverflow.com/questions/85577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: FindControl() method throws ArithmeticException? I have a line of C# in my ASP.NET code behind that looks like this: DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before? A: If that's the stacktrace, its comingn from databinding, not from the line you posted. Is it possible that you have some really large data set? I've seen a 6000-page GridView overflow an Int16, although it seems pretty unlikely you'd actually overflow an Int32... Check to make sure you're passing in sane data into, say, the startpageIndex or pageSize of your datasource, for example. A: Are you 100% sure that's the line of code that's throwing the exception? I'm pretty certain that the FindControl method is not capable of throwing an ArithmeticException. Of course, I've been known to be wrong before... :) A: I have seen ArithmeticException being thrown in weird places before in C#/.NET and it was when I was working with p/invoke to an unmanaged .dll talking to an USB device. The crash was consistent, and always at the same place. Of course, the place was totally unrelated to the crash (i think it was a basic value assignment, like int i = 4 or something similarly silly) I'd like to have a happy ending to tell you, but I never managed to fully track down the problem. I strongly believe that the cause was in the unmanaged code, and that it somehow corrupted the memory or maybe even free'd managed memory. (Removing the calls to unmanaged code made the problem go away) The message I'm sending is: are you doing any calls to unmanaged code? If so, my suggestion is you focus your debugging skills there :)
{ "language": "en", "url": "https://stackoverflow.com/questions/85588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flush disk write cache from Windows CLI Does anyone know how to flush the disk write cache data from the cache manager for the current directory (or any given file or directory, for that matter), from a Windows command line? A: I found the SysInternals Sync worked well for me - although it flushes ALL cache, not just for the specific folder. Example of usage: IF EXIST Output RD /S /Q Output && Sync && MD Output By default it flushes all cached data for all drives - you can specify command-line options to restrict which drives but you cannot restrict it to just specific folders. Without it I would often get Access denied errors because the MD was trying to create a new folder while the system was still in the process of deleting the old one.
{ "language": "en", "url": "https://stackoverflow.com/questions/85595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How do I install modperl under OS X Leopard's default Apache 2? My attempts to install modperl under the default vanilla Leopard Apache 2 have failed and all I can find online are variations on this: I would like if possible not to rely on MacPorts or Fink, though if they can be made to work with the default Apache 2 install that would probably be ok. A: Macports has it (think apt-get and the likes on linux, but on OS X) (you can see it listed here) Haven't installed myself though.... A: Why not just give up and build/install your own or port versions of perl, apache2, and mod_perl2? Probably easier than fighting with it. (Worked for me.) (as per comment) Mmmkay! Sorry, I didn't intend that to be snarky or imply that it's not a valid question. I guess I'll delete this (if I can.) Would it be useful to edit the question to add your rational rationale for not having a separate installation? A: Get the latest mod_perl and set the following var: export ARCHFLAGS="-arch x86_64" Compile/install as usual. Taken from this post, "Building mod_perl2 on Leopard" which also links to further details on how to get Apache2::Request (libapreq) working as well. - (Not that I've been able to test it since I'm personally back on Tiger running Apache 1.3!) (And let's see if stackoverflow manages to lift this answer to the top since it is the only "correct" answer) A: I asked a very similar question a few days ago and got some good answers: "How do I use a vendor Apache with a self-compiled Perl and mod_perl?" A: The mc ports install of mod_perl tries to install apache 1.3 even if you specify just the mod perl, so thats not a good option. A: Try this: http://www.unibia.com/unibianet/node/32
{ "language": "en", "url": "https://stackoverflow.com/questions/85614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compile Cairo for Visual C++ 2008 (Express edition) Most precompiled Windows binaries are made with the MSYS+gcc toolchain. It uses MSVCRT runtime, which is incompatible with Visual C++ 2005/2008. So, how to go about and compile Cairo 1.6.4 (or later) for Visual C++ only. Including dependencies (png,zlib,pixman). A: These steps can build the latest cairo on 2015-11-15 for Visual Studio 2015 community. The debug build is DLL, linking to the DLL version of CRT. The release build is static library, linking to the static link version of CRT and requiring no DLLs. Install GnuWin The build scripts require GNU command line tools. The following steps are tested with GnuWin from Chocolatey. MSYS might also work. Download zlib128.zip, lpng1619.zip, cairo-1.14.4.tar.xz, pixman-0.32.8.tar.gz Extract Extract these archives and rename the directories: . (my_cairo_build_root) ├─cairo ├─libpng ├─pixman └─zlib zlib Do not build. The build script uses MSVCRT that clashes with Visual Studio 2015. Use the generated lib from libpng build. libpng Edit libpng\projects\vstudio\zlib.props: * *in <ZLibSrcDir> remove the version number: ..\..\..\..\zlib *in <WindowsSDKDesktopARMSupport> change true to false Open libpng\projects\vstudio\vstudio.sln in Visual Studio and confirm the upgrade. Use the default Debug configuration, and right click project libpng to build. Switch to Release Library configuration and right click project libpng to build. pixman Edit pixman\Makefile.win32.common: * *Replace CFG_CFLAGS = -MD -O2 with CFG_CFLAGS = -MT -O2 (linking to the static link version of CRT in release build) *Replace @mkdir with @"mkdir" (there are cmd's builtin mkdir and GnuWin's mkdir, the quotes force the latter to be used) Run Visual Studio x86 Native Command Prompt from start menu: cd /d my_cairo_build_root cd pixman\pixman make -f Makefile.win32 make -f Makefile.win32 CFG=debug cairo Edit cairo\build\Makefile.win32.common: * *Replace CFG_CFLAGS = -MD -O2 with CFG_CFLAGS = -MT -O2 *Replace CAIRO_LIBS += $(LIBPNG_PATH)/libpng.lib with CAIRO_LIBS += $(LIBPNG_PATH)/lib/$(CFG)/libpng16.lib. Now, copy the directory libpng\projects\vstudio\Debug into (created) libpng\lib\ and rename it to debug. Copy the directory libpng\projects\vstudio\Release Library into libpng\lib\ and rename it to release. *Replace CAIRO_LIBS += $(ZLIB_PATH)/zdll.lib with CAIRO_LIBS += $(LIBPNG_PATH)/lib/$(CFG)/zlib.lib *There are two @mkdir -p $(CFG)/`dirname $<` lines. Replace both of them with: @"mkdir" -p $(CFG)/$< @"rmdir" $(CFG)/$< Edit cairo\build\Makefile.win32.features-h: * *Replace all @echo with @"echo" There is an unusable link.exe in GnuWin. Rename C:\GnuWin\bin\link.exe to link_.exe to avoid clash. Run Visual Studio x86 Native Command Prompt from start menu: cd /d my_cairo_build_root cd cairo make -f Makefile.win32 CFG=debug make -f Makefile.win32 CFG=release The last two command will show "Built successfully!" but return error. Ignore them. Rename back C:\GnuWin\bin\link.exe. Configure Visual Studio Create a directory include and copy the following headers in: * *cairo\cairo-version.h (not cairo\src\cairo-version.h) *cairo\src\*.h, excluding cairo\src\cairo-version.h Add that directory to include path in Visual Studio. Add cairo\src\$(Configuration) and libpng\lib\$(Configuration) to library path. $(Configuration) will automatically expand to Debug or Release when building. Put cairo\src\debug\cairo.dll and libpng\lib\debug\libpng16.dll to one of Windows' PATH. Before #include <cairo.h>, setup the link options: #ifndef NDEBUG # pragma comment(lib, "cairo") #else #define CAIRO_WIN32_STATIC_BUILD # pragma comment(lib, "cairo-static") # pragma comment(lib, "libpng16") # pragma comment(lib, "zlib") #endif A: The instructions don't seem to work with current version of imlib, I wonder if it's worth reasking this question ? A: Here are instructions for building Cairo/Cairomm with Visual C++. Required: * *Visual C++ 2008 Express SP1 (now includes SDK) *MSYS 1.0 To use VC++ command line tools, a batch file 'vcvars32.bat' needs to be run. C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\vcvars32.bat ZLib Download (and extract) zlib123.zip from http://www.zlib.net/ cd zlib123 nmake /f win32/Makefile.msc dir # zlib.lib is the static library # # zdll.lib is the import library for zlib1.dll # zlib1.dll is the shared library libpng Download (and extract) lpng1231.zip from http://www.libpng.org/pub/png/libpng.html The VC++ 9.0 compiler gives loads of "this might be unsafe" warnings. Ignore them; this is MS security panic (the code is good). cd lpng1231\lpng1231 # for some reason this is two stories deep nmake /f ../../lpng1231.nmake ZLIB_PATH=../zlib123 dir # libpng.lib is the static library # # dll is not being created Pixman Pixman is part of Cairo, but a separate download. Download (and extract) pixman-0.12.0.tar.gz from http://www.cairographics.org/releases/ Use MSYS to untar via 'tar -xvzf pixman*.tar.gz' Both Pixman and Cairo have Makefiles for Visual C++ command line compiler (cl), but they use Gnu makefile and Unix-like tools (sed etc.). This means we have to run the make from within MSYS. Open a command prompt with VC++ command line tools enabled (try 'cl /?'). Turn that command prompt into an MSYS prompt by 'C:\MSYS\1.0\MSYS.BAT'. DO NOT use the MSYS icon, because then your prompt will now know of VC++. You cannot run .bat files from MSYS. Try that VC++ tools work from here: 'cl -?' Try that Gnu make also works: 'make -v'. Cool. cd (use /d/... instead of D:) cd pixman-0.12.0/pixman make -f Makefile.win32 This defaults to MMX and SSE2 optimizations, which require a newish x86 processor (Pentium 4 or Pentium M or above: http://fi.wikipedia.org/wiki/SSE2 ) There's quite some warnings but it seems to succeed. ls release # pixman-1.lib (static lib required by Cairo) Stay in the VC++ spiced MSYS prompt for also Cairo to compile. cairo Download (and extract) cairo-1.6.4.tar.gz from http://www.cairographics.org/releases/ cd cd cairo-1.6.4 The Makefile.win32 here is almost good, but has the Pixman path hardwired. Use the modified 'Makefile-cairo.win32': make -f ../Makefile-cairo.win32 CFG=release \ PIXMAN_PATH=../../pixman-0.12.0 \ LIBPNG_PATH=../../lpng1231 \ ZLIB_PATH=../../zlib123 (Write everything on one line, ignoring the backslashes) It says "no rule to make 'src/cairo-features.h'. Use the manually prepared one (in Cairo > 1.6.4 there may be a 'src/cairo-features-win32.h' that you can simply rename): cp ../cairo-features.h src/ Retry the make command (arrow up remembers it). ls src/release # # cairo-static.lib cairomm (C++ API) Download (and extract) cairomm-1.6.4.tar.gz from http://www.cairographics.org/releases/ There is a Visual C++ 2005 Project that we can use (via open & upgrade) for 2008. cairomm-1.6.4\MSCV_Net2005\cairomm\cairomm.vcproj Changes that need to be done: * *Change active configuration to "Release" *Cairomm-1.0 properties (with right click menu) C++/General/Additional Include Directories: ..\..\..\cairo-1.6.4\src (append to existing) Linker/General/Additional library directories: ..\..\..\cairo-1.6.4\src\release ..\..\..\lpng1231\lpng1231 ..\..\..\zlib123 Linker/Input/Additional dependencies: cairo-static.lib libpng.lib zlib.lib msimg32.lib * *Optimization: fast FPU code C++/Code generation/Floating point model Fast Right click on 'cairomm-1.0' and 'build'. There are some warnings. dir cairomm-1.6.4\MSVC_Net2005\cairomm\Release # # cairomm-1.0.lib # cairomm-1.0.dll # cairomm.def A: Did you check here: http://cairographics.org/visualstudio/ ? What do you mean 'It uses MSCVRT runtime, which is incompatible with Visual C++ 2005/2008' ? What are the exact problems you're having? A: I ran into two problems when building on Windows (Visual Studio 2008, GNU Make 3.81): * *Invalid "if" constructs in src/Makefile.sources. Fixed that using sed "s/^if \([A-Z_]*\)$/ifeq ($(\1), 1)/" src\Makefile.sources *_lround is not available on Windows/MSVC. Worked around that using sed "s/#define _cairo_lround lround/static inline long cairo_const _cairo_lround(double r) { return (long)floor(r + .5); }/"` (which is probably a poor fix) These issues aside, everything works great (for both x86 and x86_64 architectures). A: MSYS+gcc toolchain uses the old MSVCRT runtime library (now built into Windows) and Visual C++ 2005/2008 bring their own. It is a known fact that code should not depend on multiple runtimes. Passing things s.a. file handles, memory pointers etc. will be affected, and will cause apparently random crashes in such scenario. I have not been bitted by this. Then again, I don't really target Windows any more, either. But I've been told enough to not even try the solution. What could have worked, is linking all the dependencies statically into the lib (say, Cairomm). Static libs don't have a runtime bound to them, do they? But I did not try this. I actually got the VC++ building of all ingredients to work, but it took days. I hadn't found the URL you give. Strange in itself; I looked 'everywhere'. Then again, it is for Visual Studio 2003.NET, so two generations behind already. A: I have done this, but I don't have any ready-written instructions. My builds are also rather minimal as I haven't needed support for eg. PNG and SVG files, I just used it to render generated vector graphics to memory buffers. But what I did was read through the config.h and other files for the UNIX/GNU build system and write my own suited for MSVC, and then create a project with the appropriate source files. It probably takes a few hours at best to do this, but when you're done it just works ;) Edit: Do see this page, it has an MSVC 2003 (7.1) project for building cairo: http://slinavlee.googlepages.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/85622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Component to view and annotate PDF documents Can anyone recommend a good Windows form component for displaying PDF documents and allowing users to add real annotation (by which I mean identical to that created by Adobe Reader). Update: I've tried the AxAcroPDF component which Abobe installs alongside Reader, but this doesn't support annotation. I basically want AxAcroPDF combined with Reader's "Comment & Markup Toolbar". It seems that the Foxit SDK ActiveX supports this, so I'm going to try that. I just thought that there would be some more alternatives to choose from. A: There's also http://a.nnotate.com which you can use as a PDF / Word annotation component in web applications - just uses AJAX / JS / HTML and displays the pdfs properly in the browser without needing adobe reader. (see http://a.nnotate.com/embed-guide.html for a working demo) A: For editing the documents I have worked with SyncFusions Essential PDF and it worked quite well A: The free version Foxit Reader does this, you can do Tools->Commenting Tools->Note, then click anywhere on the page of the PDF to place a little note icon which has text inside. Then just save the PDF. Later, if someone views the PDF in Acrobat or Foxit, just hover the mouse over or click on the little note icons on the page to view the comments. A: If anyone's interested, it looks like we'll end up using jPDFNotes, from Qoppa Software. To quote from the web site: jPDFNotes is a Java™ bean that integrates into your application to display PDF documents and forms and allow your users to annotate the documents and fill the forms. After editing documents, the library can save them to a local file or the host application can override the save function to save the file to any location locally or on a network. jPDFNotes is built on top of Qoppa's proprietary PDF technology so your users do not have to install Acrobat Reader or any other third party software or drivers. jPDFNotes is 100% Java so it is completely platform independent and so can run on Windows, Linux, Unix, Mac OSX and any other platform that supports the Java runtime environment. It's not what we started looking for, but it seems to be exactly what we need. They seem a nice bunch of people too.
{ "language": "en", "url": "https://stackoverflow.com/questions/85624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Safely remove a USB drive using the Win32 API? How do I remove a USB drive using the Win32 API? I do a lot of work on embedded systems and on one of these I have to copy my programs on a USB stick and insert it into the target hardware. Since I mostly work on the console I don't like to use the mouse and click on the small task-bar icon hundred times a day. I'd love to write a little program to do exactly that so I can put it into my makefiles, but I haven't found any API call that does the same thing. Any ideas? A: It looks like Sync lets you specify -e to eject removable drives. While not a win32 API, you could probably just call sync -e [drive_letter] from your makefile. A: Here is a technet article about removable storage media. Look for DismountNtmsMedia. A: You can use the CM_Request_Device_Eject() function as well as some other possibilities. Consult the following projects and articles: DevEject: Straightforward. http://www.withopf.com/tools/deveject/ A useful CodeProject article: http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx A: Here's a solution in Delphi, that I've modified and put into a service for use in a very large enterprise. Go to: link text Look for "scapi (Setup & Config Manager API)", and download it. There will be a demo program called USBView that will get you on your way. If you have Delphi, this also includes a TUSBDeviceTree component that you can use to gather information about a USB device when. Regards A: #include<SetupAPI.h> #include <windows.h> #include<initguid.h> #include <newdev.h> #include <Cfgmgr32.h> #pragma comment(lib, "Cfgmgr32.lib") #pragma comment(lib, "Setupapi.lib") #pragma comment(lib, "Newdev.lib") int RemoveDevice(const GUID *guid, const wchar_t *hwID) { HDEVINFO m_hDevInfo; SP_DEVICE_INTERFACE_DATA spdid; SP_DEVINFO_DATA spdd; DWORD dwSize; BYTE Buf[1024]; PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd = (PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf; printf("try to remove device::%ws\n", hwID); m_hDevInfo = SetupDiGetClassDevs(guid, NULL, NULL, DIGCF_PRESENT| DIGCF_DEVICEINTERFACE); if (m_hDevInfo == INVALID_HANDLE_VALUE) { printf("GetClassDevs Failed!\n"); return 0; } spdid.cbSize = sizeof(spdid); for (int i = 0; SetupDiEnumDeviceInterfaces(m_hDevInfo, NULL, guid, i, &spdid); i++) { dwSize = 0; SetupDiGetDeviceInterfaceDetail(m_hDevInfo, &spdid, NULL, 0, &dwSize, NULL); if (dwSize != 0 && dwSize <= sizeof(Buf)) { pspdidd->cbSize = sizeof(*pspdidd); // 5 Bytes! ZeroMemory((PVOID)&spdd, sizeof(spdd)); spdd.cbSize = sizeof(spdd); long res = SetupDiGetDeviceInterfaceDetail(m_hDevInfo, & spdid, pspdidd, dwSize, &dwSize, &spdd); if (res) { OLECHAR* guidString; OLECHAR* guidString2; StringFromCLSID(&spdd.ClassGuid, &guidString); StringFromCLSID(&spdid.InterfaceClassGuid, &guidString2); printf("%d, %ws, %ws, %ws\n", spdd.DevInst, pspdidd->DevicePath, guidString, guidString2); CoTaskMemFree(guidString); CoTaskMemFree(guidString2); if (!memcmp(pspdidd->DevicePath, hwID, 2 * lstrlenW(hwID))) { DEVINST DevInstParent = 0; res = CM_Get_Parent(&DevInstParent, spdd.DevInst, 0); for (long tries = 0; tries < 10; tries++) { // sometimes we need some tries... WCHAR VetoNameW[MAX_PATH]; PNP_VETO_TYPE VetoType = PNP_VetoTypeUnknown; VetoNameW[0] = 0; res = CM_Request_Device_EjectW(DevInstParent, &VetoType, VetoNameW, MAX_PATH, 0); if ((res == CR_SUCCESS && VetoType == PNP_VetoTypeUnknown)) { printf("remove %ws success!\n", pspdidd->DevicePath); SetupDiDestroyDeviceInfoList(m_hDevInfo); return 1; } Sleep(500); // required to give the next tries a chance! } break; } } } } printf("Remove Device Failed!\n"); SetupDiDestroyDeviceInfoList(m_hDevInfo); return 0; } int main(){ GUID GUID_DEVINTERFACE_USB_HUB; CLSIDFromString(L"F18A0E88-C30C-11D0-8815-00A0C906BED8", &GUID_DEVINTERFACE_USB_HUB); RemoveDevice(&GUID_DEVINTERFACE_USB_HUB, L"\\\\?\\usb#root_hub30"); return 0; } refrences: How to Prepare a USB Drive for Safe Removal GUID_DEVINTERFACE
{ "language": "en", "url": "https://stackoverflow.com/questions/85649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How do I compare two CLOB values in Oracle I have two tables I would like to complare. One of the columns is type CLOB. I would like to do something like this: select key, clob_value source_table minus select key, clob_value target_table Unfortunately, Oracle can't perform minus operations on clobs. How can I do this? A: Can you access the data via a built in package? If so then perhaps you could write a function that returned a string representation of the data (eg some sort of hash on the data), then you could do select key, to_hash_str_val(glob_value) from source_table minus select key, to_hash_str_val(glob_value) from target_table A: The format is this: dbms_lob.compare( lob_1 IN BLOB, lob_2 IN BLOB, amount IN INTEGER := 18446744073709551615, offset_1 IN INTEGER := 1, offset_2 IN INTEGER := 1) RETURN INTEGER; If dbms_lob.compare(lob1, lob2) = 0, they are identical. Here's an example query based on your example: Select key, glob_value From source_table Left Join target_table On source_table.key = target_table.key Where target_table.glob_value is Null Or dbms_lob.compare(source_table.glob_value, target_table.glob_value) <> 0
{ "language": "en", "url": "https://stackoverflow.com/questions/85675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What's the best way to model recurring events in a calendar application? I'm building a group calendar application that needs to support recurring events, but all the solutions I've come up with to handle these events seem like a hack. I can limit how far ahead one can look, and then generate all the events at once. Or I can store the events as repeating and dynamically display them when one looks ahead on the calendar, but I'll have to convert them to a normal event if someone wants to change the details on a particular instance of the event. I'm sure there's a better way to do this, but I haven't found it yet. What's the best way to model recurring events, where you can change details of or delete particular event instances? (I'm using Ruby, but please don't let that constrain your answer. If there's a Ruby-specific library or something, though, that's good to know.) A: I'm using the database schema as described below to store the recurrence parameters http://github.com/bakineggs/recurring_events_for Then I use runt to dynamically calculate the dates. https://github.com/mlipper/runt A: I have developed multiple calendar-based applications, and also authored a set of reusable JavaScript calendar components that support recurrence. I wrote up an overview of how to design for recurrence that might be helpful to someone. While there are a few bits that are specific to the library I wrote, the vast majority of the advice offered is general to any calendar implementation. Some of the key points: * *Store recurrence using the iCal RRULE format -- that's one wheel you really don't want to reinvent *Do NOT store individual recurring event instances as rows in your database! Always store a recurrence pattern. *There are many ways to design your event/exception schema, but a basic starting point example is provided *All date/time values should be stored in UTC and converted to local for display *The end date stored for a recurring event should always be the end date of the recurrence range (or your platform's "max date" if recurring "forever") and the event duration should be stored separately. This is to ensure a sane way of querying for events later. Read the linked article for more details about this. *Some discussion around generating event instances and recurrence editing strategies is included It's a really complicated topic with many, many valid approaches to implementing it. I will say that I've actually implemented recurrence several times successfully, and I would be wary of taking advice on this subject from anyone who hasn't actually done it. A: * *Keep track of a recurrence rule (probably based on iCalendar, per @Kris K.). This will include a pattern and a range (Every third Tuesday, for 10 occurrences). *For when you want to edit/delete a specific occurrence, keep track of exception dates for the above recurrence rule (dates where the event doesn't occur as the rule specifies). *If you deleted, that's all you need, if you edited, create another event, and give it a parent ID set to the main event. You can choose whether to include all of the main event's information in this record, or if it only holds the changes and inherits everything that doesn't change. Note that if you allow recurrence rules that don't end, you have to think about how to display your now infinite amount of information. Hope that helps! A: I'd recommend using the power of the date library and the semantics of the range module of ruby. A recurring event is really a time, a date range (a start & end) and usually a single day of the week. Using date & range you can answer any question: #!/usr/bin/ruby require 'date' start_date = Date.parse('2008-01-01') end_date = Date.parse('2008-04-01') wday = 5 # friday (start_date..end_date).select{|d| d.wday == wday}.map{|d| d.to_s}.inspect Produces all days of the event, including the leap year! # =>"[\"2008-01-04\", \"2008-01-11\", \"2008-01-18\", \"2008-01-25\", \"2008-02-01\", \"2008-02-08\", \"2008-02-15\", \"2008-02-22\", \"2008-02-29\", \"2008-03-07\", \"2008-03-14\", \"2008-03-21\", \"2008-03-28\"]" A: There can be many problems with recurring events, let me highlight a few that I know of. Solution 1 - no instances Store original appointment + recurrence data, do not store all the instances. Problems: * *You'll have to calculate all the instances in a date window when you need them, costly *Unable to handle exceptions (ie. you delete one of the instances, or move it, or rather, you can't do this with this solution) Solution 2 - store instances Store everything from 1, but also all the instances, linked back to the original appointment. Problems: * *Takes a lot of space (but space is cheap, so minor) *Exceptions must be handled gracefully, especially if you go back and edit the original appointment after making an exception. For instance, if you move the third instance one day forward, what if you go back and edit the time of the original appointment, re-insert another on the original day and leave the moved one? Unlink the moved one? Try to change the moved one appropriately? Of course, if you're not going to do exceptions, then either solution should be fine, and you basically choose from a time/space trade off scenario. A: From these answers, I've sort of sifted out a solution. I really like the idea of the link concept. Recurring events could be a linked list, with the tail knowing its recurrence rule. Changing one event would then be easy, because the links stay in place, and deleting an event is easy as well - you just unlink an event, delete it, and re-link the event before and after it. You still have to query recurring events every time someone looks at a new time period never been looked at before on the calendar, but otherwise this is pretty clean. A: You may want to look at iCalendar software implementations or the standard itself (RFC 2445 RFC 5545). Ones to come to mind quickly are the Mozilla projects http://www.mozilla.org/projects/calendar/ A quick search reveals http://icalendar.rubyforge.org/ as well. Other options can be considered depending on how you're going to store the events. Are you building your own database schema? Using something iCalendar-based, etc.? A: You could store the events as repeating, and if a particular instance was edited, create a new event with the same event ID. Then when looking up the event, search for all events with the same event ID to get all the information. I'm not sure if you rolled your own event library, or if you're using an existing one so it may not be possible. A: Check the article below for three good ruby date/time libraries. ice_cube in particular seems a solid choice for recurrence rules and other stuff that an event calendar would need. http://www.rubyinside.com/3-new-date-and-time-libraries-for-rubyists-3238.html A: I'm working with the following: * *http://github.com/elevation/event_calendar - model and helper for a calendar *http://github.com/seejohnrun/ice_cube - awesome recurring gem *http://github.com/justinfrench/formtastic - easy forms and a gem in progress that extends formtastic with an input type :recurring (form.schedule :as => :recurring), which renders an iCal-like interface and a before_filter to serialize the view into an IceCube object again, ghetto-ly. My idea is to make it incredibility easy to add recurring attributes to a model and connect it easily in the view. All in a couple of lines. So what does this give me? Indexed, Edit-able, Recurring attributes. events stores a single day instance, and is used in the calendar view/helper say task.schedule stores the yaml'd IceCube object, so you can do calls like : task.schedule.next_suggestion. Recap: I use two models, one flat, for the calendar display, and one attribute'd for the functionality. A: I would use a 'link' concept for all future recurring events. They are dynamically displayed in the calendar and link back to a single reference object. When events have taken place the link is broken and the event becomes a standalone instance. If you attempt to edit a recurring event then prompt to change all future items (i.e. change single linked reference) or change just that instance (in which case convert this to a standalone instance and then make change). The latter cased is slightly problematic as you need to keep track in your recurring list of all future events that were converted to single instance. But, this is entirely do-able. So, in essence, have 2 classes of events - single instances and recurring events. A: In javascript: Handling recurring schedules: http://bunkat.github.io/later/ Handling complex events and dependencies between those schedules: http://bunkat.github.io/schedule/ Basically, you create the rules then you ask the lib to compute the next N recurring events (specifying a date range or not). The rules can be parsed / serialised for saving them into your model. If you have a recurring event and would like to modify only one recurrence you can use the except() function to dismiss a particular day and then add a new modified event for this entry. The lib supports very complex patterns, timezones and even croning events. A: Store the events as repeating and dynamically display them, however allow the recurring event to contain a list of specific events that could override the default information on a specific day. When you query the recurring event it can check for a specific override for that day. If a user makes changes, then you can ask if he wants to update for all instances (default details) or just that day (make a new specific event and add it to the list). If a user asks to delete all recurrences of this event you also have the list of specifics to hand and can remove them easily. The only problematic case would be if the user wants to update this event and all future events. In which case you'll have to split the recurring event into two. At this point you may want to consider linking recurring events in some way so you can delete them all. A: For .NET programmers who are prepared to pay some licensing fees, you might find Aspose.Network useful... it includes an iCalendar compatible library for recurring appointments. A: You store the events in iCalendar format directly, which allows for open-ended repetition, time-zone localisation and so forth. You could store these in a CalDAV server and then when you want to display the events you can use the option of the report defined in CalDAV to ask the server to do the expansion of the recurring events across the viewed period. Or you could store them in a database yourself and use some kind of iCalendar parsing library to do the expansion, without needing the PUT/GET/REPORT to talk to a backend CalDAV server. This is probably more work - I'm sure CalDAV servers hide complexity somewhere. Having the events in iCalendar format will probably make things simpler in the long run as people will always want them to be exported for putting in other software anyway. A: I have Simply implemented this feature! Logic is as follows, first you need two tables. RuleTable store general or recycle paternal events. ItemTable is stored cycle events. For example, when you create a cyclic event, the start time for 6 November 2015, the end time for the December 6 (or forever), cycle for one week. You insert data into a RuleTable, fields are as follows: TableID: 1 Name: cycleA StartTime: 6 November 2014 (I kept thenumber of milliseconds), EndTime: 6 November 2015 (if it is repeated forever, and you can keep the value -1) Cycletype: WeekLy. Now you want to query November 20 to December 20 data. You can write a function RecurringEventBE (long start, long end), based on the starting and ending time, WeekLy, you can calculate the collection you want, < cycleA11.20, cycleA 11.27, cycleA 12.4 ......>. In addition to November 6, and the rest I called him a virtual event. When the user changes a virtual event' name after (cycleA11.27 for example), you insert a data into a ItemTable. Fields are as follows: TableID: 1 Name, cycleB StartTime, 27 November 2014 EndTime,November 6 2015 Cycletype, WeekLy Foreignkey, 1 (pointingto the table recycle paternal events). In function RecurringEventBE (long start, long end), you use this data covering virtual event (cycleB11.27) sorry about my english, I tried. This is my RecurringEventBE: public static List<Map<String, Object>> recurringData(Context context, long start, long end) { // 重复事件的模板处理,生成虚拟事件(根据日期段) long a = System.currentTimeMillis(); List<Map<String, Object>> finalDataList = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> tDataList = BillsDao.selectTemplateBillRuleByBE(context); //RuleTable,just select recurringEvent for (Map<String, Object> iMap : tDataList) { int _id = (Integer) iMap.get("_id"); long bk_billDuedate = (Long) iMap.get("ep_billDueDate"); // 相当于事件的开始日期 Start long bk_billEndDate = (Long) iMap.get("ep_billEndDate"); // 重复事件的截止日期 End int bk_billRepeatType = (Integer) iMap.get("ep_recurringType"); // recurring Type long startDate = 0; // 进一步精确判断日记起止点,保证了该段时间断获取的数据不未空,减少不必要的处理 long endDate = 0; if (bk_billEndDate == -1) { // 永远重复事件的处理 if (end >= bk_billDuedate) { endDate = end; startDate = (bk_billDuedate <= start) ? start : bk_billDuedate; // 进一步判断日记起止点,这样就保证了该段时间断获取的数据不未空 } } else { if (start <= bk_billEndDate && end >= bk_billDuedate) { // 首先判断起止时间是否落在重复区间,表示该段时间有重复事件 endDate = (bk_billEndDate >= end) ? end : bk_billEndDate; startDate = (bk_billDuedate <= start) ? start : bk_billDuedate; // 进一步判断日记起止点,这样就保证了该段时间断获取的数据不未空 } } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(bk_billDuedate); // 设置重复的开始日期 long virtualLong = bk_billDuedate; // 虚拟时间,后面根据规则累加计算 List<Map<String, Object>> virtualDataList = new ArrayList<Map<String, Object>>();// 虚拟事件 if (virtualLong == startDate) { // 所要求的时间,小于等于父本时间,说明这个是父事件数据,即第一条父本数据 Map<String, Object> bMap = new HashMap<String, Object>(); bMap.putAll(iMap); bMap.put("indexflag", 1); // 1表示父本事件 virtualDataList.add(bMap); } long before_times = 0; // 计算从要求时间start到重复开始时间的次数,用于定位第一次发生在请求时间段落的时间点 long remainder = -1; if (bk_billRepeatType == 1) { before_times = (startDate - bk_billDuedate) / (7 * DAYMILLIS); remainder = (startDate - bk_billDuedate) % (7 * DAYMILLIS); } else if (bk_billRepeatType == 2) { before_times = (startDate - bk_billDuedate) / (14 * DAYMILLIS); remainder = (startDate - bk_billDuedate) % (14 * DAYMILLIS); } else if (bk_billRepeatType == 3) { before_times = (startDate - bk_billDuedate) / (28 * DAYMILLIS); remainder = (startDate - bk_billDuedate) % (28 * DAYMILLIS); } else if (bk_billRepeatType == 4) { before_times = (startDate - bk_billDuedate) / (15 * DAYMILLIS); remainder = (startDate - bk_billDuedate) % (15 * DAYMILLIS); } else if (bk_billRepeatType == 5) { do { // 该段代码根据日历处理每天重复事件,当事件比较多的时候效率比较低 Calendar calendarCloneCalendar = (Calendar) calendar .clone(); int currentMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); calendarCloneCalendar.add(Calendar.MONTH, 1); int nextMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); if (currentMonthDay > nextMonthDay) { calendar.add(Calendar.MONTH, 1 + 1); virtualLong = calendar.getTimeInMillis(); } else { calendar.add(Calendar.MONTH, 1); virtualLong = calendar.getTimeInMillis(); } } while (virtualLong < startDate); } else if (bk_billRepeatType == 6) { do { // 该段代码根据日历处理每天重复事件,当事件比较多的时候效率比较低 Calendar calendarCloneCalendar = (Calendar) calendar .clone(); int currentMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); calendarCloneCalendar.add(Calendar.MONTH, 2); int nextMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); if (currentMonthDay > nextMonthDay) { calendar.add(Calendar.MONTH, 2 + 2); virtualLong = calendar.getTimeInMillis(); } else { calendar.add(Calendar.MONTH, 2); virtualLong = calendar.getTimeInMillis(); } } while (virtualLong < startDate); } else if (bk_billRepeatType == 7) { do { // 该段代码根据日历处理每天重复事件,当事件比较多的时候效率比较低 Calendar calendarCloneCalendar = (Calendar) calendar .clone(); int currentMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); calendarCloneCalendar.add(Calendar.MONTH, 3); int nextMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); if (currentMonthDay > nextMonthDay) { calendar.add(Calendar.MONTH, 3 + 3); virtualLong = calendar.getTimeInMillis(); } else { calendar.add(Calendar.MONTH, 3); virtualLong = calendar.getTimeInMillis(); } } while (virtualLong < startDate); } else if (bk_billRepeatType == 8) { do { calendar.add(Calendar.YEAR, 1); virtualLong = calendar.getTimeInMillis(); } while (virtualLong < startDate); } if (remainder == 0 && virtualLong != startDate) { // 当整除的时候,说明当月的第一天也是虚拟事件,判断排除为父本,然后添加。不处理,一个月第一天事件会丢失 before_times = before_times - 1; } if (bk_billRepeatType == 1) { // 单独处理天事件,计算出第一次出现在时间段的事件时间 virtualLong = bk_billDuedate + (before_times + 1) * 7 * (DAYMILLIS); calendar.setTimeInMillis(virtualLong); } else if (bk_billRepeatType == 2) { virtualLong = bk_billDuedate + (before_times + 1) * (2 * 7) * DAYMILLIS; calendar.setTimeInMillis(virtualLong); } else if (bk_billRepeatType == 3) { virtualLong = bk_billDuedate + (before_times + 1) * (4 * 7) * DAYMILLIS; calendar.setTimeInMillis(virtualLong); } else if (bk_billRepeatType == 4) { virtualLong = bk_billDuedate + (before_times + 1) * (15) * DAYMILLIS; calendar.setTimeInMillis(virtualLong); } while (startDate <= virtualLong && virtualLong <= endDate) { // 插入虚拟事件 Map<String, Object> bMap = new HashMap<String, Object>(); bMap.putAll(iMap); bMap.put("ep_billDueDate", virtualLong); bMap.put("indexflag", 2); // 2表示虚拟事件 virtualDataList.add(bMap); if (bk_billRepeatType == 1) { calendar.add(Calendar.DAY_OF_MONTH, 7); } else if (bk_billRepeatType == 2) { calendar.add(Calendar.DAY_OF_MONTH, 2 * 7); } else if (bk_billRepeatType == 3) { calendar.add(Calendar.DAY_OF_MONTH, 4 * 7); } else if (bk_billRepeatType == 4) { calendar.add(Calendar.DAY_OF_MONTH, 15); } else if (bk_billRepeatType == 5) { Calendar calendarCloneCalendar = (Calendar) calendar .clone(); int currentMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); calendarCloneCalendar.add(Calendar.MONTH, 1); int nextMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); if (currentMonthDay > nextMonthDay) { calendar.add(Calendar.MONTH, 1 + 1); } else { calendar.add(Calendar.MONTH, 1); } }else if (bk_billRepeatType == 6) { Calendar calendarCloneCalendar = (Calendar) calendar .clone(); int currentMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); calendarCloneCalendar.add(Calendar.MONTH, 2); int nextMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); if (currentMonthDay > nextMonthDay) { calendar.add(Calendar.MONTH, 2 + 2); } else { calendar.add(Calendar.MONTH, 2); } }else if (bk_billRepeatType == 7) { Calendar calendarCloneCalendar = (Calendar) calendar .clone(); int currentMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); calendarCloneCalendar.add(Calendar.MONTH, 3); int nextMonthDay = calendarCloneCalendar .get(Calendar.DAY_OF_MONTH); if (currentMonthDay > nextMonthDay) { calendar.add(Calendar.MONTH, 3 + 3); } else { calendar.add(Calendar.MONTH, 3); } } else if (bk_billRepeatType == 8) { calendar.add(Calendar.YEAR, 1); } virtualLong = calendar.getTimeInMillis(); } finalDataList.addAll(virtualDataList); }// 遍历模板结束,产生结果为一个父本加若干虚事件的list /* * 开始处理重复特例事件特例事件,并且来时合并 */ List<Map<String, Object>>oDataList = BillsDao.selectBillItemByBE(context, start, end); Log.v("mtest", "特例结果大小" +oDataList ); List<Map<String, Object>> delectDataListf = new ArrayList<Map<String, Object>>(); // finalDataList要删除的结果 List<Map<String, Object>> delectDataListO = new ArrayList<Map<String, Object>>(); // oDataList要删除的结果 for (Map<String, Object> fMap : finalDataList) { // 遍历虚拟事件 int pbill_id = (Integer) fMap.get("_id"); long pdue_date = (Long) fMap.get("ep_billDueDate"); for (Map<String, Object> oMap : oDataList) { int cbill_id = (Integer) oMap.get("billItemHasBillRule"); long cdue_date = (Long) oMap.get("ep_billDueDate"); int bk_billsDelete = (Integer) oMap.get("ep_billisDelete"); if (cbill_id == pbill_id) { if (bk_billsDelete == 2) {// 改变了duedate的特殊事件 long old_due = (Long) oMap.get("ep_billItemDueDateNew"); if (old_due == pdue_date) { delectDataListf.add(fMap);//该改变事件在时间范围内,保留oMap } } else if (bk_billsDelete == 1) { if (cdue_date == pdue_date) { delectDataListf.add(fMap); delectDataListO.add(oMap); } } else { if (cdue_date == pdue_date) { delectDataListf.add(fMap); } } } }// 遍历特例事件结束 }// 遍历虚拟事件结束 // Log.v("mtest", "delectDataListf的大小"+delectDataListf.size()); // Log.v("mtest", "delectDataListO的大小"+delectDataListO.size()); finalDataList.removeAll(delectDataListf); oDataList.removeAll(delectDataListO); finalDataList.addAll(oDataList); List<Map<String, Object>> mOrdinaryList = BillsDao.selectOrdinaryBillRuleByBE(context, start, end); finalDataList.addAll(mOrdinaryList); // Log.v("mtest", "finalDataList的大小"+finalDataList.size()); long b = System.currentTimeMillis(); Log.v("mtest", "算法耗时"+(b-a)); return finalDataList; } A: What if you have a recurring appointment with no end date? As cheap as space is, you don't have infinite space, so Solution 2 is a non-starter there... May I suggest that "no end date" can be resolved to an end date at the end of the century. Even for a dayly event the amount of space remains cheap.
{ "language": "en", "url": "https://stackoverflow.com/questions/85699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "248" }
Q: Best way to extract TimeZone object from a String? I have a database field that contains a raw date field (stored as character data), such as Friday, September 26, 2008 8:30 PM Eastern Daylight Time I can parse this as a Date easily, with SimpleDateFormat DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); Date scheduledDate = dbFormatter.parse(rawDate); What I'd like to do is extract a TimeZone object from this string. The default TimeZone in the JVM that this application runs in is GMT, so I can't use .getTimezoneOffset() from the Date parsed above (because it will return the default TimeZone). Besides tokenizing the raw string and finding the start position of the Timezone string (since I know the format will always be EEEE, MMMM dd, yyyy hh:mm aa zzzz) is there a way using the DateFormat/SimpleDateFormat/Date/Calendar API to extract a TimeZone object - which will have the same TimeZone as the String I've parsed apart with DateFormat.parse()? One thing that bugs me about Date vs Calendar in the Java API is that Calendar is supposed to replace Date in all places... but then they decided, oh hey let's still use Date's in the DateFormat classes. A: I found that the following: DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago")); Date scheduledDate = dbFormatter.parse("Friday, September 26, 2008 8:30 PM Eastern Daylight Time"); System.out.println(scheduledDate); System.out.println(dbFormatter.format(scheduledDate)); TimeZone tz = dbFormatter.getTimeZone(); System.out.println(tz.getDisplayName()); dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago")); System.out.println(dbFormatter.format(scheduledDate)); Produces the following: Fri Sep 26 20:30:00 CDT 2008 Friday, September 26, 2008 08:30 PM Eastern Standard Time Eastern Standard Time Friday, September 26, 2008 08:30 PM Central Daylight Time I actually found this to be somewhat surprising. But, I guess that shows that the answer to your question is to simply call getTimeZone on the formatter after you've parsed. Edit: The above was run with Sun's JDK 1.6. A: @Ed Thomas: I've tried something very similar to your example and I get very different results: String testString = "Friday, September 26, 2008 8:30 PM Pacific Standard Time"; DateFormat df = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); System.out.println("The default TimeZone is: " + TimeZone.getDefault().getDisplayName()); System.out.println("DateFormat timezone before parse: " + df.getTimeZone().getDisplayName()); Date date = df.parse(testString); System.out.println("Parsed [" + testString + "] to Date: " + date); System.out.println("DateFormat timezone after parse: " + df.getTimeZone().getDisplayName()); Output: The default TimeZone is: Eastern Standard Time DateFormat timezone before parse: Eastern Standard Time Parsed [Friday, September 26, 2008 8:30 PM Pacific Standard Time] to Date: Sat Sep 27 00:30:00 EDT 2008 DateFormat timezone after parse: Eastern Standard Time Seems like DateFormat.getTimeZone() returns the same TimeZone before and after the parse()... even if I throw in an explicit setTimeZone() before calling parse(). Looking at the source for DateFormat and SimpleDateFormat, seems like getTimeZone() just returns the TimeZone of the underlying Calendar... which will default to the Calendar of the default Locale/TimeZone unless you specify a certain one to use. A: I recommend checking out the Joda Time date and time API. I have recently been converted to a believer in it as it tends to be highly superior to the built-in support for dates and times in Java. In particular, you should check out the DateTimeZone class. Hope this helps. http://joda-time.sourceforge.net/ http://joda-time.sourceforge.net/api-release/index.html A: tl;dr ZonedDateTime.parse( "Friday, September 26, 2008 8:30 PM Eastern Daylight Time" , DateTimeFormatter.ofPattern( "EEEE, MMMM d, uuuu h:m a zzzz" ) ).getZone() java.time The modern way is with the java.time classes. The Question and other Answers use the troublesome old legacy date-time classes or the the Joda-Time project, both of which are now supplanted by the java.time classes. Define a DateTimeFormatter object with a formatting pattern to match your data. DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEEE, MMMM d, uuuu h:m a zzzz" ); Assign a Locale to specify the human language of the name-of-day and name of month, as well as the cultural norms for other formatting issues. f = f.withLocale( Locale.US ); Lastly, do the parsing to get a ZonedDateTime object. String input = "Friday, September 26, 2008 8:30 PM Eastern Daylight Time" ; ZonedDateTime zdt = ZonedDateTime.parse( input , f ); zdt.toString(): 2008-09-26T20:30-04:00[America/New_York] You can ask for the time zone from the ZonedDateTime, represented as a ZoneId object. You can then interrogate the ZoneId if you need more info about the time zone. ZoneId z = zdt.getZone(); See for yourself in IdeOne.com. ISO 8601 Avoid exchanging date-time data in this kind of terrible format. Do not assume English, do not accessorize your output with things like the name-of-day, and never use pseudo-time-zones such as Eastern Daylight Time. For time zones: Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). For serializing date-time values to text, use only the ISO 8601 formats. The java.time classes use these formats by default when parsing/generating strings to represent their value. About java.time The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat. The Joda-Time project, now in maintenance mode, advises migration to java.time. To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310. Where to obtain the java.time classes? * *Java SE 8 and SE 9 and later * *Built-in. *Part of the standard Java API with a bundled implementation. *Java 9 adds some minor features and fixes. *Java SE 6 and SE 7 * *Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport. *Android * *The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically. *See How to use…. The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more. A: Well as a partial solution you could use a RegEx match to get the timezone since you will always have the same text before it. AM or PM. I don't know enough about Java timezones to get you the last part of it. A: The main difference between Date and Calendar is, that Date is just a value object with no methods to modify it. So it is designed for storing a date/time information somewhere. If you use a Calendar object, you could modify it after it is set to a persistent entity that performs some business logic with the date/time information. This is very dangerous, because the entity has no way to recognize this change. The Calendar class is designed for operations on date/time, like adding days or something like that. Playing around with your example I get the following: import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class TimeZoneExtracter { public static final void main(String[] args) throws ParseException { DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); System.out.println(dbFormatter.getTimeZone()); dbFormatter.parse("Fr, September 26, 2008 8:30 PM Eastern Daylight Time"); System.out.println(dbFormatter.getTimeZone()); } } Output: sun.util.calendar.ZoneInfo[id="Europe/Berlin"... sun.util.calendar.ZoneInfo[id="Africa/Addis_Ababa"... Is this the result you wanted? A: Ed has it right. you want the timeZone on the DateFormat object after the time has been parsed. String rawDate = "Friday, September 26, 2008 8:30 PM Eastern Daylight Time"; DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz"); Date scheduledDate = dbFormatter.parse(rawDate); System.out.println(rawDate); System.out.println(scheduledDate); System.out.println(dbFormatter.getTimeZone().getDisplayName()); produces Friday, September 26, 2008 8:30 PM Eastern Daylight Time Fri Sep 26 20:30:00 CDT 2008 Eastern Standard Time
{ "language": "en", "url": "https://stackoverflow.com/questions/85701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How can I make a ComboBox non-editable in .NET? I want to have a "select-only" ComboBox that provides a list of items for the user to select from. Typing should be disabled in the text portion of the ComboBox control. My initial googling of this turned up an overly complex, misguided suggestion to capture the KeyPress event. A: To add a Visual Studio GUI reference, you can find the DropDownStyle options under the Properties of the selected ComboBox: Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent(), like so: this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; A: To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList; Link to the documentation for the ComboBox DropDownStyle property on MSDN. A: Stay on your ComboBox and search the DropDropStyle property from the properties window and then choose DropDownList. A: Before Method1 Method2 cmb_type.DropDownStyle=ComboBoxStyle.DropDownList After A: COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList; A: To continue displaying data in the input after selecting, do so: VB.NET Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress e.Handled = True End Sub C# Private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; } A: for winforms .NET change DropDownStyle to DropDownList from Combobox property
{ "language": "en", "url": "https://stackoverflow.com/questions/85702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "227" }
Q: Monitoring group membership in Active Directory more efficiently (C# .NET) I've got an Active Directory synchronization tool (.NET 2.0 / C#) written as a Windows Service that I've been working on for a while and have recently been tasked with adding the ability to drive events based on changes in group membership. The basic scenario is that users are synchronized with a security database and, when group membership changes, the users need to have their access rights changed (ie. if I am now a member of "IT Staff" then I should automatically receive access to the server room, if I am removed from that group then I should automatically lose access to the server room). The problem is that when doing a DirectorySynchronization against groups you receive back the group that has had a member added/removed, and from there when you grab the members list you get back the list of all members in that group currently not just the members that have been added or removed. This leads me to quite an efficiency problem - that being that in order to know if a user has been added or removed I will have to keep locally a list of each group and all members and compare that against the current list to see who has been added (not in local list), and who has been deleted (in local list, not in current members list). I'm debating just storing the group membership details in a DataSet in memory and writing to disk each time I've processed new membership changes. That way if the service stops/crashes or the machine is rebooted I can still get to the current state of the Active Directory within the security database by comparing the last information on disk to that from the current group membership list. However, this seems terrible inefficient - running through every member in the group to compare against what is in the dataset and then writing out changes to disk each time there are changes to the list. Has anyone dealt with this scenario before? Is there some way that I haven't found to retrieve only a delta of group members? What would you do in this situation to ensure that you never miss any changes while taking the smallest performance hit possible? Edit: The AD might contain 500 users, it might contain 200,000 users - it depends on the customer, and on top of that how many groups the average user is a member of A: You can set up auditing for the success of account modifications in group policy editor You may then monitor security log for entries and handle log entries on account modifications. E.g. EventLog myLog = new EventLog("Security"); // set event handler myLog.EntryWritten += new EntryWrittenEventHandler(OnEntryWritten); myLog.EnableRaisingEvents = true; Make sure that you have privileges to acces Security event log http://support.microsoft.com/kb/323076 A: I'd say it depends on how many active directory objects you need to keep track of. If it's a small number (less than 1000 users) you can probably serialize your state data to disk with little noticable performance hit. If you're dealing with a very large number of objects it might be more efficient to create a simple persistence schema in something like SQL Express and use that. A: You know there are products which help you with directory synchronization and user provisioning (google those terms)? Not invented here and all that, and you may have to justify the investment in the current climate, but developing and maintaining code for which there already is a commercial solution is not, let us say, always the most cost-effective way in the long run. Not all of the support eventing/provisioning, but they do support tracking changes and distributing them: it's not a big deal creating eventing solutions on top of those capabilities. Microsoft has the Identity Integration Server (MISS) which is being repackaged as part of Identity Lifecycle Manager. It was originally built on a more general meta/master data management product, but is workable. IBM has the Tivoli Directory Integrator (but you need to keep up with the biyearly name changes!). Oracle has an Oracle Identity Manager, and Sun an Identity Manager. Most of these are leading products bought by the major players to fill a gap in their portfolios. Of course, these are enterprise-class products, meaning large & expensive, but generally pretty future-safe and extensible. If you don't need their full strength (yet!), you'll need to look at storing a copy for yourself. In that case, have you considered storing your replica of the last known AD tree using AD LDS (formerly AD/AM)? It's not in an optimum format for comparing differences, but a directory database will scale reasonably well, even the lightweight kind.
{ "language": "en", "url": "https://stackoverflow.com/questions/85724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Converting floating point exceptions into C++ exceptions Is it possible to convert floating point exceptions (signals) into C++ exceptions on x86 Linux? This is for debugging purposes, so nonportability and imperfection is okay (e.g., if it isn't 100% guaranteed that all destructors are called). A: If your C++ standard library implementation supports the TR1 functions fetestexcept, feraiseexcept and feclearexcept (mine doesn't yet so I can't test this) you can detect five kinds of floating point errors and then you can throw whatever exceptions you want. See here for a description of these functions. I also recommend section 12.3, "Managing the Floating Point Environment," of the book The C++ Standard Library Extensions: A Tutorial and Reference by Pete Becker, ISBN-13: 9780321412997, for an excellent description of these functions with sample code. A: Due to the way signals and exceptions work, you can't do it immediately when the signal is thrown - exceptions rely on certain aspects of the stack that aren't true when a signal handler gets called. You can set a global variable in the signal handler, and then check this at key points in the program and throw an exception if it's set. This doesn't give you the exact information about the thrown exception, though. A: the gcc option -fnon-call-exceptions might be of some use to you. Couldn't find any documentation on it though so your mileage may vary. A: I don't have a ready made solution, but one thing you could look at are signals (not sure whether you can safely throw C++ exceptions from them, but it should help for debugging anyway.) You could install a signal handler for SIGFPE, and use that for your debugging purposes. A: The basic idea will be for you to install the appropriate signal handlers for floating point exceptions. Inside your signal handler, you can throw an exception (or send a user-defined signal to another process which will raise the exception, or send a message to another thread for something similar, etc. etc. etc). There are any number of ways to actually throw the exception - the main thing is to handle the signal.
{ "language": "en", "url": "https://stackoverflow.com/questions/85726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do you switch on a string in XQuery? I have an external variable coming in as a string and I would like to do a switch/case on it. How do I do that in xquery? A: Just use a series of if expressions: if ($room eq "bathroom") then "loo" else if ($room eq "kitchen") then "scullery" else "just a room" Using a typeswitch is hiding what you are really doing. Which of these methods is most efficient will depend on the XQuery processor you are using. In an ideal world it should only be a matter of taste, as it should be down to the optimizer to select the appropriate method, but if performance is important it is worth benchmarking both versions. I would be very surprised if a processor optimized the node construction out of your example, and didn't optimize my example to a specialized switch. A: XQuery doesn't have a function for switching on anything other than elements. The first thing you do is convert your string to an element. let $str := "kitchen" let $room := element {$str} {} Then just use typeswitch to do a normal switch: return typeswitch($room) case element(bathroom) return "loo" case element(kitchen) return "scullery" default return "just a room" Please note, this may be a MarkLogic only solution. A: If your processor supports XQuery 1.1, then you can simply do: switch ($room) case "bathroom" return "loo" case "kitchen" return "scullery" default return "just a room" A: Starting with XQuery 1.1, use switch: http://www.w3.org/TR/xquery-11/#id-switch switch ($animal) case "Cow" return "Moo" case "Cat" return "Meow" case "Duck" return "Quack" default return "What's that odd noise?" A: For Saxon, you can use something like this: declare function a:fn($i) { typeswitch ($i) case element(a:elemen1, xs:untyped) return 'a' case element(a:elemen2, xs:untyped) return 'b' default return "error;" }; https://rrusin.blogspot.com/2010/01/xquery4j-in-action.html
{ "language": "en", "url": "https://stackoverflow.com/questions/85761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to sort an array by keys in an ascending direction? here is the input i am getting from my flash file process.php?Q2=898&Aa=Grade1&Tim=0%3A0%3A12&Q1=908&Bb=lkj&Q4=jhj&Q3=08&Cc=North%20America&Q0=1 and in php i use this code foreach ($_GET as $field => $label) { $datarray[]=$_GET[$field]; echo "$field :"; echo $_GET[$field];; echo "<br>"; i get this out put Q2 :898 Aa :Grade1 Tim :0:0:12 Q1 :908 Bb :lkj Q4 :jhj Q3 :08 Cc :North America Q0 :1 now my question is how do i sort it alphabaticaly so it should look like this Aa :Grade1 Bb :lkj Cc :North America Q0 :1 Q1 :908 and so on....before i can insert it into the DB A: ksort($_GET); This should ksort the $_GET array by it's keys. krsort for reverse order. A: what you're looking for is ksort. Dig the PHP manual! ;) A: To get a natural sort by key: function knatsort(&$karr){ $kkeyarr = array_keys($karr); natsort($kkeyarr); $ksortedarr = array(); foreach($kkeyarr as $kcurrkey){ $ksortedarr[$kcurrkey] = $karr[$kcurrkey]; } $karr = $ksortedarr; return true; } Thanks, PHP Manual! foreach ($_GET as $key => $value) { echo $key.' - '.$value.'<br/>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/85770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I write code with unique sections for different versions of .NET My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions & what is the best way to deal with this situation. I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think? A: There are a lot of different options here. Where I work we use #if pragmas but it could also be done with separate assemblies for the separate versions. Ideally you would at least keep the version dependant code in separate partial class files and make the correct version available at compile time. I would enforce this if I could go back in time, our code base now has a whole lot of #if pragmas and sometimes it can be hard to manage. The worst part of the whole #if pragma thing is that Visual Studio just ignores anything that won't compile with the current defines and so it's very easy to check in breaking changes. NUnit supports both 1.1 and 2.0 and so is a good choice for a test framework. It's not too hard to use something like NAnt to make separate 1.1 and 2.0 builds and then automatically run the NUnit tests. A: If you want to do something like this you will need to use preprocessor commands and conditional compilation symbols. I would use symbols that clearly indicate the version of .NET you are targeting (say NET11 and NET20) and then wrap the relevant code like this: #if NET11 // .NET 1.1 code #elif NET20 // .NET 2.0 code #endif The reason for doing it this way rather than a simple if/else is an extra layer of protection in case someone forgets to define the symbol. That being said, you should really drill down to the heart of the reason why you want/need to do this. A: I would be asking the question of WHY you have to maintain two code bases, I would pick one and go with it if there is any chance of it. Trying to keep two code bases in sync with the number of changes, and types of changes would be very complex, and a build process to build for either version would be very complex. A: We had this problem and we ended up with a "compatability layer" where we implemented a single set of interfaces and utility code for .NET v1.1 and v2.0. Then our installer laid down the right code for the right version. We used NSIS (free!), and they have functions you can call to determine the .NET version.
{ "language": "en", "url": "https://stackoverflow.com/questions/85773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }