text
stringlengths
8
267k
meta
dict
Q: What are some good java make utilities? I'm looking for a make utility for building large java programs. I'm aware of ANT already, but want to see what else is available. Ideally, it should be able to handle the .java->.class package directory weirdness that fouls up GNU Make. Win32, but cross platform is a plus. EDIT: I see some cons to using ANT, which is why I wanted to see other options, though I'll probably end up using it anyway, just because it works. * *requires nontrivial XML makefiles, "HelloWorld" is already 25 lines, and any more reasonable program gets large quickly. * *The ant tutorials show comparisons of ant build.xml files that are roughly identical to big .bat files that just run all the java commands, only longer. http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html, I've already got one of those. *Xml means that every single dependency, variable, target, rule and project has extra cruft on it, it just makes lines hard to read. The Angle Bracket Tax *solves all the wrong problems for me. * *ant makes writing jar and javac command lines easier, generating manifests easier, specifying .java source files easier, specifying jvm/java properties easier, writing custom build tools easier. *ant does not make java class dependencies easier, and does not seem to have a more powerful variable system, both things usually solved by make utilities. I'd use gnu make, but it can't figure out where the .class file for a .java file with a package declaration is going to end up. A: Ant and Maven are definitely the two standards. If you're already familiar with Ant and want the dependency management that comes with Maven, you might take a look at Ivy. One thing both Ant and Maven lack is true control structures in your build scripts. There are plugins you can download for Ant that provide some of this control, but (again, if you're already familiar with Ant) you may take a look at Gant which is a Groovy wrapper for Ant. A: If you're starting a new project you may want to look into maven. It's kinda hard intially, but it handles a bunch of stuff for you including dependencies. If you already have a project which you want to make a build file for, then I don't have any recommendations apart from the aforementioned ant. A: Forget ANT!! Apache Maven is the way to go if you ask me. The feature i like the most is it built in in dependency management. This means you dont have to check 3rd party JARs into your source control project. You specify your dependencies in the maven POM (Project Object Model - Its basically an XML description of your project) and maven automatically downloads, compiles against them and packages them with your app. Other really nice features are: Release management and distribution publication - Perform releases using maven console commands. This feature will tag your code base in source control. Checkout a clean copy, build it & package it for deployment. A second command will upload it to your repository for distribution to other end users. A large and growing repository of libraries already using maven - EVERY Apache project uses maven. LOADS more are on board also. See for yourself, here's the main repo Ability to host your own repo. - Where you can release your own builds and also upload JARs that dont exist in other public repos (like most SUN jars) A: This isn't so much an answer as a question. ANT is the standard way of building Java. It works well with Java, the myriad of Java tools out there and with Cruise Control. So why would you want to try anything else? Unless you have an edge case that ANT doesn't cover, then I'd recommend you stick with ANT. Of course I'd be happy for a more knowledgeable person to point out why my attitude is stupid and why there is a good case for looking at alternatives ;) A: One alternative is scons if you want something pretty lightweight. I've used it a little and found it to be pretty easy to understand, especially if you already know python syntax. Another option is maven, but it is not simple by any means. However, it does provide a lot of additional facilities such as helping to manage docs. I wouldn't refer to it as a make replacement however;) A: ant has been the leader for years. But its build.xml being, well, xml-based, it is very verbose. Dependency management can be achieved by coupling it with ivy. maven strives to provide out of the box what the ant+ivy tandem provides, it is nice while it works. If it stops doing that and you have to find out where it messes up with dependency management, it may very likely be the worst hell you can imagine. Also it's pom.xml... is written in xml. sbt is the royal scala build tool, uses ivy for dependency management, and the build files are writen in a scala DSL. Quite mature, but the scala dialect may not be to your liking. buildr build files are specified in ruby. Compatible with maven repositories and brings it's own dependency management. Ant integration is there, too. gradle uses groovy for its build files. Beside maven or ivy support it has it's own dependency manager now after having used ivy in the past and not being satisfied. Seamless ant integration. Has the easiest syntax by far. ant, ivy, maven, buildr are apache projects. TL;DR Check gradle or buildr. A: jmk. It's primitive, but so small that you can embed it in a source .tar.gz file and barely change its size. A: Unless Maven has really improved recently, I'd steer well clear of it. Unless you have some kind of monster "multi-project" with a gazillion dependencies of course. After getting sick of looking at completely useless and unhelpful errors when attempting to do the simplest things (like FTP a war file to a server), Maven was thrown away and Ant dusted off. I haven't looked back since. A: Well, obviously, there's the classic make (make, gmake, nmake) utilities, there's also (I think) some build systems written in Ruby, or maybe Python. They aren't Java specific, rather just scriptable build systems. But ANT has been the leader of the pack pushing 8-9 years now, and in terms of the basics, it's pretty easy to get started with. Back in the day, make from particularly horrible for compiling java because it was typically invoking the javac compiler for each file individually. ANT doesn't suffer from this, and, perhaps, make could be modified to not do that. But it was one of the elements of ANT that made it so popular. It was simply fast. I appreciate that ANT may not be the perfect solution, but it sure it practical. A: I converted from Ant to Maven 2 and have not looked back since. Ant and Maven 2 different ways of building.With Ant you are giving instructions on how to build things. Whereas with Maven 2 you tell it what you want built. If you have an existing Ant build,xml you can take a first step in refactoring you build by wrapping that in an Maven 2 pom.xml. A: 1) ant + ivy is pretty good if you have existing investment in ant. You don't have to move from ant to maven just for the dependency goodies. 2) gant and ant : how do they compare : http://java.dzone.com/articles/ant-or-gant-part-1 3) http://www.gradle.org/ -- uses groovy! BR, ~A A: I like to use ant with ant4eclipse. This allows me to set up dependencies in eclipse, do development builds and testing in eclipse, and do continuous builds using ant. A: I use ANT all the time. This is because i develop web applications using Google Web Toolkit (GWT) which has an extra step of compiling client side java into java script. With ant, all i needed to know is how GWT works and then i orchestrate the build myself. With maven, i have to wait till someone writes a plugin. or i write one myself. There is a possibility that other frameworks and tools that dont follow the usual conventions will come up. i dont have to keep looking for maven plugins all the time. With ant, i can do whatever i want in a transparent manner. I also enjoy writting xml files. (i have to because i have to write several - web.xml, application.xml, persistence.xml, SqlMap.xml, dataset.xml e.t.c. My point _ XML is one thing you have to learn to like)
{ "language": "en", "url": "https://stackoverflow.com/questions/169293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to run untrusted Ruby code inside a safe sandbox? I want to be able to run unstrusted ruby code. I want to be able to pass variables to said untrusted code that it may use. I also want said code to return a result to me. Here is a conceptual example of what I am thinking input = "sweet" output = nil Thread.start { $SAFE = 4 #... untrusted code goes here, it uses the input variable(s) #to calculate some result that it places in the output variable } #parse the output variable as a string. Just to clarify, I am basically using the untrusted code as a function. I want to provide its some inputs, and then allow it to write to the output. That is all I really want, I don't care how it is done, I just want the ability to use untrusted Ruby code as a sort of function. The solution does not have to look anything like the code I wrote above, I am just using it to illustrate what I want. Now, I can currently think of 3 ways to do this: * *Use the $SAFE level construct above. *whytheluckystiff has a Sandbox plugin for ruby *I could run each function in its own virtual machine, using some sort of os virtualization software like vmware or Xen or something. I am wondering if anyone has any recommendations for running untrusted ruby code in a functional way? What option would you recomend? How would you go about it? Thanks. A: I'd strongly recommend just using JRuby. The JVM has had a very strong security model built in from the beginning, and JRuby piggy-backs off that. You can restrict access to files, restrict loading of code, and much more. It's far better than anything that exists in native Ruby impls, and there are a number of sites that run sandboxed, user-accessible sites atop JRuby for exactly this purpose. A: $SAFE doesn't protect you from everything a malicious hacker could do. Having gone down this path (see Ruby: creating a sandboxed eval?), I followed commenters' sage advice and embedded an application-specific interpreter that gave me complete control over what could and couldn't be done (see Ruby: looking for ruby-embeddable interpreter or scripting language). It turned out to be incredibly easy using stickup (like less than an hour from downloading the gem to a customized interpreter) -- see https://github.com/jcoglan/stickup A: I created a gem called 'trusted-sandbox' that runs Ruby code within a fully controlled Docker container. You can disable network, set disk quotas, limit execution time, balance CPU with other running containers, set memory limits, etc. And the overhead is quite low. You can read more about it here: https://github.com/vaharoni/trusted-sandbox Let me know what you think! A: $SAFE is not enough; you need to be at least at the level of Why's freaky sandbox. However, I don't know if that sandbox code is actively maintained or if he/they ever solved the holes such as infinite loops, etc. Unsafe generally means hostile. If you can relax from hostile to, say, 'naive', and depending upon the requirements of your app, you might get away with sandboxing in Ruby. It's not really a first-class scenario in the language design. Even with that, though, you probably don't need to go to the machine level of separation. I'd feel pretty safe using a sandbox in a separately spawned process, with your app functioning as a process manager to kill off any that manage to hang/flame. Now, that is a few orders of magnitude more work than your simple block above. But remember and keep repeating, "SAFE can't deal with hostile".
{ "language": "en", "url": "https://stackoverflow.com/questions/169303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Extending Java Web Applications with plugins I have this web application that has grown to an unmanageable mess. I want to split it into a common "framework" part (that still includes web stuff like pages and images) and several modules that add extra functionality and screens. I want this refactoring to also be useful as a plugin system for third-party extensions. All modules need to be separate unit of deployments, ideally a war or jar file. I tried to just make several regular war files, but Tomcat keeps (according to the servlet spec) these war files completely separate from each-other, so that they cannot share their classes, for example. I need to plugins to be able to see the "main" classpath. I need to main application to have some control over the plugins, such as being able to list them, and set their configuration. I would like to maintain complete separation between the plugins themselves (unless they specify dependencies) and any other unrelated web applications that may be running on the same Tomcat. I would like them to be rooted under the "main" application URL prefix, but that is not necessary. I would like to use Tomcat (big architectural changes need to be coordinated with too many people), but also to hear about a clean solution in the EJB or OSGi world if there are. A: I have been tinkering with the idea of using OSGi to solve the same problem you are describing. In particular I am looking at using Spring Dynamic Modules. A: Take a look at Java Portlets - http://developers.sun.com/portalserver/reference/techart/jsr168/ - in a nutshell, a specification that allows interoperability between what are otherwise self-contained j2ee web applications Edit I forgot to mention that Portlets are pretty much framework agnostic - so you can use Spring for the parent application, and individual developers can use whatever they want on their Portlets. A: Have you looked at using maven to separate out your projects and then have it resolve the dependencies between the WARs and JARs? You'll end up with duplication of libraries between WARs, but only where it's necessary (and this shouldn't be a problem unless you get into some funky classloader fun). Tomcat also allows you to configure cross context applications if you need to get from one WAR to another in a relatively transparent way... If you want to keep things under the same single web app (say ROOT) you could create a proxy webapp that forwards through to the relevant other webapp behind the scenes for the user to make it relatively transparent? A: Your primary problem is going to center around the physical, static assets of the system -- the rest are simply, effectively, jars. WARs are separated, in Tomcat, with separate classloaders but also they're separated at the session level (each WAR is an indvidual web app, and has it's own session state). In Glassfish, if the WARs were bundled in an EAR, they would share classloaders (GF uses a flat class loader space in EARs), but would still have separate session state. Also, I'm not sure if you can do a "forward" to another WAR in the server. The problem there is that forwards use a relative URL to the root of the Web App, and each WebApp has their own root, so you simply "can't get there from here". You can redirect, but that's not the same thing as a forward. So these features of the Web App conspire against you trying to deploy them homogenously within the container. Rather, I think the hot tip is to create an "assembler" utility that takes your individual modules and "merges" them in to a single Web App. It can merge their web.xml, their content, normalize the jars and classes, etc. WARs are a feature and a bug in the Java world. I love them because they really do make deploying compiled applications "Drag and drop" in terms of installing them, and that's feature is used far more than what you're encountering. But I feel your pain. We have a common "core" framework we share across apps, and we basically have to continuously merge it to maintain it. We've scripted it, but it's still a bit of a pain. A: "Also, I'm not sure if you can do a "forward" to another WAR in the server. The problem there is that forwards use a relative URL to the root of the Web App, and each WebApp has their own root, so you simply "can't get there from here". You can redirect, but that's not the same thing as a forward." You can forward to another WAR as long as that WAR lets someone do it. glassfish and multiple WARs of an EAR : that makes sense. If you put the MAIN classes in the shared CLASSPATH of tomcat, then you can put your individual PLUGINs in separate WAR files. The Main app can also be part of the TOMCAT servlet that you define in server.xml. This can be the MASTER SERVLET and all other WARs can be controlled by this master servlet. Does that make sense ? BR, ~A A: Depending on the complexity of the plugin functionality I would also be considering a web service, for instance implemented with Axis. Your main appplication is then configured with the URL to the web application (plugin) which provides the service. The advantage,as I see it, is twofold: * *You get a nice, clean, debuggable API between the two wars, namely the Soap/XML messages *You are able to upgrade a single plugin without having to regression-test your entire application The disadvatages are that you have to set up some Axis projects, and that you have to have some sort of plugin configuration. Furthermore you might need to limit access to your services web applications, so a bit of configuration might be required. If the plugins work on the same database be sure to either limit cache time or to configure a war-spanning caching layer. A: I also been trying develop a common or abstract framework where I can add plugins (or modules) at runtime and enhance existing running webapp. Now, as you said, preferred ed way to do it using WAR or JAR file. Problem with WAR file is, you can't deploy as plugin to existing app. Tomcat will deploy it as separate web context. Not desirable. Another option is to JAR file and write some custom code to copy that JAR file to WEB-INF/lib folder and load the classes into existing classloader. Problem is, how to deploy non-java files like JSP or config files. For that, there r two solutions, a. Use velocity templates instead of JSP (b.) write some custom code to read JSP from classpath instead of context path. OSGI or Spring Dynamic modules are nice, but at this time, they look overly complex to me. I will look into that again, if I get feel of it. I am looking for simple API, which can take care of life cycle of plugin and still able to use JSPs in my packaged JAR file. May be, you can use un jar the plugin at time deployment and copy files to right directories. A: There actually is nothing better than OSGI if you are thinking about splitting application into separate modules. Take a look at Greenpages example. You can create a parent module (core) where you include jars that your application need. If you know something about component programming, you will soon find out that OSGI modules behave like interfaces, where you have to expose what you will use in other modules. It is quite simple once you understand. Anyway it also can be really painful when you learn how to use OSGI. We had problems using JSON, as a version of Jackson that we added as jar to the module, was overridden by other jar that was contained in the Spring core modules. You always have to double check what version of jar is loaded for your needs. Unfortunately even OSGI approach does not solve what we are searching for. How to extend a persistent model and existing forms in runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/169329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Simple way to programmatically get all stored procedures Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI. I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want. To clarify.... I'd like to script out the stored procedures. The list via the Select * from sys.procedures is helpful, but in the end I need to script out each of these. A: Just read the output of SELECT NAME from SYS.PROCEDURES , then call EXEC sp_HelpText SPNAME for each stored procedure, you'll get a record set with one line of text per row. A: ;WITH ROUTINES AS ( -- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit SELECT o.type_desc AS ROUTINE_TYPE ,o.[name] AS ROUTINE_NAME ,m.definition AS ROUTINE_DEFINITION FROM sys.sql_modules AS m INNER JOIN sys.objects AS o ON m.object_id = o.object_id ) SELECT * FROM ROUTINES A: public static void GenerateTableScript() { Server databaseServer = default(Server);//DataBase Server Name databaseServer = new Server("yourDatabase Server Name"); string strFileName = @"C:\Images\Your FileName_" + DateTime.Today.ToString("yyyyMMdd") + ".sql"; //20120720`enter code here if (System.IO.File.Exists(strFileName)) System.IO.File.Delete(strFileName); List<SqlSmoObject> list = new List<SqlSmoObject>(); Scripter scripter = new Scripter(databaseServer); Database dbUltimateSurvey = databaseServer.Databases["YourDataBaseName"];//DataBase Name //Table scripting Writing DataTable dataTable1 = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.Table); foreach (DataRow drTable in dataTable1.Rows) { //string strTableSchema = (string)drTable["Schema"]; //if (strTableSchema == "dbo") // continue; Table dbTable = (Table)databaseServer.GetSmoObject(new Urn((string)drTable["Urn"])); if (!dbTable.IsSystemObject) if (dbTable.Name.Contains("SASTool_")) list.Add(dbTable); } scripter.Server = databaseServer; scripter.Options.IncludeHeaders = true; scripter.Options.SchemaQualify = true; scripter.Options.ToFileOnly = true; scripter.Options.FileName = strFileName; scripter.Options.DriAll = true; scripter.Options.AppendToFile = true; scripter.Script(list.ToArray());//Table Script completed //Store Procedures scripting Writing list = new List<SqlSmoObject>(); DataTable dataTable = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.StoredProcedure); foreach (DataRow row in dataTable.Rows) { string sSchema = (string)row["Schema"]; if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA") continue; StoredProcedure sp = (StoredProcedure)databaseServer.GetSmoObject( new Urn((string)row["Urn"])); if (!sp.IsSystemObject) if (sp.Name.Contains("custom_")) list.Add(sp); } scripter.Server = databaseServer; scripter.Options.IncludeHeaders = true; scripter.Options.SchemaQualify = true; scripter.Options.ToFileOnly = true; scripter.Options.FileName = strFileName; scripter.Options.DriAll = true; scripter.Options.AppendToFile = true; scripter.Script(list.ToArray()); // Stored procedure Script completed } A: You can use SMO for that. First of all, add references to these assemblies to your project: * *Microsoft.SqlServer.ConnectionInfo *Microsoft.SqlServer.Smo *Microsoft.SqlServer.SmoEnum They are located in the GAC (browse to C:\WINDOWS\assembly folder). Use the following code as an example of scripting stored procedures: using System; using System.Collections.Generic; using System.Data; using Microsoft.SqlServer.Management.Smo; class Program { static void Main(string[] args) { Server server = new Server(@".\SQLEXPRESS"); Database db = server.Databases["Northwind"]; List<SqlSmoObject> list = new List<SqlSmoObject>(); DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure); foreach (DataRow row in dataTable.Rows) { string sSchema = (string)row["Schema"]; if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA") continue; StoredProcedure sp = (StoredProcedure)server.GetSmoObject( new Urn((string)row["Urn"])); if (!sp.IsSystemObject) list.Add(sp); } Scripter scripter = new Scripter(); scripter.Server = server; scripter.Options.IncludeHeaders = true; scripter.Options.SchemaQualify = true; scripter.Options.ToFileOnly = true; scripter.Options.FileName = @"C:\StoredProcedures.sql"; scripter.Script(list.ToArray()); } } See also: SQL Server: SMO Scripting Basics. A: This blog post suggests running this against your database: select * from sys.procedures A: You can use: DataTable dtProcs = sqlConn.GetSchema("Procedures", new string[] { databaseName }); DataTable dtProcParams = sqlConn.GetSchema("ProcedureParameters", new string[] { databaseName }); You can also get all sorts of other schema info like tables, indexes etc. if you need them. You can get info on GetSchema() here and info on the SQL Server Schema Collections here Edit: Sorry, this doesn't help with actually scripting the info, but I guess it's useful info to have. A: You can write C# code to run the following query on your database. Select * from sys.procedures A: I think this is what you're really looking for: select SPECIFIC_NAME,ROUTINE_DEFINITION from information_schema.routines There are a ton of other useful columns in there too... A: begin --select column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Products' --Declare the Table variable DECLARE @GeneratedStoredProcedures TABLE ( Number INT IDENTITY(1,1), --Auto incrementing Identity column name VARCHAR(300) --The string value ) --Decalre a variable to remember the position of the current delimiter DECLARE @CurrentDelimiterPositionVar INT declare @sqlCode varchar(max) --Decalre a variable to remember the number of rows in the table DECLARE @Count INT --Populate the TABLE variable using some logic INSERT INTO @GeneratedStoredProcedures SELECT name FROM sys.procedures where name like 'procGen_%' --Initialize the looper variable SET @CurrentDelimiterPositionVar = 1 --Determine the number of rows in the Table SELECT @Count=max(Number) from @GeneratedStoredProcedures --A variable to hold the currently selected value from the table DECLARE @CurrentValue varchar(300); --Loop through until all row processing is done WHILE @CurrentDelimiterPositionVar <= @Count BEGIN --Load current value from the Table SELECT @CurrentValue = name FROM @GeneratedStoredProcedures WHERE Number = @CurrentDelimiterPositionVar --Process the current value --print @CurrentValue set @sqlCode = 'drop procedure ' + @CurrentValue print @sqlCode --exec (@sqlCode) --Increment loop counter SET @CurrentDelimiterPositionVar = @CurrentDelimiterPositionVar + 1; END end A: If you open up a can of reflector on sqlmetal.exe (a stand-alone part of LINQ-to-SQL that generates code from a database), you can see the SQL statements it uses to get a list of all stored procedures and functions. The SQL is similar, but not identical, to the one in this answer. A: This is a SQL that I have just tested and used in MSSQL SELECT NAME from SYS.PROCEDURES order by name In case that you need to look for a specific name or substring/text SELECT NAME from SYS.PROCEDURES where name like '%<TEXT_TO_LOOK_FOR>%' order by name Replace with exactly that for example: SELECT NAME from SYS.PROCEDURES where name like '%CUSTOMER%' order by name And calling EXEC sp_HelpText SPNAME for each stored procedure, you'll get a record set with one line of text per row A: Assuming you have SqlConnection object called sqlCon, simplest way is to call sqlCon.GetSchema("Procedures")
{ "language": "en", "url": "https://stackoverflow.com/questions/169330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Is there a timer class in C# that isn't in the Windows.Forms namespace? I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application. Is there a C# timer (or timer like) class for use in console applications? A: There are at least the System.Timers.Timer and System.Threading.Timer classes that I'm aware of. One thing to watch out though (if you haven't done this before already), say if you already have the System.Threading namespace in your using clause already but you actually want to use the timer in System.Timers, you need to do this: using System.Threading; using Timer = System.Timers.Timer; Jon Skeet has an article just on Timers in his multithreading guide, it's well worth a read: https://jonskeet.uk/csharp/threads/timers.html A: System.Timers.Timer And as MagicKat says: System.Threading.Timer You can see the differences here: http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/ And you can see MSDN examples here: http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx And here: http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx A: I would recommend the Timer class in the System.Timers namespace. Also of interest, the Timer class in the System.Threading namespace. using System; using System.Timers; public class Timer1 { private static Timer aTimer = new System.Timers.Timer(10000); public static void Main() { aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Enabled = true; Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); } // Specify what you want to happen when the Elapsed event is // raised. private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); } } Example from MSDN docs. A: System.Diagnostics.Stopwatch if your goal is to time how long something takes to run A: It is recommended to not to use System.Timer's Timer class. A: This question is old and existing answers cover well the issue as it was at the time. In the meantime, something new has happened. Timer, sure, for what ? Using a timer is a way to run some processing with some delay and/or at regular interval. There are two cases: (1) it's just to run some short code periodically without any thread concern, no trouble, no mess. If the plain Windows Forms timer is not suitable, then System.Timers.Timer with its SynchronizingObject property makes it more straightforward than System.Threading.Timer . (2) what you're coding is in the realm of asynchronous concurrent processing. That has traditionally been error-prone, difficult to debug, to get right, whatever the plain timer used. In case 2 you might get away with traditional approach, but beware, complexity is lurking and ready to eat you not just once but any time you just don't make the best choice, with cumulative effects. Now we've got something better If your situation deals with some kind of "event" handling (whatever the way it's coded: keypresses, mouse buttons, bytes from a serial port, from a network connection, from measurements, etc), you should consider Reactive Programming. Reactive Programming has in recent years somehow uncovered how to code for these situations, while not falling into complexity traps. So, technically the following link is an answer to the question: it is a timer which is in the System.Reactive.Linq namespace: Observable.Timer Method (System.Reactive.Linq) To be fair, it's a timer that comes and plays well with the Reactive Programming mindset and a lot of game-changing stuff. Yet it might or might not be the best tool, depending on the context. Since this question is .NET-centric, you might be interested in Good introduction to the .NET Reactive Framework Or for a clear, illustrated, more general (not Microsoft-centric) document, this seems good The introduction to Reactive Programming you've been missing.
{ "language": "en", "url": "https://stackoverflow.com/questions/169332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Padding - Encryption algorithm I'm writing an implementation of the XXTEA encryption algorithm that works on "streams", ie, can be used like: crypt mykey < myfile > output. One of the requisites is that it doesn't have access to the file at all (it only reads an fixed size block until find an EOF). The algorithm needs that the data bytes is multiple of 4, so its needed to add a padding. For plain text a good solution is to pad with NULLs, and in the decryption just ignore the NULLs, but the same strategy cannot be used for binary streams (that can contain embedded NULLs). I've read the common solutions, like padding with the number of missing chars (if it miss 3 chars, then append an 3, 3, 3 at the end) and etc, but I wonder: theres a more elegant solution? A: Read: http://msdn.microsoft.com/en-us/library/system.security.cryptography.paddingmode.aspx It has a list of common padding methods, like: PKCS7 - The PKCS #7 padding string consists of a sequence of bytes, each of which is equal to the total number of padding bytes added. The ANSIX923 padding string consists of a sequence of bytes filled with zeros before the length. The ISO10126 padding string consists of random data before the length. Examples: Raw data: 01 01 01 01 01 PKCS #7: 01 01 01 01 01 03 03 03 ANSIX923 01 01 01 01 01 00 00 03 ISO10126: 01 01 01 01 01 CD A9 03 A: Read up on ciphertext stealing. It's arguably much more elegant than plaintext padding. Also, I'd suggest using a block size larger than 4 bytes -- 64 bits is probably the bare minimum. Strictly speaking, do-it-yourself cryptography is a dangerous idea; it's hard to beat algorithms that the entire crypto community has tried and failed to break. Have fun, and consider reading this, or at least something from Schneier's "related reading" section. A: Reading the question it looks like the security aspect of this is moot. Simply put, you have an api that expects a multiple of 4 bytes as input, which you dont always have. Appending up to 3 bytes onto any binary stream is dangerous if you can't make guarantees that the binary stream doesn't care. Appending 0's onto the end of an exe file doesnt matter as exe files have headers specifying the relevent sizes of all remaining bits. Appending 0's onto the end of a pcx file would break it as pcx files have a header that starts a specific number of bytes from the end of the file. So really you have no choice - there are no choice of magic padding bytes you can use that are guaranteed to never occur naturally at the end of a binary stream: You must always append at least one additional dword of information describing the padding bytes used. A: Actually I would expect that a good stream cipher needs no padding at all. RC4 for example needs no padding and is is a very strong stream cipher. However, it can be attacked if the attacker can feed different chosen data to the encryption routine, that always uses the same key, and also has access to the encrypted data. Choosing the right input data and analyzing the output data can be used to restore the encryption key, without a brute force attack; but other than that RC4 is very secure. If it needs padding, it is no stream cipher IMHO. As if you pad to be a multiple of 4 byte or a multiple of 16 byte, what's the huge difference? And if it is padded to be a multiple of 16 byte, you could use pretty much any block cipher. Actually your cipher is a block cipher, it just works with 4 byte blocks. It was a stream cipher on a system where every "symbol" is 4 byte (e.g. when encryption UTF-32 text, in which case the data will always be a multiple of 4 for sure, thus there is never any padding).
{ "language": "en", "url": "https://stackoverflow.com/questions/169334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why isn't my custom WCF behavior extension element type being found? I have a solution that contains two projects. One project is an ASP.NET Web Application Project, and one is a class library. The web application has a project reference to the class library. Neither of these is strongly-named. In the class library, which I'll call "Framework," I have an endpoint behavior (an IEndpointBehavior implementation) and a configuration element (a class derived from BehaviorExtensionsElement). The configuration element is so I can attach the endpoint behavior to a service via configuration. In the web application, I have an AJAX-enabled WCF service. In web.config, I have the AJAX service configured to use my custom behavior. The system.serviceModel section of the configuration is pretty standard and looks like this: <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="MyEndpointBehavior"> <enableWebScript /> <customEndpointBehavior /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> <services> <service name="WebSite.AjaxService"> <endpoint address="" behaviorConfiguration="MyEndpointBehavior" binding="webHttpBinding" contract="WebSite.AjaxService" /> </service> </services> <extensions> <behaviorExtensions> <add name="customEndpointBehavior" type="Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> </behaviorExtensions> </extensions> </system.serviceModel> At runtime, this works perfectly. The AJAX enabled WCF service correctly uses my custom configured endpoint behavior. The problem is when I try to add a new AJAX WCF service. If I do Add -> New Item... and select "AJAX-enabled WCF Service," I can watch it add the .svc file and codebehind, but when it gets to updating the web.config file, I get this error: The configuration file is not a valid configuration file for WCF Service Library. The type 'Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' registered for extension 'customEndpointBehavior' could not be loaded. Obviously the configuration is entirely valid since it works perfectly at runtime. If I remove the element from my behavior configuration temporarily and then add the AJAX-enabled WCF Service, everything goes without a hitch. Unfortunately, in a larger project where we will have multiple services with various configurations, removing all of the custom behaviors temporarily is going to be error prone. While I realize I could go without using the wizard and do everything manually, not everyone can, and it'd be nice to be able to just use the product as it was meant to be used - wizards and all. Why isn't my custom WCF behavior extension element type being found? Updates/clarifications: * *It does work at runtime, just not design time. *The Framework assembly is in the web project's bin folder when I attempt to add the service. *While I could add services manually ("without configuration"), I need the out-of-the-box item template to work - that's the whole goal of the question. *This issue is being seen in Visual Studio 2008. In VS 2010 this appears to be resolved. I filed this issue on Microsoft Connect and it turns out you either have to put your custom configuration element in the GAC or put it in the IDE folder. They won't be fixing it, at least for now. I've posted the workaround they provided as the "answer" to this question. A: As an FYI to anyone who stumbles across this these days a possible solution is to FULLY qualify your assembly in your app.config/web.config. EG if you had <system.serviceModel> <extensions> <behaviorExtensions> <add name="clientCredential" type="Client.ClientCredentialElement, Client" /> </behaviorExtensions> </extensions> try - replacing the values as necassary <system.serviceModel> <extensions> <behaviorExtensions> <add name="clientCredential" type="Client.ClientCredentialElement, Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </behaviorExtensions> </extensions> this particular solution worked for me. A: I just used [assembly: AssemblyVersion("1.0.*")] //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")] So I have new assembly build number every time. But we have <add name="clientCredential" type="Client.ClientCredentialElement, Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> where Version=1.0.0.0 THIS IS WRONG!!! So you have 2 options * *Back to //[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] Keep it manually. [assembly: AssemblyFileVersion("1.0.0.0")] *Every build manually replace Version=1.0.0.0 with a correct number. A: I tried this with a new project just to make sure it wasn't your specific project/config and had the exact same issue. Using fusion logs, it appears that the system looks for the behavior extensions ONLY in the IDE directory (C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE). Copying the assembly to this directory in a post-build step works, but is ugly. A: Per the workaround that Microsoft posted on the Connect issue I filed for this, it's a known issue and there won't be any solution for it, at least in the current release: The reason for failing to add a new service item: When adding a new item and updating the configuration file, the system will try to load configuration file, so it will try to search and load the assembly of the cusom extension in this config file. Only in the cases that the assembly is GACed or is located in the same path as vs exe (Program Files\Microsoft Visual Studio 9.0\Common7\IDE), the system can find it. Otherwise, the error dialog will pop up and "add a new item" will fail. I understand your pain points. Unfortunately we cannot take this change in current release. We will investigate it in later releases and try to provide a better solution then,such as providing a browse dialog to enable customers to specify the path, or better error message to indicate some work around solution, etc... Can you try the work around in current stage: GAC your custom extension assembly or copy it to "Program Files\Microsoft Visual Studio 9.0\Common7\IDE"? We will provide the readme to help other customers who may run into the same issue. Unfortunately, it appears I'm out of luck on this one. A: Do you have a copy of Framework.dll with your custom behavior in the bin directory of your web project? If not that is probably the problem. Visual Studio is looking for the implementation of the behavior. Since it's listed in your config it doesn't think to look in the other projects; it expects to find the assembly in the bin. Depending on how your project is setup, it may be able to run in debug without this assembly being put in the bin, although VS usually builds it and puts it there. But again, it depends on how things are setup. Anyway, might just want to double check at that the assembly is available at design time. A: Here's the list of steps worked for me: * *Install dll into GAC, i.e. gacutil /i Bla.dll *Get FQN of dll, i.e. gacutil /l Bla *Copy resulting FQN into Web.config *Add new service in VS *Uninstall dll from GAC, i.e. gacutil /u Bla All together only. A: Putting the assembly in the GAC would probably help, but I appreciate this isn't the answer you're looking for. Not sure where else VS will look for assemblies apart from the GAC and the directory containing devenv.exe. A: I solved this by commenting out the relevant sections in the web.config including the element that used the custom extension, the element and the element. After that I was able to add a WCF service to the project, add the lines back into the web.config and publish the project. A: if you are using framework 3.5 the Culture=neutral in small not Culture=Neutral in CAPITAL A: I had the extension class within the same project (dll) as my service class and could not get it to work. Once I moved it to another project and referenced it from the service project it worked. Just in case anyone else runs into this issue. A: I had the extension class defined in my class that implements my interface, which resulted in a "could not load" error, where WCF was unable to load my extension class. Moving the extension class definition out of the interface implementation (but still in the same project/dll) sorted out my issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/169342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: VC++ 2008, OpenProcess always returning error 5 (Access Denied) Would anyone know why MSVC++ 2008 always returns error 5 on GetLastError() when I try to call OpenProcess with PROCESS_ALL_ACCESS as my desired access? PROCESS_VM_READ works just fine. I'm an administrator on this computer and it is working fine in Dev C++. Do I need to set an option somewhere? A: Opening a process with full access rights can be a highly privileged operation if it's not a process running under you credentials or in your logon session - you'll need to follow this bit of documentation from MSDN: To open a handle to another process and obtain full access rights, you must enable the SeDebugPrivilege privilege. For more information, see Changing Privileges in a Token. Remember that even if you have a privilege, in most cases the privilege is not enabled - it has to be specifically enabled in the code that's attempting to use the privilege. A: Another thing that might be causing this is new to Vista: Windows Vista introduces protected processes to enhance support for Digital Rights Management. The system restricts access to protected processes and the threads of protected processes. The following standard access rights are not allowed from a process to a protected process: DELETE READ_CONTROL WRITE_DAC WRITE_OWNER A: Which process is it? Opening a service or a process in another user session is likely to return Access Denied (5). A process in another session will open for read but you wouldn't be able to debug it. It's one reason why Windbg has the non-intrusive attach. It works across user sessions. You're not actually debugging. It suspends all the threads and is reading the memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/169355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I compress a folder and email the compressed file in Python? I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python? A: You can use the zipfile module to compress the file using the zip standard, the email module to create the email with the attachment, and the smtplib module to send it - all using only the standard library. Python - Batteries Included If you don't feel like programming and would rather ask a question on stackoverflow.org instead, or (as suggested in the comments) left off the homework tag, well, here it is: import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='you@you.com'): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close() """ # alternative to the above 4 lines if you're using gmail server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login("username", "password") server.sendmail(sender,recipients,themsg) server.quit() """ With this function, you can just do: send_file_zipped('result.txt', ['me@me.org']) You're welcome. A: Look at zipfile for compressing a folder and it's subfolders. Look at smtplib for an email client. A: You can use zipfile that ships with python, and here you can find an example of sending an email with attachments with the standard smtplib
{ "language": "en", "url": "https://stackoverflow.com/questions/169362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Sending UDP data including hex using VB.NET As a hobby I'm interesting in programming an Ethernet-connected LED sign to scroll messages across a screen. But I'm having trouble making a UDP sender in VB.NET (I am using 2008 currently). Now the sign is nice enough to have a specifications sheet on programming for it. But an example of a line to send to it (page 3): <0x01>Z30<0x02>AA<0x06><0x1B>0b<0x1C>1<0x1A>1This message will show up on the screen<0x04> With codes such as <0x01> representing the hex character. Now, to send this to the sign I need to use UDP. However, the examples I have all encode the message as ASCII before sending, like this one (from UDP: Client sends packets to, and receives packets from, a server): Imports System.Threading Imports System.Net.Sockets Imports System.IO Imports System.Net Public Class MainClass Shared Dim client As UdpClient Shared Dim receivePoint As IPEndPoint Public Shared Sub Main() receivePoint = New IPEndPoint(New IPAddress(0), 0) client = New UdpClient(8888) Dim thread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets)) thread.Start() Dim packet As String = "client" Console.WriteLine("Sending packet containing: ") ' ' Note the following line below, would appear to be my problem. ' Dim data As Byte() = System.Text.Encoding.ASCII.GetBytes(packet) client.Send(data, data.Length, "localhost", 5000) Console.WriteLine("Packet sent") End Sub Shared Public Sub WaitForPackets() While True Dim data As Byte() = client.Receive(receivePoint) Console.WriteLine("Packet received:" & _ vbCrLf & "Length: " & data.Length & vbCrLf & _ System.Text.Encoding.ASCII.GetString(data)) End While End Sub ' WaitForPackets End Class To output a hexcode in VB.NET, I think the syntax may possibly be &H1A - to send what the specifications would define as <0x1A>. Could I modify that code, to correctly send a correctly formated packet to this sign? The answers from Grant (after sending a packet with hex in it), Hamish Smith (using a function to get hex values), and Hafthor (hardcoded chr() message into example) when attempted all did not work. So I'll research to see what else could go wrong. In theory, if this string is sent successfully, I should have a message containing "OK" back, which will help to know when it works. I have tried and am now able to monitor the packets going through. A working packet example is this (in raw hex): http://www.brettjamesonline.com/misc/forums/other/working.raw vs my version: http://www.brettjamesonline.com/misc/forums/other/failed.raw. The difference is my hex codes are still not encoded correctly, seen in this side-by-side image: http://www.brettjamesonline.com/misc/forums/other/snapshotcoding.png. I have used this code to generate the packet and send it: container = &H1 & "Z" & &H30 & &H2 & "temp.nrg" & &H1C & "1Something" & &H4 ' This did not appear to work neither 'container = Chr(&H1) & "Z" & Chr(&H30) & Chr(&H2) & Chr(&H1C) & "1Something" & Chr(&H4) '<0x01>Z00<0x02>FILENAME<0x1C>1Test to display<0x04> <- the "official" spec to send Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(container) (Full snippet: http://pastebin.com/f44417743.) A: You could put together a quickie decoder like this one: Function HexCodeToHexChar(ByVal m as System.Text.RegularExpressions.Match) As String Return Chr(Integer.Parse(m.Value.Substring("<0x".Length, 2), _ Globalization.NumberStyles.HexNumber)) End Function then use this to transform: Dim r As New System.Text.RegularExpressions.Regex("<0x[0-9a-fA-F]{2}>") Dim s As String = r.Replace("abc<0x44>efg", AddressOf HexCodeToHexChar) ' s should now be "abcDefg" you could also make an encoder function that undoes this decoding (although a little more complicated) Function HexCharToHexCode(ByVal m As Match) As String If m.Value.StartsWith("<0x") And m.Value.EndsWith(">") And m.Value.Length = "<0x??>".Length Then Return "<0<0x78>" + m.Value.Substring("<0x".Length) ElseIf Asc(m.Value) >= 0 And Asc(m.Value) <= &HFF Then Return "<0x" + Right("0" + Hex(Asc(m.Value)), 2) + ">" Else Throw New ArgumentException("Non-SBCS ANSI characters not supported") End If End Function and use this to transform: Dim r As New Regex("[^ -~]|<0x[0-9a-fA-F]{2}>") Dim s As String = r.Replace("abc"+chr(4)+"efg", AddressOf HexCharToHexCode) ' s should now be "abc<0x04>efg" or you could just build the string with the special characters in it to begin with like this: Dim packet As String = Chr(&H01) + "Z30" + Chr(&H02) + "AA" + Chr(&H06) + _ Chr(&H1B) + "0b" + Chr(&H1C) + "1" + Chr(&H1A) + _ "1This message will show up on the screen" + Chr(&H04) for sending a UDP packet, the following should suffice: Dim i As New IPEndPoint(IPAddress.Parse("192.168.0.5"), 3001) ''//Target IP:port Dim u As New UdpClient() Dim b As Byte() = Encoding.UTF8.GetBytes(s) ''//Where s is the decoded string u.Send(b, b.Length, i) A: This might help. At my company we have to communicate with our hardware using sort of a combination of ascii and hex. I use this function to hexify ip addresses before sending them to the hardware Public Function HexFromIP(ByVal sIP As String) Dim aIP As String() Dim sHexCode As String = "" aIP = sIP.Split(".") For Each IPOct As String In aIP sHexCode += Hex(Val(IPOct)).PadLeft(2, "0") Next Return sHexCode End Function And occationally I use hexSomething = Hex(Val(number)).PadLeft(2,"0") as well. I can give you the source for the whole program too, though it's designed to talk to different hardware. EDIT: Are you trying to send packets in hex, or get packets in hex? A: The UDP client sends an array of bytes. You could use a memory stream and write bytes to an array. Public Class MainClass Shared client As UdpClient Shared receivePoint As IPEndPoint Public Shared Sub Main() receivePoint = New IPEndPoint(New IPAddress(0), 0) client = New UdpClient(8888) Dim thread As Thread = New Thread(New ThreadStart(AddressOf WaitForPackets)) thread.Start() Dim packet As Packet = New Packet("client") Console.WriteLine("Sending packet containing: ") Dim data As Byte() = packet.Data client.Send(data, data.Length, "localhost", 5000) Console.WriteLine("Packet sent") End Sub Public Shared Sub WaitForPackets() While True Dim data As Byte() = client.Receive(receivePoint) Console.WriteLine("Packet received:" & _ vbCrLf & "Length: " & data.Length & vbCrLf & _ System.Text.Encoding.ASCII.GetString(data)) End While End Sub ' WaitForPackets End Class Public Class Packet Private _message As String Public Sub New(ByVal message As String) _message = message End Sub Public Function Data() As Byte() Dim ret(13 + _message.Length) As Byte Dim ms As New MemoryStream(ret, True) ms.WriteByte(&H1) '<0x01>Z30<0x02>AA<0x06><0x1B>0b<0x1C>1<0x1A>1This message will show up on the screen<0x04> ms.Write(System.Text.Encoding.ASCII.GetBytes("Z30"), 0, 3) ms.WriteByte(&H2) ms.Write(System.Text.Encoding.ASCII.GetBytes("AA"), 0, 2) ms.WriteByte(&H6) ms.Write(System.Text.Encoding.ASCII.GetBytes("0b"), 0, 2) ms.WriteByte(&H1C) ms.Write(System.Text.Encoding.ASCII.GetBytes("1"), 0, 1) ms.WriteByte(&H1A) ms.Write(System.Text.Encoding.ASCII.GetBytes(_message), 0, _message.Length) ms.WriteByte(&H4) ms.Close() Data = ret End Function End Class A: They posted libraries for a bunch of languages including Visual Basic (in the separate file). I tested the demos out with one of their signs and they work! http://support.favotech.com
{ "language": "en", "url": "https://stackoverflow.com/questions/169377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Method can be made static, but should it? ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class? A: For complex logic within a class, I have found private static methods useful in creating isolated logic, in which the instance inputs are clearly defined in the method signature and no instance side-effects can occur. All outputs must be via return value or out/ref parameters. Breaking down complex logic into side-effect-free code blocks can improve the code's readability and the development team's confidence in it. On the other hand it can lead to a class polluted by a proliferation of utility methods. As usual, logical naming, documentation, and consistent application of team coding conventions can alleviate this. A: Marking a method as static within a class makes it obvious that it doesn't use any instance members, which can be helpful to know when skimming through the code. You don't necessarily have to move it to another class unless it's meant to be shared by another class that's just as closely associated, concept-wise. A: You should do what is most readable and intuitive in a given scenario. The performance argument is not a good one except in the most extreme situations as the only thing that is actually happening is that one extra parameter (this) is getting pushed onto the stack for instance methods. A: ReSharper does not check the logic. It only checks whether the method uses instance members. If the method is private and only called by (maybe just one) instance methods this is a sign to let it an instance method. A: I hope you have already understood the difference between static and instance methods. Also, there can be a long answer and a short one. Long answers are already provided by others. My short answer: Yes, you can convert them to static methods as ReSharper suggests. There is no harm in doing so. Rather, by making the method static, you are actually guarding the method so that you do not unnecessarily slip any instance members into that method. In that way, you can achieve an OOP principle "Minimize the accessibility of classes and members". When ReSharper is suggesting that an instance method can be converted to a static one, it is actually telling you, "Why the .. this method is sitting in this class but it is not actually using any of its states?" So, it gives you food for thought. Then, it is you who can realize the need for moving that method to a static utility class or not. According to the SOLID principles, a class should have only one core responsibility. So, you can do a better cleanup of your classes in that way. Sometimes, you do need some helper methods even in your instance class. If that is the case, you may keep them within a #region helper. A: If the functions are shared across many pages, you could also put them in a base page class, and then have all asp.net pages using that functionality inherit from it (and the functions could still be static as well). A: Making a method static means you can call the method from outside the class without first creating an instance of that class. This is helpful when working with third-party vendor objects or add-ons. Imagine if you had to first create a Console object "con" before calling con.Writeline(); A: Performance, namespace pollution etc are all secondary in my view. Ask yourself what is logical. Is the method logically operating on an instance of the type, or is it related to the type itself? If it's the latter, make it a static method. Only move it into a utility class if it's related to a type which isn't under your control. Sometimes there are methods which logically act on an instance but don't happen to use any of the instance's state yet. For instance, if you were building a file system and you'd got the concept of a directory, but you hadn't implemented it yet, you could write a property returning the kind of the file system object, and it would always be just "file" - but it's logically related to the instance, and so should be an instance method. This is also important if you want to make the method virtual - your particular implementation may need no state, but derived classes might. (For instance, asking a collection whether or not it's read-only - you may not have implemented a read-only form of that collection yet, but it's clearly a property of the collection itself, not the type.) A: Static methods versus Instance methods Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that). Rule CA1822 in FxCop or Code Analysis states: "After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at runtime for each call that ensures the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue." Utility Class You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration). A: I'm sure this isn't happening in your case, but one "bad smell" I've seen in some code I've had to suffer through maintaining used a heck of a lot of static methods. Unfortunately, they were static methods that assumed a particular application state. (why sure, we'll only have one user per application! Why not have the User class keep track of that in static variables?) They were glorified ways of accessing global variables. They also had static constructors (!), which are almost always a bad idea. (I know there are a couple of reasonable exceptions). However, static methods are quite useful when they factor out domain-logic that doesn't actually depend on the state of an instance of the object. They can make your code a lot more readable. Just be sure you're putting them in the right place. Are the static methods intrusively manipulating the internal state of other objects? Can a good case be made that their behavior belongs to one of those classes instead? If you're not separating concerns properly, you may be in for headaches later. A: It helps to control namespace pollution. A: This is interesting read: http://thecuttingledge.com/?p=57 ReSharper isn’t actually suggesting you make your method static. You should ask yourself why that method is in that class as opposed to, say, one of the classes that shows up in its signature... but here is what ReSharper documentaion says: http://confluence.jetbrains.net/display/ReSharper/Member+can+be+made+static A: Just to add to @Jason True's answer, it is important to realise that just putting 'static' on a method doesn't guarantee that the method will be 'pure'. It will be stateless with regard to the class in which it is declared, but it may well access other 'static' objects which have state (application configuration etc.), this may not always be a bad thing, but one of the reasons that I personally tend to prefer static methods when I can is that if they are pure, you can test and reason about them in isolation, without having to worry about the surrounding state. A: Just my tuppence: Adding all of the shared static methods to a utility class allows you to add using static className; to your using statements, which makes the code faster to type and easier to read. For example, I have a large number of what would be called "global variables" in some code I inherited. Rather than make global variables in a class that was an instance class, I set them all as static properties of a global class. It does the job, if messily, and I can just reference the properties by name because I have the static namespace already referenced. I have no idea if this is good practice or not. I have so much to learn about C# 4/5 and so much legacy code to refactor that I am just trying to let the Roselyn tips guide me. Joey
{ "language": "en", "url": "https://stackoverflow.com/questions/169378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "414" }
Q: What is the best way to install a C# windows service that doesn't require running installutil manually? I'd like to package a C# windows service project so it can be easily installed by anyone without having to use installutil command prompt utility? Is there an easy way to configure a Visual Studio setup project to do that similar to how winforms applications are installed? A: I like to create a install project to get a nice and clean MSI installer, this should help you: http://support.microsoft.com/kb/816169 And codeproject has a good example too: http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx A: There are plenty of extra answers in this question. If the app is for basic users then the MSI is the best way to go. If it's aimed at techies then I personally prefer apps that can install and uninstall themselves, and can run as a service or like a normal app. The linked question has answers that describe this. A: For completeness sakes I'll summarise http://support.microsoft.com/kb/816169 here. You need to add a Service Installer class to your service component. This can then be called by the setup routine to add you service. You'll need to create a custom action in your Setup project to call it. The details are in the KB identified.
{ "language": "en", "url": "https://stackoverflow.com/questions/169381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Change SQL Server 2005 Server Collation I need to set up an instance of SQL Server 2005 with SQL_Latin1_General_CP850_Bin as the server collation (the vendor did not take into accounting looking at DB collation for a bunch of things so stored procedures and temp tables default to the server level and the default collation will not work). During the install for SQL Server it did not give that as an option so I left it at default and finished installing it. According to MSDN and Technet I should need to just run the following command: setup.exe /q /ACTION=RebuildDatabase /INSTANCENAME=MSSQLSERVER /SAPWD="sa-pwd" /SQLSYSADMINACCOUNTS="BUILTIN\ADMINISTRATORS" /SqlCollation=SQL_Latin1_General_CP1_CI_AI However, whenever I run the above command with my parameters I get the pop-up of the SQL Server installation wizard, accept the agreement, and then it gives me output stating how to use the command. Any idea what I can do? A: I think you're looking at instructions for SQL Server 2008. See the article here for instructions for 2005. A: If possible, I would uninstall and reinstall rather than trying to change it. Changing it without re-installing is not a simple process. To change from the default during install, just uncheck the "Hide advanced configuration options" check box on the Registration Information screen; doing that will give you a Collation Settings option about 4 screens later in the install.
{ "language": "en", "url": "https://stackoverflow.com/questions/169398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ template destructors for both primitive and complex data types In a related question I asked about creating a generic container. Using polymorphic templates seems like the right way to go. However, I can't for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of T (along with its dimensions), allocated at some other point. I would like to be able to do something like MyContainer<float> blah(); ... delete blah; and MyContainer<ComplexObjectType*> complexBlah(); ... delete complexBlah;` Can I do something like this? Can I do it without smart pointers? Again, thanks for your input. A: I'd recommend if you want to store pointers to complex types, that you use your container as: MyContainer<shared_ptr<SomeComplexType> >, and for primitive types just use MyContainer<float>. The shared_ptr should take care of deleting the complex type appropriately when it is destructed. And nothing fancy will happen when the primitive type is destructed. You don't need much of a destructor if you use your container this way. How do you hold your items in the container? Do you use an STL container, or an array on the heap? An STL container would take care of deleting itself. If you delete the array, this would cause the destructor for each element to be executed, and if each element is a shared_ptr, the shared_ptr destructor will delete the pointer it itself is holding. A: You most probably do want to use smart pointers here, it really simplifies the problem. However, just as an excercise, it's quite easy to determine if given type is pointer. Rough implementation (could be more elegant, but I dont want to introduce int2type): typedef char YesType; typedef char NoType[2]; template<typename T> struct IsPointer { typedef NoType Result; }; template<typename T> struct IsPointer<T*> { typedef YesType Result; }; template<typename T> struct MyContainer { ~MyContainer() { IsPointer<T>::Result r; Clear(&r); delete[] data; } void Clear(YesType*) { for (int i = 0; i < numElements; ++i) delete data[i]; } void Clear(NoType*) {} T* data; int numElements; }; A: It can be done, but this is pretty advanced stuff. You'll need to use something like the boost MPL library (http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html) so that you can get MyContainer's destructor to select the right kind of destructing it will need to do on individual items on the container. And you can use the boost TypeTraits library to decide what kind of deleting is required (http://www.boost.org/doc/libs/1_36_0/libs/type_traits/doc/html/index.html). I'm sure it will have a trait that will let you decide if your contained type is a pointer or not, and thus decide how it needs to be destructed. You may need to implement traits yourself for any other types you want to use in MyContainer that have any other specific deletion requirements. Good luck with it! If you solve it, show us how you did it. A: If you don't want to go with smart pointers you can try partial template specialisation, it let's you write a template that is only used when you instatiate a container with a pointer type. A: delete is used to deallocate memory previously allocated with new. You do not need to use delete here, when blah and complexBlah go out of scope they will automatically be destroyed. While yrp's answer shows you one way of using template specialization to delete the objects contained if they are pointers, and not if they aren't, this seems like a fragile solution. If you want behavior like this you are better off using Boost Pointer Container libraries, which provide this exact behavior. The reason that the standard library doesn't is because the containers themselves don't know if they control the contained pointer or not - you need to wrap the pointer in a type that does know - ie a smart pointer.
{ "language": "en", "url": "https://stackoverflow.com/questions/169404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change new projects warning level in VS2008 (Express) I like having my warning level set at W4 but all new projects start at W3. Is there some way to change the default value for warning levels for new projects? A: I don't know how to do it at the IDE but you cand always edit the new project templates at: %PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\ If you're using the express version there could be a minor variation in the path: %PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\{Version}\ProjectTemplates\ Where {Version} is the express flavor you are using, VCSExpress, VBExpress, etc. The templates are zip files, just edit the project changing: <WarningLevel>3</WarningLevel> to <WarningLevel>4</WarningLevel> A: I couldn't find any project templates or anything on my machine so I just searched in all the files for WarningLevel. I found common.js at %\Microsoft Visual Studio 9.0\VC\VCWizards\1033 Searching in the file showed WarningLevel appeared in three places, lines 672, 699 and 3354. I simply changed the three lines reading CLTool.WarningLevel = WarningLevel_3; to CLTool.WarningLevel = WarningLevel_4; When I made a new project it was set at /w4. So this worked for me, won't guarantee it won't hose your machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/169419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generic Java Framework to Manage Bidirectional Associations and Inverse Updates I've been looking for a generic way to deal with bidirectional associations and a way to handle the inverse updates in manual written Java code. For those who don't know what I'm talking about, here is an example. Below it are my current results of (unsatisfying) solutions. public class A { public B getB(); public void setB(B b); } public class B { public List<A> getAs(); } Now, when updating any end of the association, in order to maintain consistency, the other end must be updated as well. Either manually each time a.setB(b); b.getA().add(a); or by putting matching code in the setter / getter and use a custom List implementation. I've found an outdated, unmaintained project whose dependencies are no longer available (https://e-nspire-gemini.dev.java.net/). It deals with the problem by using annotations that are used to inject the necessary code automatically. Does anyone know of another framework that deals with this in a generic, unobtrusive way ala gemini? ciao, Elmar A: google collections (from google's internal code) -- http://code.google.com/p/google-collections/ is Java Generics compatible(not only compatible, uses generics very well) Class BiMap -- http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html allows for Bidirectional associations. Some of these classes are expected to make their way into JDK 7. A: Unless you abstract out the setters, you are going to have to provide some sort of event notification mechanism. If your objects are JavaBeans, then you are looking at using PropertyChangeSupport and firing property change events. If you do that (or have some other mechanism for detecting changes), then Glazed Lists provides an ObservableElementList that could easily be used to handle the association synchronization from the list end (i.e. adding A to List< A> automatically calls a.setB(b)). The other direction is easily handled using property change monitoring (or equivalent). I realize that this isn't a generic solution, but it seems like it would be an easy foundation for one. Note that something like this would require a special list implementation in the B class - no way short of AOP type solutions that you could handle it in the general case (i.e. using ArrayList or something like that). I should also point out that what you are trying to achieve is something of the holy grail of data binding. There are some decent implementations for binding at the field level (stuff like getters and setters) (see JGoodies binding and JSR 295 for examples). There is also one really good implementation for list type binding (Glazed Lists, referred to above). We use both techniques in concert with each other in almost all of our applications, but have never tried to go quite as abstract as what you are asking about. If I were designing this, I would look at something like this: AssociationBuilder.createAssociation(A a, Connector< A> ca, B b, Connector< B> cb, Synchronizer< A,B> sync) Connector is an interface that allows for a single interface for various change notification types. Synchronizer is an interface that is called to make sure both objects are in sync whenever one of them is changed. sync(ChangeInfo info, A a, B b) // make sure that b reflects current state of a and vice-versa. ChangeInfo provides data on which member changed, and what the changes actually were. We are. If you are trying to really keep this generic, then you pretty much have to punt the implementation of this up to the framework user. With the above in place, it would be possible to have a number of pre-defined Connectors and Synchronizers that meet different binding criteria. Interestingly, the above method signature is pretty similar to the JSR 295 createAutoBinding() method call. Property objects are the equivalent of Connector. JSR 295 doesn't have the Synchronizer (instead, they have a binding strategy specified as an ENUM - plus JSR 295 works only with property->property binding, trying to bind a field value of one object to that object's list membership in another object is not even on the table for them). A: To make sense, these calsses will be peers. I suggest a package-private mechanism (in the absense of friend) to keep consistency. public final class A { private B b; public B getB() { return b; } public void setB(final B b) { if (b == this.b) { // Important!! return; } // Be a member of both Bs (hence check in getAs). if (b != null) { b.addA(this); } // Atomic commit to change. this.b = b; // Remove from old B. if (this.b != null) { this.b.removeA(this); } } } public final class B { private final List<A> as; /* pp */ void addA(A a) { if (a == null) { throw new NullPointerException(); } // LinkedHashSet may be better under more demanding usage patterns. if (!as.contains(a)) { as.add(a); } } /* pp */ void removeA(A a) { if (a == null) { throw new NullPointerException(); } as.removeA(a); } public List<A> getAs() { // Copy only those that really are associated with us. List<A> copy = new ArrayList<A>(as.size()); for (A a : as) { if (a.getB() == this) { copy.add(a); } } return Collection.unmodifiableList(copy); } } (Disclaime: Not tested or even compiled.) Mostly exception safe (may leak in exception case). Thread safety, many-many, performance, libraryisation, etc., is left as an exercise to the interested reader. A: Thanks for all suggestions. But none came close to what I was looking for, I probably formulated the question in a wrong way. I was looking for a replacement for gemini, so for a way to handle this in an unobtrusive manner, without polluting the code with endless checks and special List implementations. This calls of course for an AOP based approach, as suggested by Kevin. When i looked around a little more I found a package of gemini on cnet that contain all sources and dependencies with sources. The missing sources for the dependencies was the only concern that stopped me from using it. Since now all sources are available bugs can be fixed. In case anyone looks for this: http://www.download.com/Gemini/3000-2413_4-10440077.html
{ "language": "en", "url": "https://stackoverflow.com/questions/169420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP DateTime microseconds always returns 0 this code always returns 0 in PHP 5.2.5 for microseconds: <?php $dt = new DateTime(); echo $dt->format("Y-m-d\TH:i:s.u") . "\n"; ?> Output: [root@www1 ~]$ php date_test.php 2008-10-03T20:31:26.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:27.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:27.000000 [root@www1 ~]$ php date_test.php 2008-10-03T20:31:28.000000 Any ideas? A: \DateTime::createFromFormat('U.u', microtime(true)); Will give you (at least on most systems): object(DateTime)( 'date' => '2015-03-09 17:27:39.456200', 'timezone_type' => 3, 'timezone' => 'Australia/Darwin' ) But there is a loss of precision because of PHP float rounding. It's not truly microseconds. Update This is probably the best compromise of the createFromFormat() options, and provides full precision. \DateTime::createFromFormat('0.u00 U', microtime()); gettimeofday() More explicit, and maybe more robust. Solves the bug found by Xavi. $time = gettimeofday(); \DateTime::createFromFormat('U.u', sprintf('%d.%06d', $time['sec'], $time['usec'])); A: Right, I'd like to clear this up once and for all. An explanation of how to display the ISO 8601 format date & time in PHP with milliseconds and microseconds... milliseconds or 'ms' have 4 digits after the decimal point e.g. 0.1234. microseconds or 'µs' have 7 digits after decimal. Seconds fractions/names explanation here PHP's date() function does not behave entirely as expected with milliseconds or microseconds as it will only except an integer, as explained in the php date docs under format character 'u'. Based on Lucky's comment idea (here), but with corrected PHP syntax and properly handling seconds formatting (Lucky's code added an incorrect extra '0' after the seconds) These also eliminate race conditions and correctly formats the seconds. PHP Date with milliseconds Working Equivalent of date('Y-m-d H:i:s').".$milliseconds"; list($sec, $usec) = explode('.', microtime(true)); echo date('Y-m-d H:i:s.', $sec) . $usec; Output = 2016-07-12 16:27:08.5675 PHP Date with microseconds Working Equivalent of date('Y-m-d H:i:s').".$microseconds"; or date('Y-m-d H:i:s.u') if the date function behaved as expected with microseconds/microtime()/'u' list($usec, $sec) = explode(' ', microtime()); echo date('Y-m-d H:i:s', $sec) . substr($usec, 1); Output = 2016-07-12 16:27:08.56752900 A: This has worked for me and is a simple three-liner: function udate($format='Y-m-d H:i:s.', $microtime=NULL) { if(NULL === $microtime) $microtime = microtime(); list($microseconds,$unix_time) = explode(' ', $microtime); return date($format,$unix_time) . array_pop(explode('.',$microseconds)); } This, by default (no params supplied) will return a string in this format for the current microsecond it was called: YYYY-MM-DD HH:MM:SS.UUUUUUUU An even simpler/faster one (albeit, with only half the precision) would be as follows: function udate($format='Y-m-d H:i:s.', $microtime=NULL) { if(NULL === $microtime) $microtime = microtime(true); list($unix_time,$microseconds) = explode('.', $microtime); return date($format,$unix_time) . $microseconds; } This one would print out in the following format: YYYY-MM-DD HH:MM:SS.UUUU A: This seems to work, although it seems illogical that http://us.php.net/date documents the microsecond specifier yet doesn't really support it: function getTimestamp() { return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8); } A: You can specify that your input contains microseconds when constructing a DateTime object, and use microtime(true) directly as the input. Unfortunately, this will fail if you hit an exact second, because there will be no . in the microtime output; so use sprintf to force it to contain a .0 in that case: date_create_from_format( 'U.u', sprintf('%.f', microtime(true)) )->format('Y-m-d\TH:i:s.uO'); Or equivalently (more OO-style) DateTime::createFromFormat( 'U.u', sprintf('%.f', microtime(true)) )->format('Y-m-d\TH:i:s.uO'); A: This function pulled from http://us3.php.net/date function udate($format, $utimestamp = null) { if (is_null($utimestamp)) $utimestamp = microtime(true); $timestamp = floor($utimestamp); $milliseconds = round(($utimestamp - $timestamp) * 1000000); return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp); } echo udate('H:i:s.u'); // 19:40:56.78128 Very screwy you have to implement this function to get "u" to work... :\ A: Try this and it shows micro seconds: $t = microtime(true); $micro = sprintf("%06d",($t - floor($t)) * 1000000); $d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) ); print $d->format("Y-m-d H:i:s.u"); A: date_create time: String in a format accepted by strtotime(), defaults to "now". strtotime time: The string to parse, according to the GNU » Date Input Formats syntax. Before PHP 5.0.0, microseconds weren't allowed in the time, since PHP 5.0.0 they are allowed but ignored. A: Working from Lucky's comment and this feature request in the PHP bug database, I use something like this: class ExtendedDateTime extends DateTime { /** * Returns new DateTime object. Adds microtime for "now" dates * @param string $sTime * @param DateTimeZone $oTimeZone */ public function __construct($sTime = 'now', DateTimeZone $oTimeZone = NULL) { // check that constructor is called as current date/time if (strtotime($sTime) == time()) { $aMicrotime = explode(' ', microtime()); $sTime = date('Y-m-d H:i:s.' . $aMicrotime[0] * 1000000, $aMicrotime[1]); } // DateTime throws an Exception with a null TimeZone if ($oTimeZone instanceof DateTimeZone) { parent::__construct($sTime, $oTimeZone); } else { parent::__construct($sTime); } } } $oDate = new ExtendedDateTime(); echo $oDate->format('Y-m-d G:i:s.u'); Output: 2010-12-01 18:12:10.146625 A: How about this? $micro_date = microtime(); $date_array = explode(" ",$micro_date); $date = date("Y-m-d H:i:s",$date_array[1]); echo "Date: $date:" . $date_array[0]."<br>"; Sample Output 2013-07-17 08:23:37:0.88862400 A: This should be the most flexible and precise: function udate($format, $timestamp=null) { if (!isset($timestamp)) $timestamp = microtime(); // microtime(true) if (count($t = explode(" ", $timestamp)) == 1) { list($timestamp, $usec) = explode(".", $timestamp); $usec = "." . $usec; } // microtime (much more precise) else { $usec = $t[0]; $timestamp = $t[1]; } // 7 decimal places for "u" is maximum $date = new DateTime(date('Y-m-d H:i:s' . substr(sprintf('%.7f', $usec), 1), $timestamp)); return $date->format($format); } echo udate("Y-m-d\TH:i:s.u") . "\n"; echo udate("Y-m-d\TH:i:s.u", microtime(true)) . "\n"; echo udate("Y-m-d\TH:i:s.u", microtime()) . "\n"; /* returns: 2015-02-14T14:10:30.472647 2015-02-14T14:10:30.472700 2015-02-14T14:10:30.472749 */ A: String in a format accepted by strtotime() It work! A: Inside of an application I am writing I have the need to set/display microtime on DateTime objects. It seems the only way to get the DateTime object to recognize microseconds is to initialize it with the time in format of "YYYY-MM-DD HH:MM:SS.uuuuuu". The space in between the date and time portions can also be a "T" as is usual in ISO8601 format. The following function returns a DateTime object initialized to the local timezone (code can be modified as needed of course to suit individual needs): // Return DateTime object including microtime for "now" function dto_now() { list($usec, $sec) = explode(' ', microtime()); $usec = substr($usec, 2, 6); $datetime_now = date('Y-m-d H:i:s\.', $sec).$usec; return new DateTime($datetime_now, new DateTimeZone(date_default_timezone_get())); } A: PHP documentation clearly says "Note that date() will always generate 000000 since it takes an integer parameter...". If you want a quick replacement for date() function use below function: function date_with_micro($format, $timestamp = null) { if (is_null($timestamp) || $timestamp === false) { $timestamp = microtime(true); } $timestamp_int = (int) floor($timestamp); $microseconds = (int) round(($timestamp - floor($timestamp)) * 1000000.0, 0); $format_with_micro = str_replace("u", $microseconds, $format); return date($format_with_micro, $timestamp_int); } (available as gist here: date_with_micro.php) A: Building on Lucky’s comment, I wrote a simple way to store messages on the server. In the past I’ve used hashes and increments to get unique file names, but the date with micro-seconds works well for this application. // Create a unique message ID using the time and microseconds list($usec, $sec) = explode(" ", microtime()); $messageID = date("Y-m-d H:i:s ", $sec) . substr($usec, 2, 8); $fname = "./Messages/$messageID"; $fp = fopen($fname, 'w'); This is the name of the output file: 2015-05-07 12:03:17 65468400 A: Some answers make use of several timestamps, which is conceptually wrong, and overlapping issues may occur: seconds from 21:15:05.999 combined by microseconds from 21:15:06.000 give 21:15:05.000. Apparently the simplest is to use DateTime::createFromFormat() with U.u, but as stated in a comment, it fails if there are no microseconds. So, I'm suggesting this code: function udate($format, $time = null) { if (!$time) { $time = microtime(true); } // Avoid missing dot on full seconds: (string)42 and (string)42.000000 give '42' $time = number_format($time, 6, '.', ''); return DateTime::createFromFormat('U.u', $time)->format($format); } A: date('u') is supported only from PHP 5.2. Your PHP may be older! A: This method is safer than the accepted answer: date('Y-m-d H:i:s.') . str_pad(substr((float)microtime(), 2), 6, '0', STR_PAD_LEFT) Output: 2012-06-01 12:00:13.036613 Update: Not recommended (see comments)
{ "language": "en", "url": "https://stackoverflow.com/questions/169428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "75" }
Q: Eclipse's WTP translation output How can I view the intermediate translation done to JSP and JSPX pages by WTP? I'm getting weird syntax errors in my Problems tab of Eclipse in a project that has plenty of .jspx pages. They don't affect anything in the running application (Tomcat 6.0) and they appeared only over the last 2 weeks, after an update. The reason why I'd like to view the output is that I'm using the Stripes framework at http://stripesframework.org and the errors disappear for a particular .jspx file after I remove the <stripes:errors /> line of that file. At the same time, the syntax errors only appeared after I did recent fresh install of Eclipse at work, but then an update of Eclipse at home shortly therafter. I'd like to see the output to determine whose problem this should be (WTP, Stripes, or maybe just me :). Remember that this issue is somewhat cosmetic, as it doesn't affect anything functionally. It simply spams my Problems tab in Eclipse and shows the little red X icons in the project explorer. A: Right now you'd have to add the separate automated tests download to do this, and only in the 3.1 branch, but it enables a "Show Translation" command through Ctrl+Shift+9. Beware that the translation generated isn't 100% the same as the server would create at runtime--it's not intended to be executed. Also, the most recent 3.0.3 builds contain fixes to the translator that should clear up these kinds of problems (NESTED variables + self-closing tags). 3.0.3 is due in November and should update cleanly into Ganymede SR1. A: I've seen the eclipse JSP editor get really confused over almost nothing. You said the problem goes away if you remove the tag. Does it come back if you put the tag back? I know that Eclipse 3.3 sometimes had some issues with JSP files where opening them, and forcing a save would clear the file of error messages (I haven't tried 3.4 yet). Maybe that's what's happening to you. Other than that, do you have all the proper includes / xml namespaces defined in the files? A: I'm having exactly same problem with JSP and <stripes:errors/> tag in Ganymede. With Europa, there were no errors. Now it displays a couple of weird syntax errors on the problems pane. But as Silvaran stated it's just cosmetic, since the project builds correctly and works. It's still annoying though.
{ "language": "en", "url": "https://stackoverflow.com/questions/169435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Continuous Integration setup for ruby projects on linux server I would like to use open source tools if possible. here are 2 links I found but haven't tried them - * *http://pivots.pivotallabs.com/users/chad/blog/articles/471-continuous-integration-in-a-box-exploring-tsttcpw *http://laurentbois.com/category/continuous-integration/ A: Try this CruiseControl.rb http://cruisecontrolrb.thoughtworks.com/ CruiseControl.rb is written in Ruby and designed for ruby. Another one is Hudson, it is built in Java, but it has a plugin for ruby https://hudson.dev.java.net/ A: Give Cinabox a try (I'm the author). It is intended to make this as simple as possible, and uses cruisecontrol.rb. There is a screencast and readme. If you have problems, open a ticket using the LightHouse link in the readme. Good Luck! A: There is a lightweight CI server written in Sinatra called Integrity which you might want to take a look at. I mainly used it because it supports git. Git Reference
{ "language": "en", "url": "https://stackoverflow.com/questions/169442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aren't Information Expert & Tell Don't Ask at odds with Single Responsibility Principle? Information-Expert, Tell-Don't-Ask, and SRP are often mentioned together as best practices. But I think they are at odds. Here is what I'm talking about. Code that favors SRP but violates Tell-Don't-Ask & Info-Expert: Customer bob = ...; // TransferObjectFactory has to use Customer's accessors to do its work, // violates Tell Don't Ask CustomerDTO dto = TransferObjectFactory.createFrom(bob); Code that favors Tell-Don't-Ask & Info-Expert but violates SRP: Customer bob = ...; // Now Customer is doing more than just representing the domain concept of Customer, // violates SRP CustomerDTO dto = bob.toDTO(); Please fill me in on how these practices can co-exist peacefully. Definitions of the terms, * *Information Expert: objects that have the data needed for an operation should host the operation. *Tell Don't Ask: don't ask objects for data in order to do work; tell the objects to do the work. *Single Responsibility Principle: each object should have a narrowly defined responsibility. A: I don't think that they are so much at odds as they are emphasizing different things that will cause you pain. One is about structuring code to make it clear where particular responsibilities are and reducing coupling, the other is about reducing the reasons to modify a class. We all have to make decisions each and every day about how to structure code and what dependencies we are willing to introduce into designs. We have built up a lot of useful guidelines, maxims and patterns that can help us to make the decisions. Each of these is useful to detect different kinds of problems that could be present in our designs. For any specific problem that you may be looking at there will be a sweet spot somewhere. The different guidelines do contradict each other. Just applying every piece of guidance you have heard or read will not make your design better. For the specific problem you are looking at today you need to decide what the most important factors that are likely to cause you pain are. A: You can talk about "Tell Don't Ask" when you ask for object's state in order to tell object to do something. In your first example TransferObjectFactory.createFrom just a converter. It doesn't tell Customer object to do something after inspecting it's state. I think first example is correct. A: Those classes are not at odds. The DTO is simply serving as a conduit of data from storage that is intended to be used as a dumb container. It certainly doesn't violate the SRP. On the other hand the .toDTO method is questionable -- why should Customer have this responsibility? For "purity's" sake I would have another class who's job it was to create DTOs from business objects like Customer. Don't forget these principles are principles, and when you can et away with simpler solutions until changing requirements force the issue, then do so. Needless complexity is definitely something to avoid. I highly recommend, BTW, Robert C. Martin's Agile Patterns, Practices and principles for much more in depth treatments of this subject. A: DTOs with a sister class (like you have) violate all three principles you stated, and encapsulation, which is why you're having problems here. What are you using this CustomerDTO for, and why can't you simply use Customer, and have the DTOs data inside the customer? If you're not careful, the CustomerDTO will need a Customer, and a Customer will need a CustomerDTO. TellDontAsk says that if you are basing a decision on the state of one object (e.g. a customer), then that decision should be performed inside the customer class itself. An example is if you want to remind the Customer to pay any outstanding bills, so you call List<Bill> bills = Customer.GetOutstandingBills(); PaymentReminder.RemindCustomer(customer, bills); this is a violation. Instead you want to do Customer.RemindAboutOutstandingBills() (and of course you will need to pass in the PaymentReminder as a dependency upon construction of the customer). Information Expert says the same thing pretty much. Single Responsibility Principle can be easily misunderstood - it says that the customer class should have one responsibility, but also that the responsibility of grouping data, methods, and other classes aligned with the 'Customer' concept should be encapsulated by only one class. What constitutes a single responsibility is extremely hard to define exactly and I would recommend more reading on the matter. A: Craig Larman discussed this when he introduced GRASP in Applying UML and Patterns to Object-Oriented Analysis and Design and Iterative Development (2004): In some situations, a solution suggested by Expert is undesirable, usually because of problems in coupling and cohesion (these principles are discussed later in this chapter). For example, who should be responsible for saving a Sale in a database? Certainly, much of the information to be saved is in the Sale object, and thus Expert could argue that the responsibility lies in the Sale class. And, by logical extension of this decision, each class would have its own services to save itself in a database. But acting on that reasoning leads to problems in cohesion, coupling, and duplication. For example, the Sale class must now contain logic related to database handling, such as that related to SQL and JDBC (Java Database Connectivity). The class no longer focuses on just the pure application logic of “being a sale.” Now other kinds of responsibilities lower its cohesion. The class must be coupled to the technical database services of another subsystem, such as JDBC services, rather than just being coupled to other objects in the domain layer of software objects, so its coupling increases. And it is likely that similar database logic would be duplicated in many persistent classes. All these problems indicate violation of a basic architectural principle: design for a separation of major system concerns. Keep application logic in one place (such as the domain software objects), keep database logic in another place (such as a separate persistence services subsystem), and so forth, rather than intermingling different system concerns in the same component.[11] Supporting a separation of major concerns improves coupling and cohesion in a design. Thus, even though by Expert we could find some justification for putting the responsibility for database services in the Sale class, for other reasons (usually cohesion and coupling), we'd end up with a poor design. Thus the SRP generally trumps Information Expert. However, the Dependency Inversion Principle can combine well with Expert. The argument here would be that Customer should not have a dependency of CustomerDTO (general to detail), but the other way around. This would mean that CustomerDTO is the Expert and should know how to build itself given a Customer: CustomerDTO dto = new CustomerDTO(bob); If you're allergic to new, you could go static: CustomerDTO dto = CustomerDTO.buildFor(bob); Or, if you hate both, we come back around to an AbstractFactory: public abstract class DTOFactory<D, E> { public abstract D createDTO(E entity); } public class CustomerDTOFactory extends DTOFactory<CustomerDTO, Customer> { @Override public CustomerDTO createDTO(Customer entity) { return new CustomerDTO(entity); } } A: I don't 100% agree w/ your two examples as being representative, but from a general perspective you seem to be reasoning from the assumption of two objects and only two objects. If you separate the problem out further and create one (or more) specialized objects to take on the individual responsibilities you have, and then have the controlling object pass instances of the other objects it is using to the specialized objects you have carved off, you should be able to observe a happy compromise between SRP (each responsibility has handled by a specialized object), and Tell Don't Ask (the controlling object is telling the specialized objects it is composing together to do whatever it is that they do, to each other). It's a composition solution that relies on a controller of some sort to coordinate and delegate between other objects without getting mired in their internal details.
{ "language": "en", "url": "https://stackoverflow.com/questions/169450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Bad Gateway 502 error with Apache mod_proxy and Tomcat We're running a web app on Tomcat 6 and Apache mod_proxy 2.2.3. Seeing a lot of 502 errors like this: Bad Gateway! The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET /the/page.do. Reason: Error reading from remote server If you think this is a server error, please contact the webmaster. Error 502 Tomcat has plenty of threads, so it's not thread-constrained. We're pushing 2400 users via JMeter against the app. All the boxes are sitting inside our firewall on a fast unloaded network, so there shouldn't be any network problems. Anyone have any suggestions for things to look at or try? We're heading to tcpdump next. UPDATE 10/21/08: Still haven't figured this out. Seeing only a very small number of these under load. The answers below haven't provided any magical answers...yet. :) A: Just to add some specific settings, I had a similar setup (with Apache 2.0.63 reverse proxying onto Tomcat 5.0.27). For certain URLs the Tomcat server could take perhaps 20 minutes to return a page. I ended up modifying the following settings in the Apache configuration file to prevent it from timing out with its proxy operation (with a large over-spill factor in case Tomcat took longer to return a page): Timeout 5400 ProxyTimeout 5400 Some backgound ProxyTimeout alone wasn't enough. Looking at the documentation for Timeout I'm guessing (I'm not sure) that this is because while Apache is waiting for a response from Tomcat, there is no traffic flowing between Apache and the Browser (or whatever http client) - and so Apache closes down the connection to the browser. I found that if I left the Timeout setting at its default (300 seconds), then if the proxied request to Tomcat took longer than 300 seconds to get a response the browser would display a "502 Proxy Error" page. I believe this message is generated by Apache, in the knowledge that it's acting as a reverse proxy, before it closes down the connection to the browser (this is my current understanding - it may be flawed). The proxy error page says: Proxy Error The proxy server received an invalid response from an upstream server. The proxy server could not handle the request GET. Reason: Error reading from remote server ...which suggests that it's the ProxyTimeout setting that's too short, while investigation shows that Apache's Timeout setting (timeout between Apache and the client) that also influences this. A: Sample from apache conf: #Default value is 2 minutes **Timeout 600** ProxyRequests off ProxyPass /app balancer://MyApp stickysession=JSESSIONID lbmethod=bytraffic nofailover=On ProxyPassReverse /app balancer://MyApp ProxyTimeout 600 <Proxy balancer://MyApp> BalancerMember http://node1:8080/ route=node1 retry=1 max=25 timeout=600 ......... </Proxy> A: I know this does not answer this question, but I came here because I had the same error with nodeJS server. I am stuck a long time until I found the solution. My solution just adds slash or /in end of proxyreserve apache. my old code is: ProxyPass / http://192.168.1.1:3001 ProxyPassReverse / http://192.168.1.1:3001 the correct code is: ProxyPass / http://192.168.1.1:3001/ ProxyPassReverse / http://192.168.1.1:3001/ A: I'm guessing your using mod_proxy_http (or proxy balancer). Look in your tomcat logs (localhost.log, or catalina.log) I suspect your seeing an exception in your web stack bubbling up and closing the socket that the tomcat worker is connected to. A: You can avoid global timeouts or having to virtual hosts by specifying the proxy timeouts in the ProxyPass directive as follows: ProxyPass /svc http://example.com/svc timeout=600 ProxyPassReverse /svc http://example.com/svc timeout=600 Notice timeout=600 seconds. However this does not always work when you have load balancer. In that case you must add the timeouts in both the places (tested in Apache 2.2.31) Load Balancer example: <Proxy "balancer://mycluster"> BalancerMember "http://member1:8080/svc" timeout=600 BalancerMember "http://member2:8080/svc" timeout=600 </Proxy> ProxyPass /svc "balancer://mycluster" timeout=600 ProxyPassReverse /svc "balancer://mycluster" timeout=600 A side note: the timeout=600 on ProxyPass was not required when Chrome was the client (I don;t know why) but without this timeout on ProxyPass Internet Explorer (11) aborts saying connection reset by server. My theory is that the : ProxyPass timeout is used between the client(browser) and the Apache. BalancerMember timeout is used between the Apache and the backend. To those who use Tomcat or other backed you may also want to pay attention to the HTTP Connector timeouts. A: you should be able to get this problem resolved through a timeout and proxyTimeout parameter set to 600 seconds. It worked for me after battling for a while. A: So, answering my own question here. We ultimately determined that we were seeing 502 and 503 errors in the load balancer due to Tomcat threads timing out. In the short term we increased the timeout. In the longer term, we fixed the app problems that were causing the timeouts in the first place. Why Tomcat timeouts were being perceived as 502 and 503 errors at the load balancer is still a bit of a mystery. A: You can use proxy-initial-not-pooled See http://httpd.apache.org/docs/2.2/mod/mod_proxy_http.html : If this variable is set no pooled connection will be reused if the client connection is an initial connection. This avoids the "proxy: error reading status line from remote server" error message caused by the race condition that the backend server closed the pooled connection after the connection check by the proxy and before data sent by the proxy reached the backend. It has to be kept in mind that setting this variable downgrades performance, especially with HTTP/1.0 clients. We had this problem, too. We fixed it by adding SetEnv proxy-nokeepalive 1 SetEnv proxy-initial-not-pooled 1 and turning keepAlive on all servers off. mod_proxy_http is fine in most scenarios but we are running it with heavy load and we still got some timeout problems we do not understand. But see if the above directive fits your needs. A: Most likely you should increase Timeout parameter in apache conf (default value 120 sec) A: If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout. I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html : It appears that mod_proxy considers a backend as failed only when the transport layer connection to that backend fails. Unless failonstatus/failontimeout is used. ... So, setting failontimeout is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration: ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50 This is a misconfiguration because: You are defining a balancer here, so the timeout parameter relates to the balancer (like the two others). However for a balancer, the timeout parameter is not a connection timeout (like the one used with BalancerMember), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait). So, a proper configuration is done like this * *set timeout at the BalanceMember level: <Proxy balancer://mycluster> BalancerMember http://member1:8080/svc timeout=6 ... more BalanceMembers here </Proxy> *set the failontimeout on the balancer ProxyPass /svc balancer://mycluster failontimeout=on Restart apache.
{ "language": "en", "url": "https://stackoverflow.com/questions/169453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: Should I lock an ISAM table to insert a value into a unique key field? I have an ISAm table in mySql that was created similar to this: create table mytable ( id int not null auto_increment primary key, name varchar(64) not null ); create unique index nameIndex on mytable (name); I have multiple processes inserting rows into this table. If two processes try to insert the same "name", I want to make sure that one of them either gets an error or finds the row with the matching "name". Should I lock the table and in the lock make sure that the name doesn't exist, or should I rely on the server giving an error to one of the processes that try to insert a value that already exists in the unique indexed field? I'm a bit hesitant to use a lock because I don't want to get into a deadlock situation. A: Do not bother locking, your index will prevent duplicates. You should handle the error code from your application. MySQL should return an error code of 1062 (or SQLSTATE 23000) when your unique key constraint is violated. A: By the way you described the fear of encountering a DEADLOCK, the causation may not be clearly understood (unless there is more to your querying than described in the question). A good summary someone else wrote: * *Query 1 begins by locking resource A *Query 2 begins by locking resource B *Query 1, in order to continue, needs a lock on resource B, but Query 2 is locking that resource, so Query 1 starts waiting for it to release *In the meantime, Query 2 tries to finish, but it needs a lock on resource A in order to finish, but it can't get that because Query 1 has the lock on that.
{ "language": "en", "url": "https://stackoverflow.com/questions/169459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does the iPhone timeout if a function takes too long to execute? I have a function in which I get en external resource from the web using cocoa's Url object. And it works fine on the simulator, but occasionally fails on the device itself (it's a google query so the resource obviously does exist). Which leads me to believe that there is some internal timeout barrier on the hardware, but haven't read that such a barrier exists or not. Anyone else encountered similar issues? Or knows if the timeout is documented or can be changed? A: The iPhone OS will terminate your app if it seems it has become unresponsive - basically if your main thread blocks for a few seconds. This is also important when exiting - if you save on exit you have a very small window to complete the save which is compounded by the fact the OS may be doing other things. If you take too long to exit the OS kills your app which to the user appears as if your app is failing to save. I would HIGHLY recommend that you test anything time related on hardware and not the simulator. The simulator is great for quick turnaround debugging but is not representative of performance on actual hardware. If you have any heavy lifting to do, do it on a seperate thread so the UI stays responsive to the user and OS. A: iPhone imposes a timeout for application launch. So if you perform an extensive processing in applicationDidFinishLaunching: for instance, the application will be terminated and a crash log will be produced. Unfortunately I've found no mention of it in the official documentation. After the launch process has completed, I'm not aware of any timeouts that limit function execution time. I've tried it on the device with putting sleep for 30 seconds in the main thread and it works fine. A: I noticed this timeout while reading a large file in applicationDidFinishLaunching. My app would terminate during startup. In the console, I saw the log message: Sun Mar 1 10:41:03 unknown SpringBoard[22] <Warning>: <myappid>.* failed to launch in time My solution was to use performSelector: withObject: afterDelay: 0.0 to quickly return from appliationDidFinishLaunching and queue up the file load on the runloop. This avoids setting up a new Thread and dealing with the complexity of multithreading. A: I know iPhone OS will kill an app if it uses too much memory, so I wouldn't be surprised if it uses the same policy if an app is unresponsive to events for too long. If you were writing a desktop app, the problem would manifest as a spinning rainbow beach ball cursor, and your app would not respond to mouse clicks. Mac OS X wouldn't terminate your app, but it would offer to Force Quit it if you ctrl-clicked its icon in the Dock. The main problem here is that you are tying up the event processing thread. You have two options: * *Use non-blocking I/O, so instead of doing the web request in one call you use an API which fetches the data in the background and then calls a method you specify when it's done. *Use blocking I/O on a separate thread. Do the web request just like you are doing now, but in a separate thread, then signal the main thread when you are done. A: If you are using an NSUrlRequest, make sure that the timeout interval is not reached. Your phone might have a slower internet connection than your simulator. From the doc: + (id)requestWithURL:(NSURL *)theURL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval Parameters theURL The URL for the new request. cachePolicy The cache policy for the new request. timeoutInterval The timeout interval for the new request, in seconds. Return Value The newly created URL request.
{ "language": "en", "url": "https://stackoverflow.com/questions/169470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using "~" in a path resolves as C:\ I'm trying to implement a server control that frobs a couple of files inside the web directory of an ASP.NET site. I'm using VS Web Dev Express 2008 as my IDE. When I call HttpContext.Current.Request.ApplicationPath to get a path to the web root so I can find those files, it returns C:. What the heck? Absolute paths work just fine, but I'd like to be able to feed the server control a relative directory and just let it do it's thing. What have I done wrong? public String Target { get { return _target; } set { if (value.StartsWith("~")) { // WTF? Gives me C:\? Why? _target = HttpContext.Current.Request.ApplicationPath + value.Substring(1); } else { _target = value; } } } private String _target; protected override void Render(HtmlTextWriter writer) { HtmlControl wrapper = new HtmlGenericControl("div"); int fileCount = 0; try { DirectoryInfo dir = new DirectoryInfo(_target); foreach (FileInfo f in dir.GetFiles()) { fileCount++; a = new HtmlAnchor(); a.Attributes.Add("href", f.FullName); a.InnerHtml = f.Name; wrapper.Controls.Add(a); } } catch (IOException e) { throw e; } Controls.Add(wrapper); base.Render(writer); } A: This might be because it's using the development web server, which can just serve files from any directory on your hard drive. It doesn't have any specific root. Can you run your project under IIS (assuming your version of windows supports it), and see if you get the same results? To get rid of the problem completely you could just hard code the path you want to look at in your web.config and go around any problems with what Request.ApplicationPath is returning. [EDIT] Just found out you can use HTTPContext.Current.Request.ServerVariables("APPL_PHYSICAL_PATH") to return the path of your application, on the hard disk. I'm pretty sure that's what you are looking for. If that's not right, check out all the other ServerVariables to see if you can get what you are looking for. A: How about this: Server.MapPath(ResolveUrl("~/filename")) There's also information on a page TLAnews.com titled, Understanding Paths in ASP.NET. A: The ADME Developer's Kit may be what you need if you are trying to get the directory at design time.
{ "language": "en", "url": "https://stackoverflow.com/questions/169477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# & Win32 notify when separate window is closing / closed Is there a way to attach an event to a foreign / separate window from an .NET process that when the foreign window is closed or is about to close my application can be notified? I found this http://msdn.microsoft.com/en-us/library/ms229658.aspx But that seems to only be for the .NET compact framework. I am looking for something using the .NET 2.0 framework. A: There's an article on CodeProject that looks at using global hooks to receive windows messages from other applications. Can you wait for the process to exit? Or are you stuck needing to poll and check that you can still Find the window? A: Look into SetWindowsHookEx with the WH_CBT parameter. There will be a HCBT_DESTROYWND entry.
{ "language": "en", "url": "https://stackoverflow.com/questions/169483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best Dual HD Set up for Development I've got a machine I'm going to be using for development, and it has two 7200 RPM 160 GB SATA HDs in it. The information I've found on the net so far seems to be a bit conflicted about which things (OS, Swap files, Programs, Solution/Source code/Other data) I should be installing on how many partitions on which drives to get the most benefit from this situation. Some people suggest having a separate partition for the OS and/or Swap, some don't bother. Some people say the programs should be on the same physical drive as the OS with the data on the other, some the other way around. Same with the Swap and the OS. I'm going to be installing Vista 64 bit as my OS and regularly using Visual Studio 2008, VMWare Workstation, SQL Server management studio, etc (pretty standard dev tools). So I'm asking you--how would you do it? A: If they're both going through the same disk controller, there's not going to be much difference performance-wise no matter which way you do it; if you're going to be doing lots of VM's, I would split one drive for OS and swap / Programs and Data, then keep all the VM's on the other drive. Having all the VM's on an independant drive would let you move that drive to another machine seamlessly if the host fails, or if you upgrade. A: If the drives support RAID configurations in your BIOS, you should do one of the following: RAID 1 (Mirror) - Since this is a dev machine this will give you the fault tolerance and peace of mind that your code is safe (and the environment since they are such a pain to put together). You get better performance on reads because it can read from both/either drive. You don't get any performance boost on writes though. RAID 0 - No fault tolerance here, but this is the fastest configuration because you read and write off both drives. Great if you just want as fast as possible performance and you know your code is safe elsewhere (source control) anyway. Don't worry about mutiple partitions or OS/Data configs because on a dev machine you sort of need it all anyway and you shouldn't be running heavy multi-user databases or anything anyway (like a server). If your BIOS doesn't support RAID configurations, however, then you might consider doing the OS/Data split over the two drives just to balance out their use (but as you mentioned, keep the programs on the system drive because it will help with caching). Up to you where to put the swap file (OS will give you dump files, but the data drive is probably less utilized). A: I would suggest if 160gb total capacity will cover your needs (plenty of space for OS, Applications and source code, just depends on what else you plan to put on it), then you should mirror the drives in a RAID 1 unless you will have a server that data is backed up to, an external hard drive, an online backup solution, or some other means of keeping a copy of data on more then one physical drive. If you need to use all of the drive capacity, I would suggest using the first drive for OS and Applications and second drive for data. Purely for the fact of, if you change computers at some point, the OS on the first drive doesn't do you much good and most Applications would have to be reinstalled, but you could take the entire data drive with you. As for dividing off the OS, a big downfall of this is not giving the partition enough space and eventually you may need to use partitioning software to steal some space from the other partition on the drive. It never seems to fail that you allocate a certain amount of space for the OS partition, right after install you have several gigs free space so you think you are fine, but as time goes by, things build up on that partition and you run out of space. With that in mind, I still typically do use an OS partition as it is useful when reloading a system, you can format that partition blowing away the OS but keep the rest of your data. Ways to keep the space build up from happening too fast is change the location of your my documents folder, change environment variables for items such as temp and tmp. However, there are some things that just refuse to put their data anywhere besides on the system partition. I used to use 10gb, these days I go for 20gb. Dividing your swap space can be useful for keeping drive fragmentation down when letting your swap file grow and shrink as needed. Again this is an issue though of guessing how much swap you need. This will depend a lot on the amount of memory you have and how much stuff you will be running at one time. A: Mark one drive as being your warehouse, put all of your source code, data, assets, etc. on there and back it up regularly. You'll want this to be stable and easy to recover. You can even switch My Documents to live here if wanted. The other drive should contain the OS, drivers, and all applications. This makes it easy and secure to wipe the drive and reinstall the OS every 18-24 months as you tend to have to do with Windows. If you want to improve performance, some say put the swap on the warehouse drive. This will increase OS performance, but will decrease the life of the drive. In reality it all depends on your goals. If you need more performance then you even out the activity level. If you need more security then you use RAID and mirror it. My mix provides for easy maintenance with a reasonable level of data security and minimal bit rot problems. Your most active files will be the registry, page file, and running applications. If you're doing lots of data crunching then those files will be very active as well. A: For the posters suggesting RAID - it's probably OK at 160GB, but I'd hesitate for anything larger. Soft errors in the drives reduce the overall reliability of the RAID. See these articles for the details: http://alumnit.ca/~apenwarr/log/?m=200809#08 http://permabit.wordpress.com/2008/08/20/are-fibre-channel-and-scsi-drives-more-reliable/ You can't believe everything you read on the internet, but the reasoning makes sense to me. Sorry I wasn't actually able to answer your question. A: I usually run a box with two drives. One for the OS, swap, typical programs and applications, and one for VMs, "big" apps (e.g., Adobe CS suite, anything that hits the disk a lot on startup, basically). But I also run a cheap fileserver (just an old machine with a coupla hundred gigs of disk space in RAID1), that I use to store anything related to my various projects. I find this is a much nicer solution than storing everything on my main dev box, doesn't cost much, gives me somewhere to run a webserver, my personal version control, etc. Although I admit, it really isn't doing much I couldn't do on my machine. I find it's a nice solution as it helps prevent me from spreading stuff around my workstation's filesystem at random by forcing me to keep all my work in one place where it can be easily backed up, copied elsewhere, etc. I can leave it on all night without huge power bills (it uses <50W under load) so it can back itself up to a remote site with a little script, I can connect to it from outside via SSH (so I can always SCP anything I need). But really the most important benefit is that I store nothing of any value on my workstation box (at least nothing that isn't also on the server). That means if it breaks, or if I want to use my laptop, etc. everything is always accessible. A: I would put the OS and all the applications on the first disk (1 partition). Then, put the data from the SQL server (and any other overflow data) on the second disk (1 partition). This is how I'd set up a machine without any other details about what you're building. Also make sure you have a backup so you don't lose work. It might even be worth it to mirror the two drives (if you have RAID capability) so you don't lose any progress if/when one of them fails. Also, backup to an external disk daily. The RAID won't save you when you accidentally delete the wrong thing. A: In general I'd try to split up things that are going to be doing a lot of I/O (such as if you have autosave on VS going off fairly frequently) Think of it as sort of I/O multithreading A: I've observed significant speedups by putting my virtual machines on a separate disk. Whenever Windows is doing something stupid in the VM (e.g., indexing yet again), it doesn't thrash my Mac's disk quite so badly. Another issue is that many tools (Visual Studio comes to mind) break in frustrating ways when bits of them are on the non-primary disk. Use your second disk for big random things.
{ "language": "en", "url": "https://stackoverflow.com/questions/169497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to design a high performance grid with VS 2005(specifically C#) I need to build a high performance winforms data grid using Visual Studio 2005, and I'm at a loss with where to start. I've build plenty of data grid applications, but none of those were very good when the data was constantly refreshing. The grid is going to be roughly 100 rows by 40 columns, and each cell in the grid is going to update between 1 and 2 times a second(some cells possibly more). To me, this is the biggest drawback of the out of the box data grid, the repainting isn't very efficient. Couple caveats 1) No third party vendors. This grid is backbone of all our applications, so while XCeed or Syncfusion or whatever might get us up and running faster, we'd slam into its limitations and be hosed. I'd rather put in the extra work up front, and have a grid that does exactly what we need. 2) I have access to Visual Studio 2008, so if it would be much better to start this in 2008, then I can do that. If its a tossup, I'd like to stick with 2005. So whats the best approach here? A: I would recommend the following approach if you have many cells that are updating at different rates. Rather than try to invalidate each cell each time the value changes you would be better off by limiting the refresh rate. Have a timer that fires at a predefined rate, such as 4 times per second, and then each time it fires you repaint the cells that have changed since the last time around. You can then tweak the update rate in order to find the best compromise between performance and usability with some simple testing. This has the advantage of not trying to update too often and so killing your CPU performance. It batches up changes between each refresh cycle and so two quick changes to a value that occur fractions of a second apart do not cause two refreshes when only the latest value is actually worth drawing. Note this delayed drawing only applies to the rapid updates in value and does not apply to general drawing such as when the user moves the scroll bar. In that case you should draw as fast as the scroll events occur to give a nice smooth experience. A: We use the Syncfusion grid control and from what I've seen it's pretty flexible if you take the time to modify it. I don't work with the control myself, one of my co-workers does all of the grid work but we've extended it to our needs pretty well including custom painting. I know this isn't exactly answering your question, but it writing a control like this from scratch is going always going to be much more complicated than you anticipate, regardless of your anticipations. Since it'll be constantly updating I assume it's going to be databound which will be a chore in itself, especially to get it to be highly performant. Then there's debugging it. A: Try the grid from DevExpress or ComponentOne. I know from experience that the built-in grids are never going to be fast enough for anything but the most trivial of applications. A: I am planning to build a grid control to do the same as pass time, but still haven't got time. Most of the commercial grid controls have big memory foot print and update is typically an issue. My tips would be (if you go custom control) 1. Extend a Control (not UserControl or something similar). It will give you speed, without losing much. 2. In my case I was targeting the grid to contain more data. Say a million row with some 20-100 odd columns. In such scenarios it usually makes more sense to draw it yourself. Do not try to represent each cell by some Control (like say Label, TextBox, etc). They eat up a lot of resources (window handles, memory, etc). 3. Go MVC. The idea is simple: At any given time, you can display limited amount of data, due to screen size limitations, Human eye limitation, etc So your viewport is very small even if you have gazillion rows and columns and the number of updates you have to do are no more than 5 per second to be any useful to read even if the data behind the grid id being updated gazillion times per second. Also remember even if the text/image to be displayed per cell is huge, the user is still limited by the cell size. Caching styles (generic word to represent textsizes, fonts, Colors etc), also help in such scenario depending on how many of them you will be using in your grid. There will be lot more work in getting some basic drawing (highlights, grid, boundaries, borders, etc) done to get various effects. I don't recall exactly, but there was a c# .net grid on sourceforge, which can give you a good idea of how to start. That grid offered 2 options, VirtualGrid where the model data is not held by the grid making it very lightweight, and a Real grid (traditional) where the data storage is owned by the grid itself (mostly creating a duplicate, but depends on the application) For a super-agile (in terms of updates), it might just be better to have a "VirtualGrid" Just my thoughts
{ "language": "en", "url": "https://stackoverflow.com/questions/169501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Obtain form input fields using jQuery? I have a form with many input fields. When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array? A: http://api.jquery.com/serializearray/ $('#form').on('submit', function() { var data = $(this).serializeArray(); }); This can also be done without jQuery using the XMLHttpRequest Level 2 FormData object http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#the-formdata-interface var data = new FormData([form]) A: Had a similar issue with a slight twist and I thought I'd throw this out. I have a callback function that gets the form so I had a form object already and couldn't easy variants on $('form:input'). Instead I came up with: var dataValues = {}; form.find('input').each( function(unusedIndex, child) { dataValues[child.name] = child.value; }); Its similar but not identical situation, but I found this thread very useful and thought I'd tuck this on the end and hope someone else found it useful. A: This piece of code will work instead of name, email enter your form fields name $(document).ready(function(){ $("#form_id").submit(function(event){ event.preventDefault(); var name = $("input[name='name']",this).val(); var email = $("input[name='email']",this).val(); }); }); A: $('#myForm').submit(function() { // get all the inputs into an array. var $inputs = $('#myForm :input'); // not sure if you wanted this, but I thought I'd add it. // get an associative array of just the values. var values = {}; $inputs.each(function() { values[this.name] = $(this).val(); }); }); Thanks to the tip from Simon_Weaver, here is another way you could do it, using serializeArray: var values = {}; $.each($('#myForm').serializeArray(), function(i, field) { values[field.name] = field.value; }); Note that this snippet will fail on <select multiple> elements. It appears that the new HTML 5 form inputs don't work with serializeArray in jQuery version 1.3. This works in version 1.4+ A: Associative? Not without some work, but you can use generic selectors: var items = new Array(); $('#form_id:input').each(function (el) { items[el.name] = el; }); A: jQuery's serializeArray does not include disabled fields, so if you need those too, try: var data = {}; $('form.my-form').find('input, textarea, select').each(function(i, field) { data[field.name] = field.value; }); A: Don't forget the checkboxes and radio buttons - var inputs = $("#myForm :input"); var obj = $.map(inputs, function(n, i) { var o = {}; if (n.type == "radio" || n.type == "checkbox") o[n.id] = $(n).attr("checked"); else o[n.id] = $(n).val(); return o; }); return obj A: $("#form-id").submit(function (e) { e.preventDefault(); inputs={}; input_serialized = $(this).serializeArray(); input_serialized.forEach(field => { inputs[field.name] = field.value; }) console.log(inputs) }); A: Seems strange that nobody has upvoted or proposed a concise solution to getting list data. Hardly any forms are going to be single-dimension objects. The downside of this solution is, of course, that your singleton objects are going to have to be accessed at the [0] index. But IMO that's way better than using one of the dozen-line mapping solutions. var formData = $('#formId').serializeArray().reduce(function (obj, item) { if (obj[item.name] == null) { obj[item.name] = []; } obj[item.name].push(item.value); return obj; }, {}); A: Late to the party on this question, but this is even easier: $('#myForm').submit(function() { // Get all the forms elements and their values in one step var values = $(this).serialize(); }); A: The jquery.form plugin may help with what others are looking for that end up on this question. I'm not sure if it directly does what you want or not. There is also the serializeArray function. A: I had the same problem and solved it in a different way. var arr = new Array(); $(':input').each(function() { arr.push($(this).val()); }); arr; It returns the value of all input fields. You could change the $(':input') to be more specific. A: Same solution as given by nickf, but with array input names taken into account eg <input type="text" name="array[]" /> values = {}; $("#something :input").each(function() { if (this.name.search(/\[\]/) > 0) //search for [] in name { if (typeof values[this.name] != "undefined") { values[this.name] = values[this.name].concat([$(this).val()]) } else { values[this.name] = [$(this).val()]; } } else { values[this.name] = $(this).val(); } }); A: I hope this is helpful, as well as easiest one. $("#form").submit(function (e) { e.preventDefault(); input_values = $(this).serializeArray(); }); A: Sometimes I find getting one at a time is more useful. For that, there's this: var input_name = "firstname"; var input = $("#form_id :input[name='"+input_name+"']"); A: $('#myForm').bind('submit', function () { var elements = this.elements; }); The elements variable will contain all the inputs, selects, textareas and fieldsets within the form. A: Here is another solution, this way you can fetch all data about the form and use it in a serverside call or something. $('.form').on('submit', function( e )){ var form = $( this ), // this will resolve to the form submitted action = form.attr( 'action' ), type = form.attr( 'method' ), data = {}; // Make sure you use the 'name' field on the inputs you want to grab. form.find( '[name]' ).each( function( i , v ){ var input = $( this ), // resolves to current input element. name = input.attr( 'name' ), value = input.val(); data[name] = value; }); // Code which makes use of 'data'. e.preventDefault(); } You can then use this with ajax calls: function sendRequest(action, type, data) { $.ajax({ url: action, type: type, data: data }) .done(function( returnedHtml ) { $( "#responseDiv" ).append( returnedHtml ); }) .fail(function() { $( "#responseDiv" ).append( "This failed" ); }); } Hope this is of any use for any of you :) A: If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following: $('#contentform').find('input, textarea, select').each(function(x, field) { if (field.name) { if (field.name.indexOf('[]')>0) { if (!$.isArray(data[field.name])) { data[field.name]=new Array(); } data[field.name].push(field.value); } else { data[field.name]=field.value; } } }); A: I am using this code without each loop: $('.subscribe-form').submit(function(e){ var arr=$(this).serializeArray(); var values={}; for(i in arr){values[arr[i]['name']]=arr[i]['value']} console.log(values); return false; }); A: Inspired by answers of Lance Rushing and Simon_Weaver, this is my favourite solution. $('#myForm').submit( function( event ) { var values = $(this).serializeArray(); // In my case, I need to fetch these data before custom actions event.preventDefault(); }); The output is an array of objects, e.g. [{name: "start-time", value: "11:01"}, {name: "end-time", value: "11:11"}] With the code below, var inputs = {}; $.each(values, function(k, v){ inputs[v.name]= v.value; }); its final output would be {"start-time":"11:01", "end-time":"11:01"} A: For multiple select elements (<select multiple="multiple">), I modified the solution from @Jason Norwood-Young to get it working. The answer (as posted) only takes the value from the first element that was selected, not all of them. It also didn't initialize or return data, the former throwing a JavaScript error. Here is the new version: function _get_values(form) { let data = {}; $(form).find('input, textarea, select').each(function(x, field) { if (field.name) { if (field.name.indexOf('[]') > 0) { if (!$.isArray(data[field.name])) { data[field.name] = new Array(); } for (let i = 0; i < field.selectedOptions.length; i++) { data[field.name].push(field.selectedOptions[i].value); } } else { data[field.name] = field.value; } } }); return data } Usage: _get_values($('#form')) Note: You just need to ensure that the name of your select has [] appended to the end of it, for example: <select name="favorite_colors[]" multiple="multiple"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select> A: When I needed to do an ajax call with all the form fields, I had problems with the :input selector returning all checkboxes whether or not they were checked. I added a new selector to just get the submit-able form elements: $.extend($.expr[':'],{ submitable: function(a){ if($(a).is(':checkbox:not(:checked)')) { return false; } else if($(a).is(':input')) { return true; } else { return false; } } }); usage: $('#form_id :submitable'); I've not tested it with multiple select boxes yet though but It works for getting all the form fields in the way a standard submit would. I used this when customising the product options on an OpenCart site to include checkboxes and text fields as well as the standard select box type. A: serialize() is the best method. @ Christopher Parker say that Nickf's anwser accomplishes more, however it does not take into account that the form may contain textarea and select menus. It is far better to use serialize() and then manipulate that as you need to. Data from serialize() can be used in either an Ajax post or get, so there is no issue there. A: Hope this helps somebody. :) // This html: // <form id="someCoolForm"> // <input type="text" class="form-control" name="username" value="...." /> // // <input type="text" class="form-control" name="profile.first_name" value="...." /> // <input type="text" class="form-control" name="profile.last_name" value="...." /> // // <input type="text" class="form-control" name="emails[]" value="..." /> // <input type="text" class="form-control" name="emails[]" value=".." /> // <input type="text" class="form-control" name="emails[]" value="." /> // </form> // // With this js: // // var form1 = parseForm($('#someCoolForm')); // console.log(form1); // // Will output something like: // { // username: "test2" // emails: // 0: ".@....com" // 1: "...@........com" // profile: Object // first_name: "..." // last_name: "..." // } // // So, function below: var parseForm = function (form) { var formdata = form.serializeArray(); var data = {}; _.each(formdata, function (element) { var value = _.values(element); // Parsing field arrays. if (value[0].indexOf('[]') > 0) { var key = value[0].replace('[]', ''); if (!data[key]) data[key] = []; data[value[0].replace('[]', '')].push(value[1]); } else // Parsing nested objects. if (value[0].indexOf('.') > 0) { var parent = value[0].substring(0, value[0].indexOf(".")); var child = value[0].substring(value[0].lastIndexOf(".") + 1); if (!data[parent]) data[parent] = {}; data[parent][child] = value[1]; } else { data[value[0]] = value[1]; } }); return data; }; A: All answers are good, but if there's a field that you like to ignore in that function? Easy, give the field a property, for example ignore_this: <input type="text" name="some_name" ignore_this> And in your Serialize Function: if(!$(name).prop('ignorar')){ do_your_thing; } That's the way you ignore some fields. A: Try the following code: jQuery("#form").serializeArray().filter(obje => obje.value!='').map(aobj=>aobj.name+"="+aobj.value).join("&")
{ "language": "en", "url": "https://stackoverflow.com/questions/169506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "447" }
Q: How do I iterate over a range of numbers defined by variables in Bash? How do I iterate over a range of numbers in Bash when the range is given by a variable? I know I can do this (called "sequence expression" in the Bash documentation): for i in {1..5}; do echo $i; done Which gives: 1 2 3 4 5 Yet, how can I replace either of the range endpoints with a variable? This doesn't work: END=5 for i in {1..$END}; do echo $i; done Which prints: {1..5} A: The POSIX way If you care about portability, use the example from the POSIX standard: i=2 end=5 while [ $i -le $end ]; do echo $i i=$(($i+1)) done Output: 2 3 4 5 Things which are not POSIX: * *(( )) without dollar, although it is a common extension as mentioned by POSIX itself. *[[. [ is enough here. See also: What is the difference between single and double square brackets in Bash? *for ((;;)) *seq (GNU Coreutils) *{start..end}, and that cannot work with variables as mentioned by the Bash manual. *let i=i+1: POSIX 7 2. Shell Command Language does not contain the word let, and it fails on bash --posix 4.3.42 *the dollar at i=$i+1 might be required, but I'm not sure. POSIX 7 2.6.4 Arithmetic Expansion says: If the shell variable x contains a value that forms a valid integer constant, optionally including a leading plus or minus sign, then the arithmetic expansions "$((x))" and "$(($x))" shall return the same value. but reading it literally that does not imply that $((x+1)) expands since x+1 is not a variable. A: I know this question is about bash, but - just for the record - ksh93 is smarter and implements it as expected: $ ksh -c 'i=5; for x in {1..$i}; do echo "$x"; done' 1 2 3 4 5 $ ksh -c 'echo $KSH_VERSION' Version JM 93u+ 2012-02-29 $ bash -c 'i=5; for x in {1..$i}; do echo "$x"; done' {1..5} A: This is another way: end=5 for i in $(bash -c "echo {1..${end}}"); do echo $i; done A: If you want to stay as close as possible to the brace-expression syntax, try out the range function from bash-tricks' range.bash. For example, all of the following will do the exact same thing as echo {1..10}: source range.bash one=1 ten=10 range {$one..$ten} range $one $ten range {1..$ten} range {1..10} It tries to support the native bash syntax with as few "gotchas" as possible: not only are variables supported, but the often-undesirable behavior of invalid ranges being supplied as strings (e.g. for i in {1..a}; do echo $i; done) is prevented as well. The other answers will work in most cases, but they all have at least one of the following drawbacks: * *Many of them use subshells, which can harm performance and may not be possible on some systems. *Many of them rely on external programs. Even seq is a binary which must be installed to be used, must be loaded by bash, and must contain the program you expect, for it to work in this case. Ubiquitous or not, that's a lot more to rely on than just the Bash language itself. *Solutions that do use only native Bash functionality, like @ephemient's, will not work on alphabetic ranges, like {a..z}; brace expansion will. The question was about ranges of numbers, though, so this is a quibble. *Most of them aren't visually similar to the {1..10} brace-expanded range syntax, so programs that use both may be a tiny bit harder to read. *@bobbogo's answer uses some of the familiar syntax, but does something unexpected if the $END variable is not a valid range "bookend" for the other side of the range. If END=a, for example, an error will not occur and the verbatim value {1..a} will be echoed. This is the default behavior of Bash, as well--it is just often unexpected. Disclaimer: I am the author of the linked code. A: The seq method is the simplest, but Bash has built-in arithmetic evaluation. END=5 for ((i=1;i<=END;i++)); do echo $i done # ==> outputs 1 2 3 4 5 on separate lines The for ((expr1;expr2;expr3)); construct works just like for (expr1;expr2;expr3) in C and similar languages, and like other ((expr)) cases, Bash treats them as arithmetic. A: These are all nice but seq is supposedly deprecated and most only work with numeric ranges. If you enclose your for loop in double quotes, the start and end variables will be dereferenced when you echo the string, and you can ship the string right back to BASH for execution. $i needs to be escaped with \'s so it is NOT evaluated before being sent to the subshell. RANGE_START=a RANGE_END=z echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash This output can also be assigned to a variable: VAR=`echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash` The only "overhead" this should generate should be the second instance of bash so it should be suitable for intensive operations. A: Replace {} with (( )): tmpstart=0; tmpend=4; for (( i=$tmpstart; i<=$tmpend; i++ )) ; do echo $i ; done Yields: 0 1 2 3 4 A: If you're doing shell commands and you (like I) have a fetish for pipelining, this one is good: seq 1 $END | xargs -I {} echo {} A: You can use for i in $(seq $END); do echo $i; done A: Another layer of indirection: for i in $(eval echo {1..$END}); do ∶ A: if you don't wanna use 'seq' or 'eval' or jot or arithmetic expansion format eg. for ((i=1;i<=END;i++)), or other loops eg. while, and you don't wanna 'printf' and happy to 'echo' only, then this simple workaround might fit your budget: a=1; b=5; d='for i in {'$a'..'$b'}; do echo -n "$i"; done;' echo "$d" | bash PS: My bash doesn't have 'seq' command anyway. Tested on Mac OSX 10.6.8, Bash 3.2.48 A: I've combined a few of the ideas here and measured performance. TL;DR Takeaways: * *seq and {..} are really fast *for and while loops are slow *$( ) is slow *for (( ; ; )) loops are slower *$(( )) is even slower *Worrying about N numbers in memory (seq or {..}) is silly (at least up to 1 million.) These are not conclusions. You would have to look at the C code behind each of these to draw conclusions. This is more about how we tend to use each of these mechanisms for looping over code. Most single operations are close enough to being the same speed that it's not going to matter in most cases. But a mechanism like for (( i=1; i<=1000000; i++ )) is many operations as you can visually see. It is also many more operations per loop than you get from for i in $(seq 1 1000000). And that may not be obvious to you, which is why doing tests like this is valuable. Demos # show that seq is fast $ time (seq 1 1000000 | wc) 1000000 1000000 6888894 real 0m0.227s user 0m0.239s sys 0m0.008s # show that {..} is fast $ time (echo {1..1000000} | wc) 1 1000000 6888896 real 0m1.778s user 0m1.735s sys 0m0.072s # Show that for loops (even with a : noop) are slow $ time (for i in {1..1000000} ; do :; done | wc) 0 0 0 real 0m3.642s user 0m3.582s sys 0m0.057s # show that echo is slow $ time (for i in {1..1000000} ; do echo $i; done | wc) 1000000 1000000 6888896 real 0m7.480s user 0m6.803s sys 0m2.580s $ time (for i in $(seq 1 1000000) ; do echo $i; done | wc) 1000000 1000000 6888894 real 0m7.029s user 0m6.335s sys 0m2.666s # show that C-style for loops are slower $ time (for (( i=1; i<=1000000; i++ )) ; do echo $i; done | wc) 1000000 1000000 6888896 real 0m12.391s user 0m11.069s sys 0m3.437s # show that arithmetic expansion is even slower $ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; i=$(($i+1)); done | wc) 1000000 1000000 6888896 real 0m19.696s user 0m18.017s sys 0m3.806s $ time (i=1; e=1000000; while [ $i -le $e ]; do echo $i; ((i=i+1)); done | wc) 1000000 1000000 6888896 real 0m18.629s user 0m16.843s sys 0m3.936s $ time (i=1; e=1000000; while [ $i -le $e ]; do echo $((i++)); done | wc) 1000000 1000000 6888896 real 0m17.012s user 0m15.319s sys 0m3.906s # even a noop is slow $ time (i=1; e=1000000; while [ $((i++)) -le $e ]; do :; done | wc) 0 0 0 real 0m12.679s user 0m11.658s sys 0m1.004s A: If you need it prefix than you might like this for ((i=7;i<=12;i++)); do echo `printf "%2.0d\n" $i |sed "s/ /0/"`;done that will yield 07 08 09 10 11 12 A: for i in $(seq 1 $END); do echo $i; done edit: I prefer seq over the other methods because I can actually remember it ;) A: discussion Using seq is fine, as Jiaaro suggested. Pax Diablo suggested a Bash loop to avoid calling a subprocess, with the additional advantage of being more memory friendly if $END is too large. Zathrus spotted a typical bug in the loop implementation, and also hinted that since i is a text variable, continuous conversions to-and-fro numbers are performed with an associated slow-down. integer arithmetic This is an improved version of the Bash loop: typeset -i i END let END=5 i=1 while ((i<=END)); do echo $i … let i++ done If the only thing that we want is the echo, then we could write echo $((i++)). ephemient taught me something: Bash allows for ((expr;expr;expr)) constructs. Since I've never read the whole man page for Bash (like I've done with the Korn shell (ksh) man page, and that was a long time ago), I missed that. So, typeset -i i END # Let's be explicit for ((i=1;i<=END;++i)); do echo $i; done seems to be the most memory-efficient way (it won't be necessary to allocate memory to consume seq's output, which could be a problem if END is very large), although probably not the “fastest”. the initial question eschercycle noted that the {a..b} Bash notation works only with literals; true, accordingly to the Bash manual. One can overcome this obstacle with a single (internal) fork() without an exec() (as is the case with calling seq, which being another image requires a fork+exec): for i in $(eval echo "{1..$END}"); do Both eval and echo are Bash builtins, but a fork() is required for the command substitution (the $(…) construct). A: If you're on BSD / OS X you can use jot instead of seq: for i in $(jot $END); do echo $i; done A: This works fine in bash: END=5 i=1 ; while [[ $i -le $END ]] ; do echo $i ((i = i + 1)) done A: There are many ways to do this, however the ones I prefer is given below Using seq Synopsis from man seq $ seq [-w] [-f format] [-s string] [-t string] [first [incr]] last Syntax Full command seq first incr last * *first is starting number in the sequence [is optional, by default:1] *incr is increment [is optional, by default:1] *last is the last number in the sequence Example: $ seq 1 2 10 1 3 5 7 9 Only with first and last: $ seq 1 5 1 2 3 4 5 Only with last: $ seq 5 1 2 3 4 5 Using {first..last..incr} Here first and last are mandatory and incr is optional Using just first and last $ echo {1..5} 1 2 3 4 5 Using incr $ echo {1..10..2} 1 3 5 7 9 You can use this even for characters like below $ echo {a..z} a b c d e f g h i j k l m n o p q r s t u v w x y z A: Here is why the original expression didn't work. From man bash: Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. So, brace expansion is something done early as a purely textual macro operation, before parameter expansion. Shells are highly optimized hybrids between macro processors and more formal programming languages. In order to optimize the typical use cases, the language is made rather more complex and some limitations are accepted. Recommendation I would suggest sticking with Posix1 features. This means using for i in <list>; do, if the list is already known, otherwise, use while or seq, as in: #!/bin/sh limit=4 i=1; while [ $i -le $limit ]; do echo $i i=$(($i + 1)) done # Or ----------------------- for i in $(seq 1 $limit); do echo $i done 1. Bash is a great shell and I use it interactively, but I don't put bash-isms into my scripts. Scripts might need a faster shell, a more secure one, a more embedded-style one. They might need to run on whatever is installed as /bin/sh, and then there are all the usual pro-standards arguments. Remember shellshock, aka bashdoor? A: This works in Bash and Korn, also can go from higher to lower numbers. Probably not fastest or prettiest but works well enough. Handles negatives too. function num_range { # Return a range of whole numbers from beginning value to ending value. # >>> num_range start end # start: Whole number to start with. # end: Whole number to end with. typeset s e v s=${1} e=${2} if (( ${e} >= ${s} )); then v=${s} while (( ${v} <= ${e} )); do echo ${v} ((v=v+1)) done elif (( ${e} < ${s} )); then v=${s} while (( ${v} >= ${e} )); do echo ${v} ((v=v-1)) done fi } function test_num_range { num_range 1 3 | egrep "1|2|3" | assert_lc 3 num_range 1 3 | head -1 | assert_eq 1 num_range -1 1 | head -1 | assert_eq "-1" num_range 3 1 | egrep "1|2|3" | assert_lc 3 num_range 3 1 | head -1 | assert_eq 3 num_range 1 -1 | tail -1 | assert_eq "-1" }
{ "language": "en", "url": "https://stackoverflow.com/questions/169511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2080" }
Q: What is the simplest way to set up a BIRT report viewer for a xulrunner application? I recently began using BIRT and have developed a report to use with my xulrunner application. What I haven't yet figured out is how I should deploy the viewer. It seems like BIRT mostly targets Java applications, so there are instructions for deploying on J2EE, JBoss, and other technologies -- with which I am not familiar (but I'm not developing in Java anyway). Reviewing this article on deploying BIRT and reviewing the deployment details on BIRT's web site, I'm not sure where to go. I wasn't expecting to have to add some large Java dependency for the xulrunner application --is there no way I can drop an executable in with my xulrunner app, call it from my app, and pass it a report document? (Or something else that would be simpler than learning and using J2EE, JBoss, tomcat?) A: It appears that there is a genReport.bat file in the run-time somewhere that can generate reports from the command line. This appears to be what I need, and this article describes it. A: (11/2014) I'm going to add: * *download Birt runtime from: http://www.eclipse.org/downloads/download.php?file=/birt/downloads/drops/R-R1-4_3_0-201306131152/birt-runtime-4_3_0.zip *extract somewhere and set a new Environment variable BIRT_HOME=path_to_where_you_extracted *remember to add your database library into \ReportEngine\lib , (ex: jtds.jar) *Open a console inside ReportEngine dir and run: genReport.bat -f PDF -o PATH/GENERATED_REPORTS/REPORT.pdf -F "PATH/TO/REPORT.rptdesign" And that's all what I needed to do
{ "language": "en", "url": "https://stackoverflow.com/questions/169512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Warning when using mysql_fetch_assoc in PHP Possible Duplicate: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result When I run my php page, I get this error and do not know what's wrong, can anyone help? If anyone needs more infomation, I'll post the whole code. Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in H:\Program Files\EasyPHP 2.0b1\www\test\info.php on line 16 <?PHP $user_name = "root"; $password = ""; $database = "addressbook"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "SELECT * FROM tb_address_book"; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . "<BR>"; print $db_field['First_Name'] . "<BR>"; print $db_field['Surname'] . "<BR>"; print $db_field['Address'] . "<BR>"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?> A: It generally means that you've got an error in your SQL. $sql = "SELECT * FROM myTable"; // table name only do not add tb $result = mysql_query($sql); var_dump($result); // bool(false) Obviously, false is not a MySQL resource, hence you get that error. EDIT with the code pasted now: On the line before your while loop, add this: if (!$result) { echo "Error. " . mysql_error(); } else { while ( ... ) { ... } } Make sure that the tb_address_book table actually exists and that you've connected to the DB properly. A: <?PHP $user_name = "root"; $password = ""; $database = "addressbook"; $server = "127.0.0.1"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "SELECT * FROM tb_address_book"; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ID'] . "<BR>"; print $db_field['First_Name'] . "<BR>"; print $db_field['Surname'] . "<BR>"; print $db_field['Address'] . "<BR>"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/169520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to efficiently filter a large LIstViewItemCollection? So I have a ListView with an upper limit of about 1000 items. I need to be able to filter these items using a textbox's TextChanged event. I have some code that works well for a smaller number of items (~400), but when I need to re-display a full list of all 1000 items, it takes about 4 seconds. I am not creating new ListViewItems every time. Instead, I keep a list of the full item collection and then add from that. It seems that the .Add method is taking a long time regardless. Here is a little sample: this.BeginUpdate(); foreach (ListViewItem item in m_cachedItems) { MyListView.Add(item); } this.EndUpdate; I have tried only adding the missing items (i.e., the difference between the items currently being displayed and the total list of items), but this doesn't work either. There can be a situation in which there is only one item currently displayed, the user clears the textbox, and I need to display the entire list. I am not very experienced in eeking performance out of .NET controls with a large sample like this, so I don't really know a better way to do it. Is there any way around using the .Add() method, or if not, just e better general solution? A: There is a better way, you can use the VirtualMode of the list view. That documentation should get you started. The idea is to provide information to the ListView only as it's needed. Such information is retrieved using events. All you have to do is implement those events and tell the list view how many items it contains. A: AddRange is much faster than add MyListView.AddRange(items) A: There are two things to address this: * *Turn off sorting while manipulating the list contents. *Hide the list so it doesn't try to paint. The 1st point is the biggest performance gain in list manipulation out of these two. To achieve this, just set the ListViewItemSorter to null for the duration of the modification and set it back at the end. For the 2nd option, I often draw the list to a bitmap and then show that bitmap in a PictureBox so the user doesn't see the list disappear, then just reshow the list when I'm done. A: Also note that you can hide items and so make them invisible without removing them. So add all your items the first time around and then later on you just hide the ones no longer needed and show the ones that are.
{ "language": "en", "url": "https://stackoverflow.com/questions/169529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Class property as a collection Greetings, I need to include a property in my class which is a collection of System.IO.FileInfo objects. I am not really sure how to do this and how I would add and removed objects from an instance of the the class (I would assume like any other collection). Please let me know if I need to add more information. Thank you Update: Am I approaching this the wrong way? I have read comments that adding to a collection which is a property is bad practice. If this is true what is good practice? I have a bunch of objects I need to store in a collection. The collection will be added to and removed from before a final action will be taken on it. Is this a correct approach or am I missing something? A: File is a static class. So let's assume you meant FileInfo. There are lots of ways, you can: * *Expose a private field *Use Iterators *Expose a private field through a ReadOnlyCollection<> For example, class Foo { public IEnumerable<FileInfo> LotsOfFile { get { for (int i=0; i < 100; i++) { yield return new FileInfo("C:\\" + i + ".txt"); } } } private List<FileInfo> files = new List<FileInfo>(); public List<FileInfo> MoreFiles { get { return files; } } public ReadOnlyCollection<FileInfo> MoreFilesReadOnly { get { return files.AsReadOnly(); } } } With this code, you can easily add to the property MoreFiles: Foo f = new Foo(); f.MoreFiles.Add(new FileInfo("foo.txt")); f.MoreFiles.Add(new FileInfo("BAR.txt")); f.MoreFiles.Add(new FileInfo("baz.txt")); Console.WriteLine(f.MoreFiles.Count); A: using System.Collections.ObjectModel; public class Foo { private Collection<FileInfo> files = new Collection<FileInfo>(); public Collection<FileInfo> Files { get { return files;} } } //... Foo f = new Foo(); f.Files.Add(file); A: One simple way to do this is to create a property as such (sorry for the VB.Net) Public ReadOnly Property Files As Generic.List(Of IO.File) GET Return _Files END GET END Property Where _Files is a private class variable of type Generic.List(Of IO.File), which holds the list of files. That will allow files to be added and removed by calling the functions of the List data type. Some people will probably say this is bad practice, and that you should never expose the collection itself, and instead recode all the necessary functions as separate parameters, which would basically just call the appropriate functions from your private collection. A: I just make it either a list or dictionary. I'll show both. class Example { public List<FileInfo> FileList { get; set; } public Dictionary<string, FileInfo> Files { get; set; } public Example() { FileList = new List<FileInfo>(); Files = new Dictionary<string, FileInfo>(); } } You would now use the property as if it were the actual List or Dictionary object. var obj = new Example(); obj.FileList.Add(new FileInfo("file.txt")); // List<> obj.Files.Add("file.txt", new FileInfo("file.txt")); // Dictionary<> // also obj.Files["file2.txt"] = new FileInfo("file2.txt"); // Dictionary<> // fetch var myListedFile = obj.FileList[0]; // List<> var myFile = obj.Files["file.txt"]; // Dictionary<> I prefer the dictionary approach. Note that since the property is public set, you could replace the entire list or dictionary as well. obj.Files = new Dictionary<string, FileInfo>(); // or var otherFiles = new Dictionary<string, FileInfo>(); otherFiles["otherfile.txt"] = new FileInfo("otherfile.txt"); obj.Files = otherFiles; If you made the property private set, then you could still call Add(), but not reassign the list or dictionary itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/169555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Proper nullable type checking in C#? Ok, my actual problem was this: I was implementing an IList<T>. When I got to CopyTo(Array array, int index), this was my solution: void ICollection.CopyTo(Array array, int index) { // Bounds checking, etc here. if (!(array.GetValue(0) is T)) throw new ArgumentException("Cannot cast to this type of Array."); // Handle copying here. } This worked in my original code, and still works. But it has a small flaw, which wasn't exposed till I started building tests for it, specifically this one: public void CopyToObjectArray() { ICollection coll = (ICollection)_list; string[] testArray = new string[6]; coll.CopyTo(testArray, 2); } Now, this test should pass. It throws the ArgumentException about not being able to cast. Why? array[0] == null. The is keyword always returns false when checking a variable that is set to null. Now, this is handy for all sorts of reasons, including avoiding null dereferences, etc. What I finally came up with for my type checking was this: try { T test = (T)array.GetValue(0); } catch (InvalidCastException ex) { throw new ArgumentException("Cannot cast to this type of Array.", ex); } This isn't exactly elegant, but it works... Is there a better way though? A: There is a method on Type specifically for this, try: if(!typeof(T).IsAssignableFrom(array.GetElementType())) A: The only way to be sure is with reflection, but 90% of the time you can avoid the cost of that by using array is T[]. Most people are going to pass a properly typed array in, so that will do. But, you should always provide the code to do the reflection check as well, just in case. Here's what my general boiler-plate looks like (note: I wrote this here, from memory, so this might not compile, but it should give the basic idea): class MyCollection : ICollection<T> { void ICollection<T>.CopyTo(T[] array, int index) { // Bounds checking, etc here. CopyToImpl(array, index); } void ICollection.CopyTo(Array array, int index) { // Bounds checking, etc here. if (array is T[]) { // quick, avoids reflection, but only works if array is typed as exactly T[] CopyToImpl((T[])localArray, index); } else { Type elementType = array.GetType().GetElementType(); if (!elementType.IsAssignableFrom(typeof(T)) && !typeof(T).IsAssignableFrom(elementType)) { throw new Exception(); } CopyToImpl((object[])array, index); } } private void CopyToImpl(object[] array, int index) { // array will always have a valid type by this point, and the bounds will be checked // Handle the copying here } } EDIT: Ok, forgot to point something out. A couple answers naively used what, in this code, reads as element.IsAssignableFrom(typeof(T)) only. You should also allow typeof(T).IsAssignableFrom(elementType), as the BCL does, in case a developer knows that all of the values in this specific ICollection are actually of a type S derived from T, and passes an array of type S[] A: List<T> uses this: try { Array.Copy(this._items, 0, array, index, this.Count); } catch (ArrayTypeMismatchException) { //throw exception... } A: Here is a little test of try / catch vs. reflection: object[] obj = new object[] { }; DateTime start = DateTime.Now; for (int x = 0; x < 1000; x++) { try { throw new Exception(); } catch (Exception ex) { } } DateTime end = DateTime.Now; Console.WriteLine("Try/Catch: " + (end - start).TotalSeconds.ToString()); start = DateTime.Now; for (int x = 0; x < 1000; x++) { bool assignable = typeof(int).IsAssignableFrom(obj.GetType().GetElementType()); } end = DateTime.Now; Console.WriteLine("IsAssignableFrom: " + (end - start).TotalSeconds.ToString()); The resulting output in Release mode is: Try/Catch: 1.7501001 IsAssignableFrom: 0 In debug mode: Try/Catch: 1.8171039 IsAssignableFrom: 0.0010001 Conclusion, just do the reflection check. It's worth it.
{ "language": "en", "url": "https://stackoverflow.com/questions/169562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Open source Java library to produce webpage thumbnails server-side I am searching for an open source Java library to generate thumbnails for a given URL. I need to bundle this capability, rather than call out to external services, such as Amazon or websnapr. http://www.webrenderer.com/ was mentioned in this post: Server generated web screenshots, but it is a commercial solution. I'm hoping for a Java based solution, but may need to look into executing an external process such as khtml2png, or integrating something like html2ps. Any suggestions? A: The first thing that comes to mind is using AWT to capture a screen grab (see code below). You could look at capturing the JEditorPane, the JDIC WebBrowser control or the SWT Browser (via the AWT embedding support). The latter two embed native browsers (IE, Firefox), so introduce dependencies; the JEditorPane HTML support stopped at HTML 3.2. It may be that none of these will work on a headless system. import java.awt.Component; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JLabel; public class Capture { private static final int WIDTH = 128; private static final int HEIGHT = 128; private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); public void capture(Component component) { component.setSize(image.getWidth(), image.getHeight()); Graphics2D g = image.createGraphics(); try { component.paint(g); } finally { g.dispose(); } } private BufferedImage getScaledImage(int width, int height) { BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = buffer.createGraphics(); try { g.drawImage(image, 0, 0, width, height, null); } finally { g.dispose(); } return buffer; } public void save(File png, int width, int height) throws IOException { ImageIO.write(getScaledImage(width, height), "png", png); } public static void main(String[] args) throws IOException { JLabel label = new JLabel(); label.setText("Hello, World!"); label.setOpaque(true); Capture cap = new Capture(); cap.capture(label); cap.save(new File("foo.png"), 64, 64); } } A: You're essentially asking for a complete rendering engine accessible by Java. Personally, I would save myself the hassle and call out to a child process. Otherwise, I ran into this pure Java browser: Lobo A: wasn't there a QA/test website/service which would let you specify a web page that you wanted to be rendered in a certain browser(IE, FIREFOX, SAFARI version x,y,z) and they would mail the snapshot back to you. ' I can't remember the service -- maybe other developers who frequent ajaxian might remember it ? A: Try calling ImageMagick. I know it's not a Java solution, but you can call it from Java, and there's even a Java front-end, although I've had less success with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/169573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Keeping dot files synched across machines? Like most *nix people, I tend to play with my tools and get them configured just the way that I like them. This was all well and good until recently. As I do more and more work, I tend to log onto more and more machines, and have more and more stuff that's configured great on my home machine, but not necessarily on my work machine, or my web server, or any of my work servers... How do you keep these config files updated? Do you just manually copy them over? Do you have them stored somewhere public? A: I also use subversion to manage my dotfiles. When I login to a box my confs are automagically updated for me. I also use github to store my confs publicly. I use git-svn to keep the two in sync. Getting up and running on a new server is just a matter of running a few commands. The create_links script just creates the symlinks from the .dotfiles folder items into my $HOME, and also touches some files that don't need to be checked in. $ cd # checkout the files $ svn co https://path/to/my/dotfiles/trunk .dotfiles # remove any files that might be in the way $ .dotfiles/create_links.sh unlink # create the symlinks and other random tasks needed for setup $ .dotfiles/create_links.sh A: It seems like everywhere I look these days I find a new thing that makes me say "Hey, that'd be a good thing to use DropBox for" A: Rsync is about your best solution. Examples can be found here: http://troy.jdmz.net/rsync/index.html A: I use git for this. There is a wiki/mailing list dedicated to the topic. vcs-home A: I would definetly recommend homesick. It uses git and automatically symlinks your files. homesick track tracks a new dotfile, while homesick symlink symlinks new dotfiles from the repository into your homefolder. This way you can even have more than one repository. A: You could use rsync. It works through ssh which I've found useful since I only setup new servers with ssh access. Or, create a tar file that you move around everywhere and unpack. A: I store them in my version control system. A: i use svn ... having a public and a private repository ... so as soon as i get on a server i just svn co http://my.rep/home/public and have all my dot files ... A: I store mine in a git repository, which allows me to easily merge beyond system dependent changes, yet share changes that I want as well. A: I've had pretty good luck keeping my files under a revision control system. It's not for everyone, but most programmers should be able to appreciate the benefits. Read Keeping Your Life in Subversion for an excellent description, including how to handle non-dotfile configuration (like cron jobs via the svnfix script) on multiple machines. A: I keep master versions of the files under CM control on my main machine, and where I need to, arrange to copy the updates around. Fortunately, we have NFS mounts for home directories on most of our machines, so I actually don't have to copy all that often. My profile, on the other hand, is rather complex - and has provision for different PATH settings, etc, on different machines. Roughly, the machines I have administrative control over tend to have more open source software installed than machines I use occasionally without administrative control. So, I have a random mix of manual and semi-automatic process. A: There is netskel where you put your common files on a web server, and then the client program maintains the dot-files on any number of client machines. It's designed to run on any level of client machine, so the shell scripts are proper sh scripts and have a minimal amount of dependencies. A: Svn here, too. Rsync or unison would be a good idea, except that sometimes stuff stops working and i wonder what was in my .bashrc file last week. Svn is a life saver in that case. A: Now I use Live Mesh which keeps all my files synchronized across multiple machines. A: I put all my dotfiles in to a folder on Dropbox and then symlink them to each machine. Changes made on one machine are available to all the others almost immediately. It just works. A: Depending on your environment you can also use (fully backupped) NFS shares ... A: Speaking about storing dot files in public there are http://www.dotfiles.com/ and http://dotfiles.org/ But it would be really painful to manually update your files as (AFAIK) none of these services provide any API. The latter is really minimalistic (no contact form, no information about who made/owns it etc.) A: briefcase is a tool to facilitate keeping dotfiles in git, including those with private information (such as .gitconfig). By keeping your configuration files in a git public git repository, you can share your settings with others. Any secret information is kept in a single file outside the repository (it’s up to you to backup and transport this file). -- http://jim.github.com/briefcase A: mackup https://github.com/lra/mackup Ira/mackup is a utility for Linux & Mac systems that will sync application preferences using almost any popular shared storage provider (dropbox, icloud, google drive). It works by replacing the dot files with symlinks. It also has a large library of hundreds of applications that are supported https://github.com/lra/mackup/tree/master/mackup/applications
{ "language": "en", "url": "https://stackoverflow.com/questions/169574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How can I detect a held down mouse button over a PictureBox? I need to fire an event when the mouse is above a PictureBox with the mouse button already clicked and held down. Problems: The MouseDown and MouseEnter event handlers do not work together very well. For instance once a mouse button is clicked and held down, C# will fire the MouseDown event handler, but when the cursor moves over the PictureBox the MouseEnter event does not fire, until the mouse button is realeased. A: Set up a MouseMove event within the PictureBox control: this.myPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.myPictureBox_MouseMove); Then, within your MouseMove event handler, check to see if the left mouse button (or whatever) is pressed: private void myPictureBox_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) // Do what you want to do } A: If you're trying to implement a drag-and-drop operation of some sort, the Drag... events (DragEnter, DragDrop etc.) on the receiving picture box are what you want to use. Basically, you start the drag operation using the DoDragDrop method of the source control, and then any control that you drag over will have its Drag... events raised. Search "DoDragDrop" on MSDN to see how to implement this. A: Mouse events Use the MouseDown event to just detect a down press of a mouse button and set this.Capture to true so that you then get other mouse events, even when the mouse leaves the control (i.e. you won't get a MouseLeave event because you captured the mouse). Release capture by setting this.Capture to false when MouseUp occurs. Just checking the state of the mouse This may not be relevant, but you can check System.Windows.Control.MousePosition and see if it is in the PictureBox.ClientRectangle, then check the Control.MouseButtons static property for which buttons might be down at any time. As in: if (pictureBox.ClientRectangle.Contains(pictureBox.PointToClient(Control.MousePosition))) { if ((Control.MouseButtons & MouseButtons.Left) != 0) { // Left button is down. } } A: When the mouse is pressed down most controls will then Control.Capture the mouse input. This means that all MouseMove events are sent to the original control that captured rather than the control the mouse happens to be over. This continues until the mouse loses capture which typically happens on the mouse up. If you really need to know when the mouse is over your control even when another control has captured mouse input then you only really have one way. You need to snoop the windows messages destined for other controls inside your application. To do that you need add a message filter ... Application.AddMessageFilter(myFilterClassInstance); Then you need to implement the IMessageFilter on a suitable class... public class MyFilterClass : IMessageFilter { public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_MOUSEMOVE) // Check if mouse is over my picture box! return false; } } Then you watch for mouse move events and check if they are over your picture box and do whatever it is you want to do. A: You can use the Preview Events For example say I want to detect a mousedown event on my button. The MouseDown event is not going to work because as one of the answers here, the mouse capture is sent to the main control, however what you can do is use the mouse preview event. Here is a code example I want to check when the Left Mouse Button is pressed on my Button, hence I use the PreviewMouseLeftButtonDown private void MyButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // code here } WPF has preview events for alot of other events, you can read about them here Preview Events - It particular talks about Buttons and how the mouse events interacts with it, So I highly recommend you read it A: The best way to move a Form based on mouse position and control relative position is similar to what Ian Campbell posted. private void imgMoveWindow_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Form1.ActiveForm.Left = Control.MousePosition.X - imgMoveWindow.Left - (imgMoveWindow.Size.Width/2); Form1.ActiveForm.Top = Control.MousePosition.Y - imgMoveWindow.Top - (imgMoveWindow.Size.Height/2); } } Where imgMoveWindow is a PictureBox Control. Bruno Ratnieks Sniffer Networks A: You should try MouseMove of the picture box instead of MouseEnter, MouseMove will normally fire regardless mouse button state. A: set a flag or a state on mouse down. release it on mouse up. When on mouse over fires for the picture box check your state. Now you can detect when a person is dragging something.
{ "language": "en", "url": "https://stackoverflow.com/questions/169590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What is an efficient method of paging through very large result sets in SQL Server 2005? EDIT: I'm still waiting for more answers. Thanks! In SQL 2000 days, I used to use temp table method where you create a temp table with new identity column and primary key then select where identity column between A and B. When SQL 2005 came along I found out about Row_Number() and I've been using it ever since... But now, I found a serious performance issue with Row_Number(). It performs very well when you are working with not-so-gigantic result sets and sorting over an identity column. However, it performs very poorly when you are working with large result sets like over 10,000 records and sorting it over non-identity column. Row_Number() performs poorly even if you sort by an identity column if the result set is over 250,000 records. For me, it came to a point where it throws an error, "command timeout!" What do you use to do paginate a large result set on SQL 2005? Is temp table method still better in this case? I'm not sure if this method using temp table with SET ROWCOUNT will perform better... But some say there is an issue of giving wrong row number if you have multi-column primary key. In my case, I need to be able to sort the result set by a date type column... for my production web app. Let me know what you use for high-performing pagination in SQL 2005. And I'd also like to know a smart way of creating indexes. I'm suspecting choosing right primary keys and/or indexes (clustered/non-clustered) will play a big role here. Thanks in advance. P.S. Does anyone know what stackoverflow uses? EDIT: Mine looks something like... SELECT postID, postTitle, postDate FROM (SELECT postID, postTitle, postDate, ROW_NUMBER() OVER(ORDER BY postDate DESC, postID DESC) as RowNum FROM MyTable ) as DerivedMyTable WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1 postID: Int, Identity (auto-increment), Primary key postDate: DateTime EDIT: Is everyone using Row_Number()? A: The row_number() technique should be quick. I have seen good results for 100,000 rows. Are you using row_number() similiar to the following: SELECT column_list FROM (SELECT column_list ROW_NUMBER() OVER(ORDER BY OrderByColumnName) as RowNum FROM MyTable m ) as DerivedTableName WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1 ...and do you have a covering index for the column_list and/or an index on the 'OrderByColumnName' column? A: Well, for your sample query ROW_COUNT should be pretty fast with thousands of rows, provided you have an index on your PostDate field. If you don't, the server needs to perform a complete clustered index scan on your PK, practically load every page, fetch your PostDate field, sort by it, determine the rows to extract for the result set and again fetch those rows. It's kind of creating a temp index over and over again (you might see an table/index spool in the plain). No wonder you get timeouts. My suggestion: set an index on PostDate DESC, this is what ROW_NUMBER will go over - (ORDER BY PostDate DESC, ...) As for the article you are referring to - I've done pretty much paging and stuff with SQL Server 2000 in the past without ROW_COUNT and the approach used in the article is the most efficient one. It does not work in all circumstances (you need unique or almost unique values). An overview of some other methods is here. .
{ "language": "en", "url": "https://stackoverflow.com/questions/169596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: strcat() new line, duplicate string I'm writing a function that gets the path environment variable of a system, splits up each path, then concats on some other extra characters onto the end of each path. Everything works fine until I use the strcat() function (see code below). char* prependPath( char* exeName ) { char* path = getenv("PATH"); char* pathDeepCopy = (char *)malloc(strlen(path) + 1); char* token[80]; int j, i=0; // used to iterate through array strcpy(pathDeepCopy, path); //parse and split token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0 //place in array while(token[i]!= NULL) { //ensure a pointer was found i++; token[i] = strtok(NULL, ":"); //continue to tokenize the string } for(j = 0; j <= i-1; j++) { strcat(token[j], "/"); //strcat(token[j], exeName); printf("%s\n", token[j]); //print out all of the tokens } } My shell output is like this (I'm concatenating "/which" onto everything): ... /usr/local/applic/Maple/bin/which which/which /usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which which/which Bus error (core dumped) I'm wondering why strcat is displaying a new line and then repeating which/which. I'm also wondering about the Bus error (core dumped) at the end. Has anyone seen this before when using strcat()? And if so, anyone know how to fix it? Thanks A: strtok() does not give you a new string. It mutilates the input string by inserting the char '\0' where the split character was. So your use of strcat(token[j],"/") will put the '/' character where the '\0' was. Also the last token will start appending 'which' past the end of your allocated memory into uncharted memory. You can use strtok() to split a string into chunks. But if you want to append anything onto a token you need to make a copy of the token otherwise what your appending will spill over onto the next token. Also you need to take more care with your memory allocation you are leaking memory all over the place :-) PS. If you must use C-Strings. use strdup() to copy the string. char* prependPath( char* exeName ) { char* path = getenv("PATH"); char* pathDeepCopy = strdup(path); char* token[80]; int j, i; // used to iterate through array token[0] = strtok(pathDeepCopy, ":"); for(i = 0;(token[i] != NULL) && (i < 80);++i) { token[i] = strtok(NULL, ":"); } for(j = 0; j <= i; ++j) { char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1); strcpy(tmp,token[j]); strcat(tmp,"/"); strcat(tmp,exeName); printf("%s\n",tmp); //print out all of the tokens free(tmp); } free(pathDeepCopy); } A: strtok() tokenizes in place. When you start appending characters to the tokens, you're overwriting the next token's data. Also, in general it's not safe to simply concatenate to an existing string unless you know that the size of the buffer the string is in is large enough to hold the resulting string. This is a major cause of bugs in C programs (including the dreaded buffer overflow security bugs). So even if strtok() returned brand-new strings unrelated to your original string (which it doesn't), you'd still be overrunning the string buffers when you concatenated to them. Some safer alternatives to strcpy()/strcat() that you might want to look into (you may need to track down implementations for some of these - they're not all standard): * *strncpy() - includes the target buffer size to avoid overruns. Has the drawback of not always terminating the result string *strncat() *strlcpy() - similar to strncpy(), but intended to be simpler to use and more robust (http://en.wikipedia.org/wiki/Strlcat) *strlcat() *strcpy_s() - Microsoft variants of these functions *strncat_s() And the API you should strive to use if you can use C++: the std::string class. If you use the C++ std::string class, you pretty much do not have to worry about the buffer containing the string - the class manages all of that for you. A: strtok does not duplicate the token but instead just points to it within the string. So when you cat '/' onto the end of a token, you're writing a '\0' either over the start of the next token, or past the end of the buffer. Also note that even if strtok did returning copies of the tokens instead of the originals (which it doesn't), it wouldn't allocate the additional space for you to append characters so it'd still be a buffer overrun bug. A: If you're using C++, consider boost::tokenizer as discussed over here. If you're stuck in C, consider using strtok_r because it's re-entrant and thread-safe. Not that you need it in this specific case, but it's a good habit to establish. Oh, and use strdup to create your duplicate string in one step. A: OK, first of all, be careful. You are losing memory. Strtok() returns a pointer to the next token and you are storing it in an array of chars. Instead of char token[80] it should be char *token. Be careful also when using strtok. strtok practically destroys the char array called pathDeepCopy because it will replace every occurrence of ":" with '\0'.As Mike F told you above. Be sure to initialize pathDeppCopy using memset of calloc. So when you are coding token[i] there is no way of knowing what is being point at. And as token has no data valid in it, it is likely to throw a core dump because you are trying to concat. a string to another that has no valida data (token). Perphaps th thing you are looking for is and array of pointers to char in which to store all the pointer to the token that strtok is returnin in which case, token will be like char *token[]; Hope this helps a bit. A: replace that with strcpy(pathDeepCopy, path); //parse and split token[0] = strtok(pathDeepCopy, ":");//get pointer to first token found and store in 0 //place in array while(token[i]!= NULL) { //ensure a pointer was found i++; token[i] = strtok(NULL, ":"); //continue to tokenize the string } // use new array for storing the new tokens // pardon my C lang skills. IT's been a "while" since I wrote device drivers in C. const int I = i; const int MAX_SIZE = MAX_PATH; char ** newTokens = new char [MAX_PATH][I]; for (int k = 0; k < i; ++k) { sprintf(newTokens[k], "%s%c", token[j], '/'); printf("%s\n", newtoken[j]); //print out all of the tokens } this will replace overwriting the contents and prevent the core dump. A: and don't forget to check if malloc returns NULL!
{ "language": "en", "url": "https://stackoverflow.com/questions/169610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java EE -- is it just fluff or the real stuff? I'm familiar with the LAMP stack and over the years have successfully deployed a handful of web sties based on it. I've used everything from Apache + modPerl, to PHP, to Ruby and Rails. With good use of caching my Rails site can sustain a pretty good load, but I'm not talking massive. I never really liked Java as a language, or XML for that matter, and have very much been ignoring the whole Java EE side of things. For those who have had real and direct experience in both worlds: is there something super cool about Java EE that I'm missing, or is just a bunch of hot air? What justifies the high price of the proprietary app servers? I'm not trolling here: I'm looking for concrete examples of things that Java EE really nails that are missing from modern LAMP frameworks, if such differences exist. (Modern = Rails, Django, etc). Alternatively pipe in with those things that LAMP really does better (fewer XML sit ups for one). +++++ Update October 16, 2008 I'm sad to report that most of the replies here are not helpful, and simply fall into one of two categories: "It scales because here are three examples of large web sites" and "It scales because it is really actually much better than the LAMP stack". I've done quite a bit of reading, and have concluded that Java EE only has one really good trick: transactions (thanks Will) and as for the rest you can succeed or fail on your own merit, there is nothing intrinsically in the environment to cause you to create a scalable and reliable web site, indeed Java EE has quite a few traps that make it easy to fail (for instance it is easy to start using session beans without realizing that you are paying now for quite a bit of JMS traffic that perhaps could have been avoided with a different design.) Useful discussion * *http://www.subbu.org/blog/2007/10/large-scale-web-site-development *http://highscalability.com/ *http://www.oreillynet.com/onlamp/blog/2004/07/php_scales.html *http://www.schlossnagle.org/~george/blog/index.php?/archives/29-Why-PHP-Scales-A-Cranky,-Snarky-Answer.html *http://blogs.law.harvard.edu/philg/2003/09/20/ A: Amazon.com, ebay, google -- they all use a subset of Java EE and they are pretty successful. They all use servlets and JSPs If you try to use EJB 1.1 or EJB 2.0, then the scalability is hit. Developer productivity is also reduced as a result of making unit testing harder. With EJB 3.0, developer productivity and application scalability improves. So, depending on what your application needs, use only those pieces of Java EE that makes sense for you. Do a sample POC(proof of concept) using only those pieces that you intend to use. This POC will show how well the application will work. NEW Java EE application servers don't always need a lot of XML. They will let you use annotation to do dependency injection and database mapping. More than 50% of all enterprise development happens on Java EE (when I say that, it is mostly using subset of the Java EE stack. someone might use stateless SESSION bean EJBs, someone might just JNDI, someone might use MESSAGE DRIVEN BEAN EJB). Hope it helps. A: You can build really huge and scalable applications with Java EE, and it's widely used in enterprise computing. But: My experience with Java EE was pretty bad because it seemed like 90% of the work my team was doing was boilerplate and plumbing. Our productivity at the time was much, much lower than it could have been had we used a different technology stack. A: Almost all the answers mention what it takes to build a Java EE web application. Let me mention another important consideration. Most enterprises have significant back-office requirements, where an enterprise app has to integrate with other apps. This can range from hooking up to some crufty old COBOL mainframe program, to a LAMP stack to a little Access app that some accountant whipped up at night, etc. Usually this means you will need some sort of messaging solution in order to get 2 or more apps to hook up together. In my experience, I've found the Java EE world stretches itself further to deal with these integration problems than your typical LAMP stack. A: The core of Java EE is simply a bunch of interfaces that have implementations provided by a container. Most applications do not use all of the Java EE specification. There are two main aspects of the Java EE that people think of when they discuss it: EJBs and Servlets. I have no experience whatsoever with EJBs. I use the Spring Framework and as such it provides all of the "plumbing and boilerplate" code referenced as in Ben Collins' answer. It provides all that we needed EJBs to do, and then some (transactions with database access is what we use its special features for, although we use its IOC container as well for the Servlet portion). Servlets, however, are fantastic. They are a very good and proven technology. The core of a Servlet is a request and response cycle: a user requests something, and the server intercepts the request and provides a response based on it. A chain of requests and responses can be kept track of by means of a Session for a single user. As for the high price of proprietary app servers, I have no idea why the price is so high, but Apache Tomcat is a very good Servlet container and is free. We use Tomcat for testing and WebSphere for deployment (Websphere is provided by our client for the apps' use). Unfortunately it's only Websphere 6 (update 11, as we found out to our dismay, which doesn't have the fix for update 13 which enables JSTL functions to operate properly when contained inside a JSP tag), so we're forced to use Java 1.4x, not Java 1.5+. There are also several frameworks (see the Spring framework referenced before for an example) that allow easy Servlet development. If you're just using this for HTTP/HTML, there are a large number of frameworks to easily aid you in this development. A: The key differentiator that Java EE offers over the LAMP stack can be boiled down to a single word. Transactions. Most smaller systems simply rely on the transaction system supplied by the database, and for many applications that is (obviously) quite satisfactory. But each Java EE server includes a distributed transaction manager. This lets you do more complicated things, across diverse systems, safely and reliably. The most simple example of this is the simple scenario of taking a record from a database, putting it on a messaging queue (JMS), and then deleting that row from the database. This simple case involves two separate systems, and can not reliably be done out side of a transaction. For example, you can put the row on to the message queue, but (due to a system failure) not remove the row from the database. You can see how having a transaction with the JMS provider and a separate transaction with the database doesn't really solve the problem, as the transactions are not linked together. Obviously this simple scenario can be worked around, a dealt with, etc. The nice thing with Java EE, though, is that you don't have to deal with these kind of issues -- the container gets to deal with them. And, again, not every problem requires this level o transaction handling. But for those that do, it's invaluable. And once you get used to using them, you'll find the transaction management of a Java EE server to be a great asset. A: The big gun Java EE web servers (Jboss, WebSphere, WebLogic etc), and Windows Server/IIS/ASP.NET are truly in a different league in scalability and performance than your typical lamp stack. My team is responsible for one of the largest telecomunications commerce sites in the united states, handling millions of hits per day (One of our databases is over 1000TB in size, to give you some perspective). We use a combination of ASP.NET and WebSphere as well as SAP ISA (Which is also a Java EE solution) for different sections of our site, there is absolutely no way the LAMP stack could handle this kind of load without scaling to massive amounts of hardware....The .NET stack section handles the majority of the load and runs on only 32 servers. We also don't do anything fancy, such as using a memcached type solution, or static HTTP cacheing...we do cache SOAP calls and database calls on the individual app servers, but no use of an in memory database etc...our platform can handle it so far. So yeah, its apples to oranges to compare this kind of stuff to LAMP. A: Java EE and other program languages must be treated just like any other tool. Yes, it's been used in enterprise environment and it takes good craftsmanship to get these tools to work "perfectly" and knowing when to use it. I'm currently working on a Mainframe environment and Java EE is used to some extent. If high-speed transaction is involved, Java EE would be my last choice. If multi-platform interoperability is needed, then Java EE, XML and Web Services would be more appropriate. A: In terms of scalability, Java EE gives you huge choices that you don't have with a LAMP stack, or RUBY. All of the choices revolve around N-tier applications, while most LAMP and ruby applications are 2 tier. I'm developing an application, and plan on allowing people access to the API over the net. Java EE will allow me to easily scale the middle tier, without impacting the UI tier. As I add interfaces to my application, I can scale the middle tier very easily. A LAMP stack has no concept of this, built in. So I have to interfaces, the web UI, and the SOAP API. Now I want a rest API. Okay...Build that interface to hit the middle tier as well.. and add more computers to the cluster.. or go multicluster doesn't really matter. This middle tier is all EJB, a faster protocol then SOAP in many ways. Now let's say that I want to add the ability to SMS text my users. I also need to do this based on what they set, and that comes from the database. Scalability wise, I want to disconnect the actual sending of the text, from the realization the applications wants to send it. This screams JMS. I can use a Timer Bean to go off every X amount of time, and figure out what messages need to be sent, and put each message into JMS. Now I can manage the queue and how many processors are working on it etc. I can see how many texts are going out. I can even put the receivers on another box, resulting in little impact on my other servers performance wise. Scaling wise, I can see which of my EJB's are getting hit the most, and add more resources to those, while removing resources form others. I can do that with the JMS queues, and every other part of the Java EE stack of technologies. Not only do I get scalability, I get management of my servers resources. Since LAMP and Ruby don't yet have a JMS like queue for async processing, or the ability to easily put business logic in a separate tier they can be harder to scale with multiple interfaces. What do you have to do rip out the logic, and make it available to a different interface? Let's say that now you not only provide a Web UI, but a desktop UI, an IVR Interface and a SOAP interface for your website? A: Scalability and other matters aside, here's one simple thing that wasn't mentioned, which can be an advantage: it's Java. * *There's a staggering amount of 3rd party libraries available for Java, both proprietary and open-source. Now, I'm sure there are huge free libraries for Perl, Ruby, PHP, etc. - but when it comes to commercial libraries for more niche application areas, they don't come close to Java (and .NET, and probably C++). Whether you need any special 3rd party libraries of course depends solely on what kind of application you are building. *I think there are more Java developers in the world than developers for any other platform. (Maybe I'm wrong but this is what I've heard sometimes.) When choosing a platform in a commercial setting, either might turn out important.
{ "language": "en", "url": "https://stackoverflow.com/questions/169620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Is it possible to order by any column given a stored procedure parameter in SQL Server? I was looking into sorting tables by a column designated given some input, and from what I've found, there is no easy way to do this. The best I've found is a switch statement: SELECT Column1, Column2, Column3, Column4 FROM Table ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1 WHEN @OrderBY = 'Column2' THEN Column2 WHEN @OrderBY = 'Column3' THEN Column3 WHEN @OrderBY = 'Column4' THEN Column4 Is it possible to do this without having a CASE statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy. The only way I've been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain. A: You have two choices: * *As you have implemented above *Or generate dynamic sql and execute using sp_executesql A: I generally convert the stored procedure to a function that returns a table ( so you can select FROM it ... and add the dynamic order by columns to it in the application code: Select * From myTableFUnction() Order by 1, 2, 3, 6 <-- defined by application code in the SQL for the query Ron A: The RANK feature of SQL Server and Oracle can improve performance and makes the code a little cleaner: SQL: DECLARE @column varchar(10) SET @column = 'D' SELECT * FROM Collection.Account AS A ORDER BY CASE WHEN @column = 'A' THEN (RANK() OVER(ORDER BY A.Code ASC)) WHEN @column = 'D' THEN (RANK() OVER(ORDER BY A.Code DESC)) END A: You already write the correct syntax: SELECT Column1, Column2, Column3 FROM SOME_TABLE ORDER BY 1,2,3 try it A: In this case, unless you have an extremely large dataset and you need to leverage the power of the database server (thin client, weak client machine, etc), it is best to sort within the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/169624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regex to check if valid URL that ends in .jpg, .png, or .gif I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif. A: (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))? That's a (slightly modified) version of the official URI parsing regexp from RFC 2396. It allows for #fragments and ?querystrings to appear after the filename, which may or may not be what you want. It also matches any valid domain, including localhost, which again might not be what you want, but it could be modified. A more traditional regexp for this might look like the below. ^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$ |-------- domain -----------|--- path ---|-- extension ---| EDIT See my other comment, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for karma-whoring completeness reasons. A: (http(s?):)([/|.|\w|\s|-])*\.(?:jpg|gif|png) worked really well for me. This will match URLs in the following forms: https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.jpg https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.jpg https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.gif https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.gif https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.gif https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png http://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.png https://farm4.staticflickr.com/3894/15008518202-c265dfa55f-h.png https://farm4.staticflickr.com/3894/15008518202.c265dfa55f.h.png Check this regular expression against the URLs here: http://regexr.com/3g1v7 A: Actually. Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting aren't images. Try performing a HEAD request on it, and see what content-type it actually is. A: Here's the basic idea in Perl. Fetch the URL and see what it says in the Content-type header: use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $url = "http://www.example.com/logo.png"; my $response = $ua->head( $url ); my( $class, $type ) = split m|/|, lc $response->content_type; print "It's an image!\n" if $class eq 'image'; If you need to inspect just the URL without accessing it, use a solid library for it rather than trying to handle all the odd situations yourself: use URI; my $url = "http://www.example.com/logo.png"; my $uri = URI->new( $url ); my $last = ( $uri->path_segments )[-1]; my( $extension ) = $last =~ m/\.([^.]+)$/g; print "My extension is $extension\n"; And here's a Mojolicious example: use Mojo::URL; my $url = "http://www.example.com/logo.png"; my( $extension ) = Mojo::URL->new($url)->path->parts->[-1] =~ m/\.([^.]+)$/g; print "My extension is $extension\n"; Good luck, :) A: If you really want to be sure, grabbing the first kilobyte or two of the given URL should be sufficient to determine everything you need to know about the image. Here's an example of how you can get that information, using Python, and here's an example of it being put to use, as a Django form field which allows you to easily validate an image's existence, filesize, dimensions and format, given its URL. A: In general, you're better off validating URLs using built-in library or framework functions, rather than rolling your own regular expressions to do this - see What is the best regular expression to check if a string is a valid URL for details. If you are keen on doing this, though, check out this question: Getting parts of a URL (Regex) Then, once you're satisfied with the URL (by whatever means you used to validate it), you could either use a simple "endswith" type string operator to check the extension, or a simple regex like (?i)\.(jpg|png|gif)$ A: (http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png) This will mach all images from this string: background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto; <div id="divbg" style="background-color:#ff0000"><img id="bg" src="../res/img/temp/634043/original/cc3d8715eed0c.jpg" width="100%" height="100%" /></div> background-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png); background: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3 _d8715eed0c.jpg) repeat fixed left top; cursor: auto; background: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto; Test your regex here: https://regex101.com/r/l2Zt7S/1 A: I am working in Javascript based library (React). The below regex is working for me for the URL with image extension. [^\\s]+(.*?)\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$ Working URL`s are: https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg https://images.pexels.com/photos/674010/pexels-photo-674010.jpg https://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG http://www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG www.images.pexels.com/photos/674010/pexels-photo-674010.JPEG images.pexels.com/photos/674010/pexels-photo-674010.JPEG Got the solution from: https://www.geeksforgeeks.org/how-to-validate-image-file-extension-using-regular-expression/ A: Use FastImage - it'll grab the minimum required data from the URL to determine if it's an image, what type of image and what size. A: Addition to Dan's Answer. If there is an IP address instead of domain. Change regex a bit. (Temporary solution for valid IPv4 and IPv6) ^https?://(?:[a-z0-9\-]+\.)+[a-z0-9]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$ However this can be improved, for IPv4 and IPv6 to validate subnet range(s). A: This expression will match all the image urls - ^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+(?:png|jpg|jpeg|gif|svg)+$ Examples - Valid - https://itelligencegroup.com/wp-content/usermedia/de_home_teaser-box_puzzle_in_the_sun.png http://sweetytextmessages.com/wp-content/uploads/2016/11/9-Happy-Monday-images.jpg example.com/de_home_teaser-box_puzzle_in_the_sun.png www.example.com/de_home_teaser-box_puzzle_in_the_sun.png https://www.greetingseveryday.com/wp-content/uploads/2016/08/Happy-Independence-Day-Greetings-Cards-Pictures-in-Urdu-Marathi-1.jpg http://thuglifememe.com/wp-content/uploads/2017/12/Top-Happy-tuesday-quotes-1.jpg https://1.bp.blogspot.com/-ejYG9pr06O4/Wlhn48nx9cI/AAAAAAAAC7s/gAVN3tEV3NYiNPuE-Qpr05TpqLiG79tEQCLcBGAs/s1600/Republic-Day-2017-Wallpapers.jpg Invalid - https://www.example.com http://www.example.com www.example.com example.com http://blog.example.com http://www.example.com/product http://www.example.com/products?id=1&page=2 http://www.example.com#up http://255.255.255.255 255.255.255.255 http://invalid.com/perl.cgi?key= | http://web-site.com/cgi-bin/perl.cgi?key1=value1&key2 http://www.siteabcd.com:8008 A: Reference: See DecodeConfig section on the official go lang image lib docs here I believe you could also use DecodeConfig to get the format of an image which you could then validate against const types like jpeg, png, jpg and gif ie import ( "encoding/base64" "fmt" "image" "log" "strings" "net/http" // Package image/jpeg is not used explicitly in the code below, // but is imported for its initialization side-effect, which allows // image.Decode to understand JPEG formatted images. Uncomment these // two lines to also understand GIF and PNG images: // _ "image/gif" // _ "image/png" _ "image/jpeg" ) func main() { resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg") if err != nil { log.Fatal(err) } defer resp.Body.Close() data, _, err := image.Decode(resp.Body) if err != nil { log.Fatal(err) } reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)) config, format, err := image.DecodeConfig(reader) if err != nil { log.Fatal(err) } fmt.Println("Width:", config.Width, "Height:", config.Height, "Format:", format) } format here is a string that states the file format eg jpg, png etc A: Just providing a better solution. You can just validate the uri and check the format then: public class IsImageUriValid { private readonly string[] _supportedImageFormats = { ".jpg", ".gif", ".png" }; public bool IsValid(string uri) { var isUriWellFormed = Uri.IsWellFormedUriString(uri, UriKind.Absolute); return isUriWellFormed && IsSupportedFormat(uri); } private bool IsSupportedFormat(string uri) => _supportedImageFormats.Any(supportedImageExtension => uri.EndsWith(supportedImageExtension)); } A: const url = "https://www.laoz.com/image.png"; const acceptedImage = [".png", ".jpg", ".gif"]; const extension = url.substring(url.lastIndexOf(".")); const isValidImage = acceptedImage.find((m) => m === extension) != null; console.log("isValidImage", isValidImage); console.log("extension", extension); A: ^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))
{ "language": "en", "url": "https://stackoverflow.com/questions/169625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: DateTime, DateTime? and LINQ When I retrieve a record using LINQ that has a DateTime field only the ToString() is available. Where are all the other DateTime methods? I have to Convert.ToDateTime the DateTime? that the Field returns? What is the difference between (DateTime) and (DateTime?) A: In SQL, DateTimes are allowed to be null. In C# DateTimes cannot be null. You can read a little bit about nullable value types. Since value typed variables cannot be null, a generic class was created to handle this situation. It is called Nullable<> and it is commonly written with a question mark after the type. In order to use these values you will want to check the .HasValue property. It is a boolean that knows whether there is a value in the object or it is null. Once you have checked that the .HasValue property is true, you can safely use the .Value property. The .Value property will be of type DateTime. A: In SQL, you have the DateTime field set to Allow Null. Then in LINQ, when you're going to access the field, .NET doesn't know if the field is really a date or not, which is why you have to Convert.ToDateTime() before any date methods become available to you. If the field will always contain a date, set the database column to NOT NULL and you should be fine. A: If by DateTime? you mean a Nullable<DateTime>, then you can get the DateTime value via the DateTime?.Value property. A: The namespace collision aside, I know that SQL's datetime has a different epoch (and therefore a different range of valid dates) than C# datetime. Try to send a new DateTime() to a stored procedure and see what I mean.
{ "language": "en", "url": "https://stackoverflow.com/questions/169637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is there a way to implement algebraic types in Java? Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example: public abstract class A {} public final class B extends A {} public final class C extends A {} public final class D extends A {} Can I somehow enforce that no other subclasses of A can ever be created? A: Give class A a constructor with package-level accessibility (and no other constructors). Thanks, Dave L., for the bit about no other constructors. A: You probably want an enum (Java >= 1.5). An enum type can have a set of fixed values. And it has all the goodies of a class: they can have fields and properties, and can make them implement an interface. An enum cannot be extended. Example: enum A { B, C, D; public int someField; public void someMethod() { } } A: You could put class A,B,C,D in a seperate package and make class A not public. A: Church encoding to the rescue: public abstract class A { public abstract <R> R fold(R b, R c, R d); } There are only three implementations possible: public final class B extends A { public <R> R fold(R b, R c, R d) { return b; } } public final class C extends A { public <R> R fold(R b, R c, R d) { return c; } } public final class D extends A { public <R> R fold(R b, R c, R d) { return d; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/169662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Persisting Printer Settings What is the best way to persist/save printer settings in .Net? There used to be a bug in .Net 1.1 in the serialization of the PrinterSetting object and there were some workarounds but I'm wondering if there isn't a better or easier way of doing this in the more recent versions of the framework. The main use case is to allow a user to define, using the standard printer setting user interfaces, all print details (including printer-specific options) for a given printer and have these saved so they get restored the next time the user prints to that printer. A: I did a pretty ghetto method of dumping the current DEVMODE and overwriting it back when they want to use it again to send some proprietary printer settings to a copier machine at work. I couldn't find a better way to get to some of the properties that simply weren't exposed via the printing API (such as proprietary stapling and folding options on an old Fiery controller...I think the new XPS printer model has support for these, but lord only knows when we'll start seeing industry support for that). The main caveat is that it would not be portable across machines or across different versions of the same printer driver. For me, that's no big deal since it's a controlled office environment. For you, I guess it would depend on the context of how your users use the program. Good luck! A: You should use the class PrinterSettings. A: not programmatic answer would be: use print management console from 2003 r2 server adminpack to Export Printer configuration. Maybe that feature has an API for it, wich can be called from .net. A: The issues with the serialization of a PrinterSetting object is about the PrintFileName Property. This property has to have a value to avoid an exception when you try to unserialize back the object. If you want to save PrinterSettings of a reportviewer Me.ReportViewer.PrinterSettings.PrintFileName = "abc" My.Settings.PrinterSettings = Me.ReportViewer.PrinterSettings My.Settings.Save() And getting them back If My.Settings.PrinterSettings IsNot Nothing Then Me.ReportViewer.PrinterSettings = My.Settings.PrinterSettings Anyway saving the PrinterSetting will only persist the "standard" value. You have to use DEVMODE if you want to persist the exotic stuff each driver have.
{ "language": "en", "url": "https://stackoverflow.com/questions/169695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What are your required software development operation manuals? After reading E-myth Revisited, I realize that I can do a better job at making my company less reliant upon me... I spend a tremendous amount of time answering silly questions (silly to me, but necessary for my developers to get the job done). I need to write a set of operating manuals for what to do in certain situations... For instance: * *How to make a build *How to write test cases *How to report status *How to fix a bug *How to handle support question A, B, C, etc... *What to do when you are stalled *What to do when the power goes out (really, I need to do this) *etc... What are some useful, generic operating manuals that you can think of, for a software development company?And please, if you have some good, short, online versions that you know of, please post them. I would much rather use a starter manual and modify it for my needs, than start from scratch. A: What about a wiki - at least then other people can start to contribute. Otherwise they are just going to rely on you for the manuals A: I disagree with the wiki. As the owner of the company -- it is your responsibility to write the manuals, or delegate it in a very controlled fashion. People should rely on you for the manuals. Really though, back to the question. The obvious standards, coding, SQL, etc for your platform and programming languages. You'll be able to find examples of these anywhere on the internet. As for customer support, you should probably write that yourself, you know how you want your customers treated. As for test cases, again, you'd have expect your developers or testers to have a professional understanding of what needs to be done, you might indicate the acceptable minimums however. What to do when you are stalled. That's what managers are for :-) I think it boils down to writing the manuals that are unique to your business, and trying to steal or borrow manuals for the generic processes.
{ "language": "en", "url": "https://stackoverflow.com/questions/169697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the toughest bug you ever found and fixed? What made it hard to find? How did you track it down? Not close enough to close but see also https://stackoverflow.com/questions/175854/what-is-the-funniest-bug-youve-ever-experienced A: The two toughest bugs that come to mind were both in the same type of software, only one was in the web-based version, and one in the windows version. This product is a floorplan viewer/editor. The web-based version has a flash front-end that loads the data as SVG. Now, this was working fine, only sometimes the browser would hang. Only on a few drawings, and only when you wiggled the mouse over the drawing for a bit. I narrowed the problem down to a single drawing layer, containing 1.5 MB of SVG data. If I took only a subsection of the data, any subsection, the hang didn't occur. Eventually it dawned on me that the problem probably was that there were several different sections in the file that in combination caused the bug. Sure enough, after randomly deleting sections of the layer and testing for the bug, I found the offending combination of drawing statements. I wrote a workaround in the SVG generator, and the bug was fixed without changing a line of actionscript. In the same product on the windows side, written in Delphi, we had a comparable problem. Here the product takes autocad DXF files, imports them to an internal drawing format, and renders them in a custom drawing engine. This import routine isn't particularly efficient (it uses a lot of substring copying), but it gets the job done. Only in this case it wasn't. A 5 megabyte file generally imports in 20 seconds, but on one file it took 20 minutes, because the memory footprint ballooned to a gigabyte or more. At first it seemed like a typical memory leak, but memory leak tools reported it clean, and manual code inspection turned up nothing either. The problem turned out to be a bug in Delphi 5's memory allocator. In some conditions, which this particular file was duly recreating, it would be prone to severe memory fragmentation. The system would keep trying to allocate large strings, and find nowhere to put them except above the highest allocated memory block. Integrating a new memory allocation library fixed the bug, without changing a line of import code. Thinking back, the toughest bugs seem to be the ones whose fix involves changing a different part of the system than the one where the problem occurs. A: When the client's pet bunny rabbit gnawed partway through the ethernet cable. Yes. It was bad. A: Had a bug on a platform with a very bad on device debugger. We would get a crash on the device if we added a printf to the code. It then would crash at a different spot than the location of the printf. If we moved the printf, the crash would ether move or disappear. In fact, if we changed that code by reordering some simple statements, the crash would happen some where unrelated to the code we did change. It turns out there was a bug in the relocator for our platform. the relocator was not zero initializing the ZI section but rather using the relocation table to initialze the values. So any time the relocation table changed in the binary the bug would move. So simply added a printf would change the relocation table an there for the bug. A: This happened to me on the time I worked on a computer store. One customer came one day into shop and tell us that his brand new computer worked fine on evenings and night, but it does not work at all on midday or late morning. The trouble was that mouse pointer does not move at that times. The first thing we did was changing his mouse by a new one, but the trouble were not fixed. Of course, both mouses worked on store with no fault. After several tries, we found the trouble was with that particular brand and model of mouse. Customer workstation was close to a very big window, and at midday the mouse was under direct sunlight. Its plastic was so thin that under that circumstances, it became translucent and sunlight prevented optomechanical wheel for working :| A: My team inherited a CGI-based, multi-threaded C++ web app. The main platform was Windows; a distant, secondary platform was Solaris with Posix threads. Stability on Solaris was a disaster, for some reason. We had various people who looked at the problem for over a year, off and on (mostly off), while our sales staff successfully pushed the Windows version. The symptom was pathetic stability: a wide range of system crashes with little rhyme or reason. The app used both Corba and a home-grown protocol. One developer went so far as to remove the entire Corba subsystem as a desperate measure: no luck. Finally, a senior, original developer wondered aloud about an idea. We looked into it and eventually found the problem: on Solaris, there was a compile-time (or run-time?) parameter to adjust the stack size for the executable. It was set incorrectly: far too small. So, the app was running out of stack and printing stack traces that were total red herrings. It was a true nightmare. Lessons learned: * *Brainstorm, brainstorm, brainstorm *If something is going nuts on a different, neglected platform, it is probably an attribute of the environment platform *Beware of problems that are transferred from developers who leave the team. If possible, contact the previous people on personal basis to garner info and background. Beg, plead, make a deal. The loss of experience must be minimized at all costs. A: Adam Liss's message above talking about the project we both worked on, reminded me of a fun bug I had to deal with. Actually, it wasn't a bug, but we'll get to that in a minute. Executive summary of the app in case you haven't seen Adam message yet: sales-force automation software...on laptops...end of the day they dialed up ...to synchronize with the Mother database. One user complained that every time he tried to dial in, the application would crash. The customer support folks went through all their usually over-the-phone diagnostic tricks, and they found nothing. So, they had to relent to the ultimate: have the user FedEx the laptop to our offices. (This was a very big deal, as each laptop's local database was customized to the user, so a new laptop had to be prepared, shipped to the user for him to use while we worked on his original, then we had to swap back and have him finally sync the data on first original laptop). So, when the laptop arrived, it was given to me to figure out the problem. Now, syncing involved hooking up the phone line to the internal modem, going to the "Communication" page of our app, and selecting a phone number from a Drop-down list (with last number used pre-selected). The numbers in the DDL were part of the customization, and were basically, the number of the office, the number of the office prefixed with "+1", the number of the office prefixed with "9,,," in case they were calling from an hotel etc. So, I click the "COMM" icon, and pressed return. It dialed in, it connected to a modem -- and then immediately crashed. I tired a couple more times. 100% repeatability. So, a hooked a data scope between the laptop & the phone line, and looked at the data going across the line. It looked rather odd... The oddest part was that I could read it! The user had apparently wanted to use his laptop to dial into a local BBS system, and so, change the configuration of the app to use the BBS's phone number instead of the company's. Our app was expecting our proprietary binary protocol -- not long streams of ASCII text. Buffers overflowed -- KaBoom! The fact that a problem dialing in started immediately after he changed the phone number, might give the average user a clue that it was the cause of the problem, but this guy never mentioned it. I fixed the phone number, and sent it back to the support team, with a note electing the guy the "Bonehead user of the week". (*) (*) OkOkOk... There's probably a very good chance what actually happened in that the guy's kid, seeing his father dial in every night, figured that's how you dial into BBS's also, and changed the phone number sometime when he was home alone with the laptop. When it crashed, he didn't want to admit he touched the laptop, let alone broke it; so he just put it away, and didn't tell anyone. A: This requires knowing a bit of Z-8000 assembler, which I'll explain as we go. I was working on an embedded system (in Z-8000 assembler). A different division of the company was building a different system on the same platform, and had written a library of functions, which I was also using on my project. The bug was that every time I called one function, the program crashed. I checked all my inputs; they were fine. It had to be a bug in the library -- except that the library had been used (and was working fine) in thousands of POS sites across the country. Now, Z-8000 CPUs have 16 16-bit registers, R0, R1, R2 ...R15, which can also be addressed as 8 32-bit registers, named RR0, RR2, RR4..RR14 etc. The library was written from scratch, refactoring a bunch of older libraries. It was very clean and followed strict programming standards. At the start of each function, every register that would be used in the function was pushed onto the stack to preserve its value. Everything was neat & tidy -- they were perfect. Nevertheless, I studied the assembler listing for the library, and I noticed something odd about that function --- At the start of the function, it had PUSH RR0 / PUSH RR2 and at the end to had POP RR2 / POP R0. Now, if you didn't follow that, it pushed 4 values on the stack at the start, but only removed 3 of them at the end. That's a recipe for disaster. There an unknown value on the top of the stack where return address needed to be. The function couldn't possibly work. Except, may I remind you, that it WAS working. It was being called thousands of times a day on thousands of machines. It couldn't possibly NOT work. After some time debugging (which wasn't easy in assembler on an embedded system with the tools of the mid-1980s), it would always crash on the return, because the bad value was sending it to a random address. Evidently I had to debug the working app, to figure out why it didn't fail. Well, remember that the library was very good about preserving the values in the registers, so once you put a value into the register, it stayed there. R1 had 0000 in it. It would always have 0000 in it when that function was called. The bug therefore left 0000 on the stack. So when the function returned it would jump to address 0000, which just so happened to be a RET, which would pop the next value (the correct return address) off the stack, and jump to that. The data perfectly masked the bug. Of course, in my app, I had a different value in R1, so it just crashed.... A: It was during my diploma thesis. I was writing a program to simulate the effect of high intensity laser on a helium atom using FORTRAN. One test run worked like this: * *Calculate the intial quantum state using program 1, about 2 hours. *run the main simulation on the data from the first step, for the most simple cases about 20 to 50 hours. *then analyse the output with a third program in order to get meaningful values like energy, tork, momentum These should be constant in total, but they weren't. They did all kinds of weird things. After debugging for two weeks I went berserk on the logging and logged every variable in every step of the simulation including the constants. That way I found out that I wrote over an end of an array, which changed a constant! A friend said he once changed the literal 2 with such a mistake. A: This was on Linux but could have happened on virtually any OS. Now most of you are probably familiar with the BSD socket API. We happily use it year after year, and it works. We were working on a massively parallel application that would have many sockets open. To test its operation we had a testing team that would open hundreds and sometimes over a thousand connections for data transfer. With the highest channel numbers our application would begin to show weird behavior. Sometimes it just crashed. The other time we got errors that simply could not be true (e.g. accept() returning the same file descriptor on subsequent calls which of course resulted in chaos.) We could see in the log files that something went wrong, but it was insanely hard to pinpoint. Tests with Rational Purify said nothing was wrong. But something WAS wrong. We worked on this for days and got increasingly frustrated. It was a showblocker because the already negotiated test would cause havoc in the app. As the error only occured in high load situations, I double-checked everything we did with sockets. We had never tested high load cases in Purify because it was not feasible in such a memory-intensive situation. Finally (and luckily) I remembered that the massive number of sockets might be a problem with select() which waits for state changes on sockets (may read / may write / error). Sure enough our application began to wreak havoc exactly the moment it reached the socket with descriptor 1025. The problem is that select() works with bit field parameters. The bit fields are filled by macros FD_SET() and friends which DON'T CHECK THEIR PARAMETERS FOR VALIDITY. So everytime we got over 1024 descriptors (each OS has its own limit, Linux vanilla kernels have 1024, the actual value is defined as FD_SETSIZE), the FD_SET macro would happily overwrite its bit field and write garbage into the next structure in memory. I replaced all select() calls with poll() which is a well-designed alternative to the arcane select() call, and high load situations have never been a problem everafter. We were lucky because all socket handling was in one framework class where 15 minutes of work could solve the problem. It would have been a lot worse if select() calls had been sprinkled all over of the code. Lessons learned: * *even if an API function is 25 years old and everybody uses it, it can have dark corners you don't know yet *unchecked memory writes in API macros are EVIL *a debugging tool like Purify can't help with all situations, especially when a lot of memory is used *Always have a framework for your application if possible. Using it not only increases portability but also helps in case of API bugs *many applications use select() without thinking about the socket limit. So I'm pretty sure you can cause bugs in a LOT of popular software by simply using many many sockets. Thankfully, most applications will never have more than 1024 sockets. *Instead of having a secure API, OS developers like to put the blame on the developer. The Linux select() man page says "The behavior of these macros is undefined if a descriptor value is less than zero or greater than or equal to FD_SETSIZE, which is normally at least equal to the maximum number of descriptors supported by the system." That's misleading. Linux can open more than 1024 sockets. And the behavior is absolutely well defined: Using unexpected values will ruin the application running. Instead of making the macros resilient to illegal values, the developers simply overwrite other structures. FD_SET is implemented as inline assembly(!) in the linux headers and will evaluate to a single assembler write instruction. Not the slightest bounds checking happening anywhere. To test your own application, you can artificially inflate the number of descriptors used by programmatically opening FD_SETSIZE files or sockets directly after main() and then running your application. Thorsten79 A: A deadlock in my first multi-threaded program! It was very tough to find it because it happened in a thread pool. Occasionally a thread in the pool would deadlock but the others would still work. Since the size of the pool was much greater than needed it took a week or two to notice the first symptom: application completely hung. A: I have spent hours to days debugging a number of things that ended up being fixable with literally just a couple characters. Some various examples: * *ffmpeg has this nasty habit of producing a warning about "brainfart cropping" (referring to a case where in-stream cropping values are >= 16) when the crop values in the stream were actually perfectly valid. I fixed it by adding three characters: "h->". *x264 had a bug where in extremely rare cases (one in a million frames) with certain options it would produce a random block of completely the wrong color. I fixed the bug by adding the letter "O" in two places in the code. Turned out I had mispelled the name of a #define in an earlier commit. A: My first "real" job was for a company that wrote client-server sales-force automation software. Our customers ran the client app on their (15-pound) laptops, and at the end of the day they dialed up to our unix servers to synchronize with the Mother database. After a series of complaints, we found that an astronomical number of calls were dropping at the very beginning, during authentication. After weeks of debugging, we discovered that the authentication always failed if the incoming call was answered by a getty process on the server whose Process ID contained an even number followed immediately by a 9. Turns out the authentication was a homebrew scheme that depended on an 8-character string representation of the PID; a bug caused an offending PID to crash the getty, which respawned with a new PID. The second or third call usually found an acceptable PID, and automatic redial made it unnecessary for the customers to intervene, so it wasn't considered a significant problem until the phone bills arrived at the end of the month. The "fix" (ahem) was to convert the PID to a string representing its value in octal rather than decimal, making it impossible to contain a 9 and unnecessary to address the underlying problem. A: Basically, anything involving threads. I held a position at a company once in which I had the dubious distinction of being one of the only people comfortable enough with threading to debug nasty issues. The horror. You should have to get some kind of certification before you're allowed to write threaded code. A: I heard about a classic bug back in high school; a terminal that you could only log into if you sat in the chair in front of it. (It would reject your password if you were standing.) It reproduced pretty reliably for most people; you could sit in the chair, log in, log out... but if you stand up, you're denied, every time. Eventually it turned out some jerk had swapped a couple of adjacent keys on the keyboard, E/R and C/V IIRC, and when you sat down, you touch-typed and got in, but when you stood, you had to hunt 'n peck, so you looked at the incorrent labels and failed. A: Mine was a hardware problem... Back in the day, I used a DEC VaxStation with a big 21" CRT monitor. We moved to a lab in our new building, and installed two VaxStations in opposite corners of the room. Upon power-up,my monitor flickered like a disco (yeah, it was the 80's), but the other monitor didn't. Okay, swap the monitors. The other monitor (now connected to my VaxStation) flickered, and my former monitor (moved across the room) didn't. I remembered that CRT-based monitors were susceptable to magnetic fields. In fact, they were -very- susceptable to 60 Hz alternating magnetic fields. I immediately suspected that something in my work area was generating a 60 Hz alterating magnetic field. At first, I suspected something in my work area. Unfortunately, the monitor still flickered, even when all other equipment was turned off and unplugged. At that point, I began to suspect something in the building. To test this theory, we converted the VaxStation and its 85 lb monitor into a portable system. We placed the entire system on a rollaround cart, and connected it to a 100 foot orange construction extension cord. The plan was to use this setup as a portable field strength meter,in order to locate the offending piece of equipment. Rolling the monitor around confused us totally. The monitor flickered in exactly one half of the room, but not the other side. The room was in the shape of a square, with doors in opposite corners, and the monitor flickered on one side of a diagnal line connecting the doors, but not on the other side. The room was surrounded on all four sides by hallways. We pushed the monitor out into the hallways, and the flickering stopped. In fact, we discovered that the flicker only occurred in one triangular-shaped half of the room, and nowhere else. After a period of total confusion, I remembered that the room had a two-way ceiling lighting system, with light switches at each door. At that moment, I realized what was wrong. I moved the monitor into the half of the room with the problem, and turned the ceiling lights off. The flicker stopped. When I turned the lights on, the flicker resumed. Turning the lights on or off from either light switch, turned the flicker on or off within half of the room. The problem was caused by somebody cutting corners when they wired the ceiling lights. When wiring up a two-way switch on a lighting circuit, you run a pair of wires between the SPDT switch contacts, and a single wire from the common on one switch, through the lights, and over to the common on the other switch. Normally, these wires are bundeled together. They leave as a group from one switchbox, run to the overhead ceiling fixture, and on to the other box. The key idea, is that all of the current-carrying wires are bundeled together. When the building was wired, the single wire between the switches and the light was routed through the ceiling, but the wires travelling between the switches were routed through the walls. If all of the wires ran close and parallel to each other, then the magnetic field generated by the current in one wire was cancelled out by the magnetic field generated by the equal and opposite current in a nearby wire. Unfortunately, the way that the lights were actually wired meant that one half of the room was basically inside a large, single-turn transformer primary. When the lights were on, the current flowed in a loop, and the poor monitor was basically sitting inside of a large electromagnet. Moral of the story: The hot and neutral lines in your AC power wiring are next to each other for a good reason. Now, all I had to do was to explain to management why they had to rewire part of their new building... A: While I don't recall a specific instance, the toughest category are those bugs which only manifest after the system has been running for hours or days, and when it goes down, leaves little or no trace of what caused the crash. What makes them particularly bad is that no matter how well you think you've reasoned out the cause, and applied the appropriate fix to remedy it, you'll have to wait for another few hours or days to get any confidence at all that you've really nailed it. A: Our network interface, a DMA-capable ATM card, would very occasionally deliver corrupted data in received packets. The AAL5 CRC had checked out as correct when the packet came in off the wire, yet the data DMAd to memory would be incorrect. The TCP checksum would generally catch it, but back in the heady days of ATM people were enthused about running native applications directly on AAL5, dispensing with TCP/IP altogether. We eventually noticed that the corruption only occurred on some models of the vendor's workstation (who shall remain nameless), not others. By calculating the CRC in the driver software we were able to detect the corrupted packets, at the cost of a huge performance hit. While trying to debug we noticed that if we just stored the packet for a while and went back to look at it later, the data corruption would magically heal itself. The packet contents would be fine, and if the driver calculated the CRC a second time it would check out ok. We'd found a bug in the data cache of a shipping CPU. The cache in this processor was not coherent with DMA, requiring the software to explicitly flush it at the proper times. The bug was that sometimes the cache didn't actually flush its contents when told to do so. A: A bug where you come across some code, and after studying it you conclude, "There's no way this could have ever worked!" and suddenly it stops working though it always did work before. A: The toughest bug I ever had to fix was one I'd raised myself - I contracted as a tester for a large telco, testing another company's product. Several years later, I had a contract with the other company and the first thing they gave me were the bugs I'd raised myself. It was a kernel race condition in am embedded operating system written in 6809 assembler and BCPL. The debugging environment consisted of a special printf which wrote to a serial device; no fancy IDE stuff in this setup. Took quite a while to fix but it was a huge satisfaction boost when I finally nutted it out. A: That was an access violation crash. from the crash dump I could only figure out a parameter on the call stack was corrupted. The reason was this code: n = strlen(p->s) - 1; if (p->s[n] == '\n') p->s[n] = '\0'; if the string length was 0, and the parameter on the stack above happen to be on address 0x0Axxxxxxx ==> stack corruption Fortunately this code was close enough to the actuall crash location, so browsing the (ugly) source code was the way to find the culrpit A: Designed a realtime multithreaded (shudder) system once which polled images from mutliple network surveilance cameras and did all kinds of magic on the images. The bug simply made the system crash, some critical section being mistreated ofcourse. I had no idea how to trigger the failure directly, but had to wait for it to occur, which was about once in three or four days (odds: about 1 in 15000000 on 30 fps). I had to prepare everything I could, debug output messages soiling the code, trace tools, remote debugging tools on the camera and the list goes on. Then I just had to wait two-three days and hope to catch all info for locating the failing mutex or whatever. It took four of these runs before I tracked it down, four weeks!. One more run and I would have broken the customer deadline.. A: Thanks to a flash of inspiration this didn't take too long to track down but was a bit odd nonetheless. Small application, only used by other people in the IT department. It is connecting in turn to all of the desktop PC's in the domain. Many are turned off and the connection takes AGES to time out, so it runs on the threadpool. It just scans AD and queues thousands of work items to the thread pool. All worked fine. Some years later I was talking to another member of staff that actually uses this appliacation and he mentioned it made the PC un-usable. While it was running trying to open web pages or browse a network drive would take minutes, or just never happen. the problem turned out to be XP's half open tcp limit. The original PC's were dual processor, so .NET allocates 50 (or 100, not sure) threads to the pool, no problem. Now we have dual processor dual core, we now have more threads in the thread pool than you can have half open connections, so other network activity becomes impossable while the application is running. It is now fixed, it pings machines before attempting to connect to them so the timeout is much shorter and uses a small fixed number of threads to do the actual work. A: I work for a large community college and we switched over from Blackboard to Moodle last year. Moodle uses the nomenclature of "courses" and "groups". A course might be Microeconomics ECO-150, for example, and groups are what we would call sections (OL1, OL2, 01, 14, W09 as examples). Anyway we are primitive. We don't even have LDAP. Everything is text files, excel spreadsheets and GD microsoft Access databases. My job is to create a web application that takes all of the above as input and produces still more text files than can then be uploaded into Moodle to create courses, groups in courses and users and put users into courses and groups. The whole setup is positively byzantine, with about 17 individual steps that must be done in order. But the thing works and replaces a process that previously took days during the busiest time of the semester. But there was one problem. Sometimes we got what I dubbed "Crazy Groups". So instead of creating a course with 4 groups of 20 students each it would create a course with 80 groups of 1 student each. The worst part, there is no way programmatically short of getting into cpanel(which I don't have access to) to delete a group once it is created. It is a manual process that takes about 5 button clicks. So every time a course with Crazy Groups got created I either had to delete the course, which is preferable but not an option if the teacher had already started putting content in the course, or I had to spend an hour repetitively following the same pattern: Select group, display group, edit group, delete group, Are you sure you want to delete group? Yes for godsake! And there was no way to know if crazy groups had occured unless you manually opened up each course and looked (with hundreds of courses) or until you got a complaint. Crazy Groups seemed to happen randomly and Google and the Moodle forums were no help, it seems everyone else uses this thing called LDAP or a REAL database so they've never encountered the problem. Finally, after I don't know how much investigating and more time deleting crazy groups than I ever want to admit I figured it out. It was a bug in Moodle not my code! This gave me not a little pleasure. You see the way to create a group is just try to enroll someone into the group and if the group does not already exist then Moodle creates it. And this worked fine for groups named OL1 or W12 or even SugarCandyMountain but if you tried to create a group with a number as the name, say 01 or 14 THAT is when crazy groups would occur. Moodle does not properly compare numbers as strings. No matter how many groups named 01 inside a course there are it will always think that group does not exist yet and will therefore create it. That is how you end up with 80 groups with 1 person in each. Proud of my discovery I went to the Moodle forum and posted my findings complete with steps to reproduce the problem at will. That was about a year ago and the problem still exists inside of Moodle to my knowledge, no one seems motivated to fix it because no one but us primitives uses the text file enrollment. My solution, simply to make sure that all our group names contained at least 1 non-numeric character. Crazy groups are gone forever at least for us but I feel for that guy who works at a community college in outer Mongolia who just uploaded a semester's worth of courses and is about to have a rude awakening. At least this time Google may help him because I've written him this message in a bottle on the tides of cyberspace. A: In CS435 back at Purdue, we had to write a raytracer for our final project. Everything mine produced had a strong orange tint to it, but I could see every one of the objects in my scene. I finally gave up and submitted it as is, and had the professor look over my code to find the bug, and when he couldn't find it, I spent most of the summer digging to find just what the hell was wrong. Buried deep in the code, as part of a color calculation function, I finally realized I was dividing an int and passing it to an OpenGL function that expected a float value. One of the color components was just low enough throughout most of the scene that it would round down to 0, causing the orange tint. Casting it to a float in just one place (before the division) fixed the bug. Always check your inputs and expected types. A: One of the products I helped build at my work was running on a customer site for several months, collecting and happily recording each event it received to a SQL Server database. It ran very well for about 6 months, collecting about 35 million records or so. Then one day our customer asked us why the database hadn't updated for almost two weeks. Upon further investigation we found that the database connection that was doing the inserts had failed to return from the ODBC call. Thankfully the thread that does the recording was separated from the rest of the threads, allowing everything but the recording thread to continue functioning correctly for almost two weeks! We tried for several weeks on end to reproduce the problem on any machine other than this one. We never could reproduce the problem. Unfortunately, several of our other products then began to fail in about the same manner, none of which have their database threads separated from the rest of their functionality, causing the entire application to hang, which then had to be restarted by hand each time they crashed. Weeks of investigation turned into several months and we still had the same symptoms: full ODBC deadlocks in any application that we used a database. By this time our products are riddled with debugging information and ways to determine what went wrong and where, even to the point that some of the products will detect the deadlock, collect information, email us the results, and then restart itself. While working on the server one day, still collecting debugging information from the applications as they crashed, trying to figure out what was going on, the server BSoD on me. When the server came back online, I opened the minidump in WinDbg to figure out what the offending driver was. I got the file name and traced it back to the actual file. After examining the version information in the file, I figured out it was part of the McAfee anti-virus suite installed on the computer. We disabled the anti-virus and haven't had a single problem since!! A: I just want to point out a quite common and nasty bug that can happens in this google-area time: code pasting and the infamous minus That is when you copy paste some code with an minus in it, instead of a regular ASCII character hyphen-minus ('-'). Plus, minus(U+2212), Hyphen-Minus(U+002D) Now, even though the minus is supposedly rendered as longer than the hyphen-minus, on certain editors (or on a DOS shell windows), depending on the charset used, it is actually rendered as a regular '-' hyphen-minus sign. And... you can spend hours trying to figure why this code does not compile, removing each line one by one, until you find the actual cause! May be not the toughest bug out there, but frustrating enough ;) (Thank you ShreevatsaR for spotting the inversion in my original post - see comments) A: A jpeg parser, running on a surveillance camera, which crashed every time the company's CEO came into the room. 100% reproducible error. I kid you not! This is why: For you who doesn't know much about JPEG compression - the image is kind of broken down into a matrix of small blocks which then are encoded using magic etc. The parser choked when the CEO came into the room, because he always had a shirt with a square pattern on it, which triggered some special case of contrast and block boundary algorithms. Truly classic. A: A multi-threaded applications where running in debug is fine but as soon as you run in release it goes wrong because of slightly different timing. Even adding Console.WriteLine calls to product basic debugging outpit caused enough of a change in timing for it to work and not show the issue. Tool a week to find and fix a couple of lines of code that needed changing. A: Just before the internet caught on, we were working on a modem-based home banking application (The first in North America). Three days before release, we were (almost) on schedule, and were planning to use the remaining time to exhaustivly test the system. We had a test plan, and next on the list was modem communications. Right about then, our client came rushing in wanting a last minute feature upgrade. Of course, I was completely against this, but I was overruled. We burned the midnight oil for three days adding the stupid thing, and got it working by release date. We made the deadline, and delivered over 2000 floppy disks to the customers. The day after release, I got back to my testing schedule, and resumed testing the modem communication module. Much to my suprise, I found that the modem would randomly fail to connect. Just about then, our phones started ringing off the hook, with angry customers not being able use their application. After much knashing of teeth and pulling of hair, I traced the problem to the serial port initialization. A junior programmer had commented out a write to one of the control registers. The register remained uninitialized, and there was about a 10% chance that it would contain an invalid value - depending upon the user's configuration, and what applications he had run beforehand. When asked about it, the programmer claimed that it made it work on his machine. So we had to re-burn those 2000+ floppies, and track down each and every customer to recall them. Not a fun thing to do, especially with an already burnt-out team. We took a big hit on that one. Our client claimed that because it was our bug, we should have to absorb the cost of the recall. Our schedule for the next release was put back a month. And our relationship with the client was tarnished. Nowadays, I am much less flexible with last-minute feature additions, and I try to communicate better with my team. A: In a game I was working on, a particular sprite would not display anymore in Release mode, but worked fine in Debug mode, and only in one particular edition. Another programmer tried to find this bug for 2 days, then left for vacation. It ended up on my shoulders to try to find the bug ~5 hours before release. Since the Debug build worked, I had to debug with the release build. Visual Studio supports some debugging in the Release build, but you can't rely on everything the debugger tells you to be correct (especially with the aggressive optimization settings we were using). Therefore, I had to step through half code listings and half assembler listings, sometimes looking at objects directly in the hex dump instead of in the nicely formatted debugger view. After spending a while making sure that all the correct draw calls were being made, I found out that the material color of the sprite was incorrect - it was supposed to be full opacity orange, but instead was set to black and completely transparent. The color was grabbed from a palette residing in a const array in our EditionManager class. It was setup initially as the correct orange color, but when the actual color was retrieved from the sprite drawing code, it was that transparent black again. I set a memory breakpoint, which was triggered in the EditionManager constructor. A write to a different array caused the value in the palette array to change. As it turns out, the other programmer changed an essential enum of the system: enum { EDITION_A = 0, EDITION_B, //EDITION_DEMO, EDITION_MAX, EDITION_DEMO, }; He put EDITION_DEMO right after EDITION_MAX, and the array that was being written to was indexed with EDITION_DEMO so it overflowed into the palette and set the wrong values there. I couldn't change the enum back, however, since the edition numbers couldn't change anymore (they were being used in binary transmission). Therefore, I ended up making a EDITION_REAL_MAX entry in the enum and using that as the array size. A: The first was that our released product exhibited a bug, but when I tried to debug the problem, it didn't occur. I thought this was a "release vs. debug" thing at first -- but even when I compiled the code in release mode, I couldn't reproduce the problem. I went to see if any other developer could reproduce the problem. Nope. After much investigation (producing a mixed assembly code / C code listing) of the program output and stepping through the assembly code of the released product (yuck!), I found the offending line. But the line looked just fine to me! I then had to lookup what the assembly instructions did -- and sure enough the wrong assembly instruction was in the released executable. Then I checked the executable that my build environment produced -- it had the correct assembly instruction. It turned out that the build machine somehow got corrupt and produced bad assembly code for only one instruction for this application. Everything else (including previous versions of our product) produced identical code to other developers machines. After I showed my research to the software manager, we quickly re-built our build machine. A: Somewhere deep in the bowels of a networked application was the line (simplified): if (socket = accept() == 0) return false; //code using the socket() What happened when the call succeeded? socket was set to 1. What does send() do when given a 1? (such as in: send(socket, "mystring", 7); It prints to stdout... this I found after 4 hours of wondering why, with all my printf()s taken out, my app was printing to the terminal window instead of sending the data over the network. A: With FORTRAN on a Data General minicomputer in the 80's we had a case where the compiler caused a constant 1 (one) to be treated as 0 (zero). It happened because some old code was passing a constant of value 1 to a function which declared the variable as a FORTRAN parameter, which meant it was (supposed to be) immutable. Due to a defect in the code we did an assignment to the parameter variable and the compiler gleefully changed the data in the memory location it used for a constant 1 to 0. Many unrelated functions later we had code that did a compare against the literal value 1 and the test would fail. I remember staring at that code for the longest time in the debugger. I would print out the value of the variable, it would be 1 yet the test 'if (foo .EQ. 1)' would fail. It took me a long time before I thought to ask the debugger to print out what it thought the value of 1 was. It then took a lot of hair pulling to trace back through the code to find when the constant 1 became 0. A: I had a bug in a console game that occurred only after you fought and won a lengthy boss-battle, and then only around 1 time in 5. When it triggered, it would leave the hardware 100% wedged and unable to talk to outside world at all. It was the shyest bug I've ever encountered; modifying, automating, instrumenting or debugging the boss-battle would hide the bug (and of course I'd have to do 10-20 runs to determine that the bug had hidden). In the end I found the problem (a cache/DMA/interrupt race thing) by reading the code over and over for 2-3 days. A: Not very tough, but I laughed a lot when it was uncovered. When I was maintaining a 24/7 order processing system for an online shop, a customer complained that his order was "truncated". He claimed that while the order he placed actually contained N positions, the system accepted much less positions without any warning whatsoever. After we traced order flow through the system, the following facts were revealed. There was a stored procedure responsible for storing order items in database. It accepted a list of order items as string, which encoded list of (product-id, quantity, price) triples like this: "<12345, 3, 19.99><56452, 1, 8.99><26586, 2, 12.99>" Now, the author of stored procedure was too smart to resort to anything like ordinary parsing and looping. So he directly transformed the string into SQL multi-insert statement by replacing "<" with "insert into ... values (" and ">" with ");". Which was all fine and dandy, if only he didn't store resulting string in a varchar(8000) variable! What happened is that his "insert ...; insert ...;" was truncated at 8000th character and for that particular order the cut was "lucky" enough to happen right between inserts, so that truncated SQL remained syntactically correct. Later I found out the author of sp was my boss. A: While testing some new functionality that I had recently added to a trading application, I happened to notice that the code to display the results of a certain type of trade would never work properly. After looking at the source control system, it was obvious that this bug had existed for at least a year, and I was amazed that none of the traders had ever spotted it. After puzzling for a while and checking with a colleague, I fixed the bug and went on testing my new functionality. About 3 minutes later, my phone rang. On the other end of the line was an irate trader who complained that one of his trades wasn’t showing correctly. Upon further investigation, I realized that the trader had been hit with the exact same bug I had noticed in the code 3 minutes earlier. This bug had been lying around for a year, just waiting for a developer to come along and spot it so that it could strike for real. This is a good example of a type of bug known as a Schroedinbug. While most of us have heard about these peculiar entities, it is an eerie feeling when you actually encounter one in the wild. A: This is back when I thought that C++ and digital watches were pretty neat... I got a reputation for being able to solve difficult memory leaks. Another team had a leak they couldn't track down. They asked me to investigate. In this case, they were COM objects. In the core of the system was a component that gave out many twisty little COM objects that all looked more or less the same. Each one was handed out to many different clients, each of which was responsible for doing AddRef() and Release() the same number of times. There wasn't a way to automatically calculate who had called each AddRef, and whether they had Released. I spent a few days in the debugger, writing down hex addresses on little pieces of paper. My office was covered with them. Finally I found the culprit. The team that asked me for help was very grateful. The next day I switched to a GC'd language.* (*Not actually true, but would be a good ending to the story.) A: Bryan Cantrill of Sun Microsystems gave an excellent Google Tech Talk on a bug he tracked down using a tool he helped develop called dtrace. The The Tech Talk is funny, geeky, informative, and very impressive (and long, about 78 minutes). I won't give any spoilers here on what the bug was but he starts revealing the culprit at around 53:00. A: This didn't happen to me, but a friend told me about it. He had to debug a app which would crash very rarely. It would only fail on Wednesdays -- in September -- after the 9th. Yes, 362 days of the year, it was fine, and three days out of the year it would crash immediately. It would format a date as "Wednesday, September 22 2008", but the buffer was one character too short -- so it would only cause a problem when you had a 2 digit DOM on a day with the longest name in the month with the longest name. A: Not sure this is the toughest, but several years ago I had a Java program which made use of XMLEncoder in order to save/load a particular class. For some reason the class wasn't working properly. I did a simple binary search for error and discovered that the error was happening after one function call but before another call, which should have been impossible. 2 hours later I had not figured it out, though the moment I took a break (and was leaving) I realized the problem. It turned out the XMLEncoder was creating a default-constructed instance of the class instead of having both the class and the reference to the class refer to the same object. So, while I thought the two function calls where both on members of the same instance of a particular class, one was actually on a default-constructed copy. Was tough to find since I knew they were both references to the same class. A: long ago, i wrote an object-oriented language using C and a (character-based) forms library; each form was an object, forms could contain subforms, and so on. The complex invoicing application written using this would work fine for about 20 minutes, then random garbage characters would appear every now and then on the screen. After a few more minutes of using the app, the machine would reboot, hang, or something drastic. this turned out to be a bad deallocation resulting from a misdirected delegation in the message-processing engine; mis-routed messages were being delegated up the containment tree when we ran out of superclasses, and sometimes the parent objects would have methods with the same name so it would appear to work most of the time. The rest of the time it would deallocate a small buffer (8 bytes or so) in the wrong context. The pointer being deallocated incorrectly was actually dead memory used by an intermediate counter for another operation, so its value tended to converge on zero after time. yes, the bad pointer would cross through the memory-map area of the screen on its way to the zero page, where it eventually overwrote an interrupt vector and killed the PC this was way before modern debugging tools, so figuring out what was happening took a couple of weeks... A: Not one of mine, but a colleague at a previous place of employment spent 3 days debugging his JavaScript popout editor control (this was quite a while ago, before the joys of frameworks), only to find that it was missing a single semicolon halfway down one of its huge core files. We dubbed it "the world's most expensive semicolon", but I'm sure there's been far worse throughout history! A: This is a little off-topic (which is why I made it community). But The Bug by Ellen Ullman is a fantastic fictional book about this very topic. A: There was a code that sets some expiry date to current date plus one year by adding 1 to the current year and keeping the day and month as the same. This failed big time on Feb 29, 2008 because the database refused to accept Feb 29, 2009 !! Don't know whether that qualifies for being 'tough', but it was a weird code which was rewritten immediately of course ! A: When I first started at the company I work for I did a lot of CPR to learn the products. This embedded product written in HC11 assembly had a feature that occurred every eight hours. Turns out the interrupt that decremented the value was firing during the code that was checking the counter. Slapped some CLI/STI around the code and it was fine. I tracked it down by hacking the event to happen twice a second rather than every eight hours. The lesson I learned from this was when debugging code that fails infrequently I should check the variables used by interrupts first. A: DevExpress XPO talking to an Oracle database crashing hard (as in: program exits silently) if directory path that the application is installed to does not contain at least one space, and the data dictionary XPO checks for isn't 100% correctly cased in the database. Problem described here. I can tell you this: I was this >< close to crying when we figured out how to circumvent the problem. I still don't know what the actual, real, cause of the problem is, but our product is not going to support Oracle in future version so I'm actually not giving a .... any more. A: I had a bug with a custom synchronization program once. It used the date/time stamp of files/folders to compare what was modified to synchronize data from a flash key to a network share in windows, with some extra integrity and business logic built in it. One day, an operator reported that his sync was taking forever...after reviewing the logs, for some reason, the software thought every file on the stick (or the server) was 3 hours older than it should be, refreshing all 8 gigs of data! I was using UTC, how the heck could this be? It turns out, this particular operator did indeed set his time zone to Pacific time instead of Eastern, causing the problem, but it shouldn't have, because all the code was using UTC - good god what could it be?! It worked when testing it on my local system...what gives? At this point, we requested all operators ensure that their laptops were set to eastern time before they synced, and the bug stayed in the queue until we had more time to investigate. Then, October came around and BOOM! Daylight savings time! What the heck!? Now everyone was complaining syncing was taking forever! Had to be fixed, and fast! I tracked it down by modifying the test case to run off a stick instead of off my local hard drive, and sure enough, it failed...phew, must a a memory stick thing - wait a sec, is it formatted FAT32... AH HA! FAT32 uses localtime when recording the timestamp of a file! http://msdn.microsoft.com/en-us/library/ms724290(VS.85).aspx So, the software was rewritten so that when writing to FAT32 media, we programatically set it to UTC... A: A deadlock in a Java Server Application. But not a simple deadlock with two threads. I tracked down a deadlock involving eight threads. Thread 1 waits for thread 2 that waits for thread 3, etc, and finally thread 8 waits for thread 1. It took me about one entire day to understand what was going on and then just 15 minutes to fix it. I use eclipse to monitor about 40 threads till I discovered the deadlock. A: The toughest bug would have to be when a programmer output to a log "General Error!". After looking through the code, it was scattered everywhere with the text "General Error!". Try nailing that one down. At least writing a macro to output __LINE__ or __FUNCTION__ would have been a little more helpful to add to the debug output. A: A race between Oracle's OracleDecimal class's ToString method (which P/Invokes the native version of the same functionality) and the garbage collector caused by a missing GC.KeepAlive call which can cause OracleDecimal.ToString() to return essentially arbitrary junk if its heap space happens to be overwritten before the call finishes. I wrote a detailed bug report and never heard back, for all I know this is still out there. I even had a test harness that did nothing but create new OracleDecimal representations of the number 1, call ToString on them, and compare the result with "1". It would fail every ten-millionth time or so with crazy gibberish (huge numbers, negative numbers, and even alphanumeric junk strings). Be careful out there with your P/Invoke calls! It is legal for the .NET garbage collector to collect your instance while a call to an instance method on that instance is still pending, as long as the instance method has finished using the this reference. Reflector is an absolute lifesaver for stuff like this. A: In Python, I had a thread doing something like this: while True: with some_mutex: ... clock.tick(60) clock.tick(60) suspends the thread so that it runs no more than 60 times per second. The problem was that most of the time the program just showed a black screen. If I let it run for some time, it finally showed the game screen. It's because the thread was doing the pause while maintaining the mutex. Thus it rarely let other threads acquire the mutex. It may seem obvious here, but I took me two days to figure it out. The solution is simply to remove an indent level: while True: with some_mutex: ... clock.tick(60) A: might seem funny but when i was learing i spent an entire afternoon trying to figure out why an if statment always evaluate to true i used = instead of == :d i ve rewritten everything twice on an other computer :) A: A box had crashed at a big customer's site, and we had to connect via a WebX session to an IT guy's computer, which was connected to our box. I poked around for about an hour, grabbing stack traces, register dumps, statistics, counters, and dumping sections of memory that seemed relevant. Their IT guys then emailed me a transcript of my session, and I got to work. After a few hours, I'd traced it back to an array of structures which contained packet metadata followed by packet data. One of the packet's metadata was corrupt, and it looked like it had been overwritten by a few bytes of packet data. Bugzilla had no record of anything similar. Delving into the code, I checked all the obvious things. The code that copied packet data into the buffer was meticulous about not exceeding its bounds: the buffer was the MTU size for the interface, and the copy routine checked that the data didn't exceed the MTU size. My memory dumps allowed me to validate that, yes, foo->bar was indeed 4 when the crash happened. Nothing added up. Nothing was wrong in a way that should have caused the problem. There were what looked like 16 bytes of packet data in the next header. A couple days later, I started checking anything and everything that I could think of. I noticed that the length of the data buffer was actually correct. That is, the number of bytes from start of data until end of data was an MTU, even though the next header started at MTU-16. When these structs were malloc'd, pointers to each element were placed in an array, and I'd dumped that array. I started measuring distance between these pointers. 6888... 6888... 6888... 6872... 6904... 6880... 6880... Wait, what? I started looking at the internal pointers and offsets in both structures. Everything added up. It just looked like my one bad structure - the one that'd been partially clobbered - was just 16 bytes too soon in memory. The allocation routine malloc'd these guys as a chunk, and then carved them up in a loop: for (i = 0; i < NUM_ELEMS; i++) { array[i] = &head[i*sizeof(foo)]; } (with allowances for alignment, etc.). When the array was filled the value for my corrupt pointer must have been read as 0x8a1128ac instead of 0x8a1129ac. I came to the conclusion that I'd been the victim of a 1-bit memory error during allocation (I know, I know! I didn't believe it either, but we'd seen them before on this hardware -- NULL values that were read as 0x00800000). In any case, I managed to convince my boss and co-workers that there was no other reasonable explanation, and that my explanation exactly explained what we were seeing. So, box RMA'd. A: A legacy database based application (with only part of the source avaliable) crashed when one particular user accessed a certain inventory feature. It worked perfectly for all other users. The user profile right? Nope. When logging in as a different user (even as admin) the same user had the same problem. Computer problem? Nope. Same user, different PC (under her login or any other login) still crashed. The problem: when logging in the program displayed a copyright splash screen that could be closed either by clicking the "X" to close the window, or by pressing any key. When logging in this user always clicked the "X" where other users always pressed a key. This resulted in a memory leak that caused but only when the inventory lookup was accessed. Fix: Don't click the X. A: The toughest bugs I ever fixed actually came quite early in my career. I was working on a real-time system for a power station that used pairs of GEC 2050 computers with shared memory. 2050 RTOS had a main scheduling table which consisted of one slot per process, the contents of which were either an add 1,X instruction for an inactive process or a jump for an executable process. Executing this table with X set to zero meant that the first runnable process automatically got entered with the X register being the process number. Whoever designed this obviously felt he was being very clever! The 2050 architecture also had a security feature where an unrecognised opcode always caused a halt. Since the 2050 had a full-blown front panel, you could then use that to try and work out what had crashed. Since the X register always held the current process ID, this was usually fairly straight-forward. There was no memory segmentation or protection, so it was perfectly possible for a process to corrupt either any other process currently in memory or indeed anything in the system area. So far so consistent for the era (late 70s). Since this particular system had shared memory between the two CPUs, the system configuration placed the system tables in the shared memory, to allow one CPU to start and stop processes in the other without having to go through any namby pamby secure interface. Unfortunately this also allowed one CPU's wild process to corrupt the tables for the other CPU, so one CPU could happily crash the other. If this happened, what was running in the crashed CPU bore no relationship at all to the actual fault. Meanwhile the other CPU had happily carried on so there was no way to tell if it had caused the problem. Needless to say, this provided a few hard to fix issues! After a little bit of hair tearing, I ended up writing a fairly substantial patch to the O/S which looked for corruption in the scheduler table for the other CPU and crashed the CPU it was running on. This was hooked into a regular interrupt so while not being perfectly synchronised, at least it had a good chance of catching the offending process. This helped me clear up quite a few mutual-CPU issues... A: I'm currently attending university and the hardest bug I encountered was from a programming class there. In the previous two semesters, we simply wrote all of our own code. But for the third semester, the professor and TA would write half the code, and we were to write the other half. This was to help us learn to read code. Our first assignment for that semester was to write a program that simulates DNA gene splitting. Basically, we just had to find a substring in a larger one and process the results. Apparently, the professor and TA were both busy that week and gave us their half of the code without having their own full implementation finished yet. They hadn't had time to write the other half to act as a solution. Their half would compile, but without a full solution coded, there wasn't a way for them to test it. We were told not to alter the professors code. Everyone in the class had the exact same bug, but we all still assumed we were just all making the same mistake. The program was gobbling gigabytes of memory and then running out and crashed. We (the students) all assumed that our half the code must have some obscure memory leak in it. Everyone in the class was scouring the code for two weeks and running it through a debugger over and over again. Our input file was a 5.7 MB string and we were finding hundreds of substrings in it and storing them. The professor/TA's code used this. myString = myString.substr(0,pos); See the problem? When you assign a string variable to its own substring, the memory is not reallocated. That's a tidbit of information nobody (not even the professor or TA) knew. So myString had 5.7 MB of allocated memory only to hold a few bytes of actual data. This was repeated hundreds of times; thus the massive memory usage. I spent two weeks on this problem. I spent the first week checking my own code for memory leaks. In my frustration I finally concluded the professor/TA's half must have the leak, so I spent the second week checking their code. But even then, it took me so long to find because this wasn't technically a leak. All allocations were eventually being freed and the program worked fine when our input data was only a dozen kilobytes. The only reason I found it was because I sent psycho crazy and decided to analyze every single last variable; even the temporary throw-away stuff. I was also spending a lot of time checking how many chars the string actually had, not how much was allocated. I assumed the string class was taking care of this. Here was the solution, a one line change that fixed weeks of frustrated and earned me an A on the assignment for finding/fixing the teacher's code. myString.substr(0,pos).swap(myString); The swap method, does force a reallocation. A: I once had a bug in a .NET app that would cause the CLR to crash - yes the CLR would just exit with a non-zero result and there'd be no debug info. I peppered the code with console trace messages trying to find out where the issue was (the error would occur at startup) and eventually found the few lines causing the problem. I tried isolating the issue but every time I did the isolated case would work! In the end I changed the code from: int value = obj.CalculateSomething(); to int value; value = obj.CalculateSomething(); Don't ask me why, but this worked. A: A nasty crash in a GUI app written in Turbo Pascal. Three days plus before i discovered, by single stepping in the debugger, at a machine code level, over simple and obviously correct code, that i was putting a 16-bit integer on the call stack for a function expecting 32-bit (or some such mismatch) Now i am wise to that, although modern compilers don't allow that kind of trouble any more. A: A heap memory violation in a text edit control that I used. After many months (...) looking for it, I found the solution working with another programmer, peer debugging the problem. This very instance convinced me of the value of working in teams and Agile in general. Read more about it at my blog A: There are a couple of those I can recollect, most of them caused by me :). Almost evey one of these needed lots of head scratching. * *I was part of a java project (rich client), the java code used to work well on vanilla builds or new machines without problem, but when installed on the presentation laptops,it suddenly stopped working and started throwing stackdump. Further investigation showed that the the code relied on a custom dll which has conflicting with cygwin. Thats not the end of the story, we were supposed to install it on 5 other machies and guess what, on one of the machines it again crashed! This time the culprit was the jvm, the code we gave was for built using Sun microsystems jdk and the machine had ibm's jvm. *Another instance I can recollect has to do with a custom event handler code, The code was unit tested and verified, finally when I removed the print() statements, BOOM!!. When we debugged, the code ran perfectly adding to our owes. I had to resort to zen meditation (a nap on the desk) and it occured that there might be a temporal anamoly! The event we were delegating was triggering the function even before the condition was set, the print statements & debug mode gave enough time for the condition to be set and so worked properly. A sigh of relief and some refactoring solved the issue. *One fine day I decided that some of the domain objects needed to implement Clonable interface, things were fine. After some weeks, we observed that the application started behaving wierdly. Guess what? we were adding these shallow copies to the collection classes and the remove() methods were not actually clearing the contents properly, (due to duplicate references pointing to the same object). This caused some serious model review and a couple of raised browes. A: Had a bug on a platform with a very bad on device debugger. We would get a crash on the device if we added a printf to the code. It then would crash at a different spot than the location of the printf. If we moved the printf, the crash would ether move or disappear. In fact, if we changed that code by reordering some simple statements, the crash would happen some where unrelated to the code we did change. This looks like a classic Heisenbug. The minute you recognize it, you immediately go looking for uninitialized variables or stack boundary trashing. A: In two words: memory leaks. A: I once uninstalled PHP. Manually. Lots of bugs fixed with one move... A: It was a tiny bug in Rhino (Javascript interpreter in Java) that was causing one script to fail. It was hard because I knew little about how the interpreter would work, but I had to jump in there to fix the bug as quickly as possible, for the sake of another project. First I tracked down which call in the Javascript was failing, so I could reproduce the problem. I stepped through the running interpreter in debug mode, initially quite lost, but slowly learning bits of how it worked. (Reading the docs helped a little.) I added printlns/logging at points I thought might be relevant. I diffed the (cleaned up) logfile of a working run against a breaking run, to see at what point they first started to diverge. By re-running and adding lots of breakpoints, I found my way to the chain of events that lead up to the failure. Somewhere in there was a line of code that, if written slightly differently, solved the problem! (It was something very simple, like nextNode() should return null instead of IndexOutOfBounds.) Two weeks after that I realised my fix broke scripts in certain other situations, and I changed the line to work well for all the cases. I was in an unfamiliar environment. So I just tried a lot of different things, until one of them worked, or at least helped to make some progress/understanding. It did take a while, but I was pleased to get there in the end! If I was doing it again now, I would look for the project's IRC channel (not only its mailing list), to ask a few polite questions and seek pointers. A: I can't imagine how did they code this: You can't assign IP address 127.0.0.1 to the loopback adapter, because it is a reserved address for loopback devices --Microsoft(r) WindowsXP PROFESSIONAL A: I had a piece of delphi code that ran a long processing routine updating a progress bar as it went. The code ran fine in 16bit Delphi 1 however when we upgraded to delphi 2 a process that was taking 2 minutes suddenly took about an hour. After weeks of pulling the routine apart it turns out it was the line that updated the progress bar that caused the issue, for every itteration we were checking the record count using table1.recordcount, in delphi 1 this worked fine but it seems in later versions of delphi calling table.recordcount on a dbase table takes a copy of the table counts the records and returns the amount, calling this on every itteration of our progress was causing the table to be downloaded from the network with every ittteration and counted. The solution was to count the records before the processing started and stored the amount in a variable. Took ages to find but turned out to be so simple. A: A crash happening in a DLL, loaded from a service. Triggered by shutting the system down. The bug was simple to fix, but it took about a week - and a lot of frustration - to locate. A: Years ago I spent several days trying to track down and fix a small bug in dbx, the text-based debugger on AIX. I don't remember the exact bug. What made it tough was I was using the installed dbx to debug the dev version of dbx I was working on. It was very tough to keep track of where I was. More than once, I prepared to leave for the day and exited dbx twice (the dev version and the installed version) only to see that I was still running inside dbx, sometimes two or more levels "deep". -- bmb A: A Heisenbug where the main difficulty was not realizing it wasn't my bug at all. The problem was an API interface. Calling any real function (as opposed to the setup stuff) had a very high probability of crashing with a protection violation. Single-stepping through the function (to the extent possible, it would hit an interrupt and you couldn't trace past that point--this was back when you used interrupts to talk to the system) produced the correct output, no crash. After a long search in vain for what I was doing wrong I finally dug through the RTL routines to try to understand what I was doing wrong. What I was doing wrong was believing the routines worked--all the routines that bombed were manipulating a real-mode pointer with a protected-mode pointer type. Unless the real-mode segment value happened to be valid in protected mode this went boom. However, something about the debugger's manipulation of the program caused correct operation while single-stepping, I never bothered to figure out why. A: We had an RMI server running on a DOS prompt Someone "selected" the window - which paused the process The fix was quite simple...press enter. It was quite an agonizing day... A: Unexplained SQL Server Timeouts and Intermittent Blocking We had a problem where our users would timeout for apparently no reason. I monitored the SQL Server for a while and found that every once in a while there would be a lot of blocking going on. So I need to find the cause of this and fix it. If there was blocking going on, than there must have been exclusive locks somewhere in the chain of stored proc calls…. Right? I walked thru the full list of stored procs that were called, and all of the subsequent stored procs, functions and views. Sometimes this hierarchy was deep and even recursive. I was looking for any UPDATE or INSERT statements…. There weren’t any (except on temporary tables that only had the scope of the stored proc so they didn’t count.) On further research I found the locking is caused by the following: A. If you use a SELECT INTO to create your temp table then SQL Sever places locks on system objects. The following was in our getUserPrivileges proc: --get all permissions for the specified user select permissionLocationId, permissionId, siteNodeHierarchyPermissionId, contactDescr as contactName, l.locationId, description, siteNodeId, roleId into #tmpPLoc from vw_PermissionLocationUsers vplu inner join vw_ContactAllTypes vcat on vplu.contactId = vcat.contactId inner join Location l on vplu.locationId = l.locationId where isSelected = 1 and contactStatusId = 1 and vplu.contactId = @contactId The getUserPrivileges proc is called with every page request (it is in the base pages.) It was not cached like you might expect. It doesn’t look like it, but the SQL above references 23 tables in the FROM or JOIN clauses. None of these table have the “with(nolock)” hint on it so it is taking longer than it should. If I remove the WHERE clause to get an idea of the number of rows involved it returns 159,710 rows and takes 3 to 5 seconds to run (after hours with no one else on the server.) So if this stored proc can only be run one-at-a-time because of the lock, and it is being called once per page, and it holds the locks on the system tables for the duration of the select and temp table creation, you can see how it might be affecting the performance of the whole application. The fix for this would be: 1. Use session level caching so this is only called once per session. 2. Replace the SELECT INTO with code that creates the table using standard Transact-SQL DDL statements, and then use INSERT INTO to populate the table. 3. Put “with(nolock)” on everything involved with this call. B. If the stored proc getUserPrivileges didn’t have enough problems for you, then let me add: it probably gets recompiled on each call. So SQL Server acquires a COMPILE lock on each call. The reason it gets recompiled is because the temp table gets created and then a lot of rows are deleted from it (if a @locationId or @permissionLocationId are passed in). This will cause the stored proc to be recompiled on the SELECT that follows (yes, in the middle of running the stored proc.) In other procs I’ve noticed a DECLARE CURSOR statement whose SELECT statement references a temporary table – this will force a recompile too. For more info on recompilation see: http://support.microsoft.com/kb/243586/en-us The fix for this would be: 1. Again, hit this stored proc far fewer times by using caching. 2. Have the @locationId or @permissionLocationId filtering applied in the WHERE clause while the table is being created. 3. Replace the temp tables with table variables – they result in fewer recompilations. If things don’t work like you expect them to then you can spend a lot of time staring at something without every figuring out what is wrong. A: I fixes someone's bug with the code below : private void foo(Bar bar) { bar = new Bar(); bar.setXXX(yyy); } He was expecting bar will be changed outside foo! A: the toughest bug i ever had was not caused by me, although it caused my code to crash! this was TurboPascal on DOS. The TurboPascal compiler compiler had a minor upgrade and all of a sudden my binary started crashing. turned out that in the new version, memory was allocated starting on segment boundaries only. of course my program never checked for such things because why? how would a programmer know such things? someone on the old compuserve special interest groups posted this clue and the workaround: since segments were 4 words long the fix was to always do a mod(4) to calculate the size of memory to allocate.
{ "language": "en", "url": "https://stackoverflow.com/questions/169713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: Where can I find the Flex source code? I keep hearing that Flex is open source and I figured that a great way to learn about the inner workings would be to look at it. I can easily find the Flex SDK (http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code), but I'm wanting to look at the class definitions for the MXML core library (like NumericStepper). Have I misunderstood, or is this kind of thing available somewhere? Note, I'm looking for the source of some core MXML components so I can see how they work internally, not for the compiler's source. Does what I've linked above have what I'm looking for and I just can't find it in the director structure? A: The source is found in the SVN repository that is here: http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code A: Here's a direct link to the NumericStepper code: http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/frameworks/projects/framework/src/mx/controls/NumericStepper.as And here's the complete code of the framework: http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/frameworks/projects/framework/src/mx/ A: If you have installed the sdk or Flex builder all of the source files are installed locally on your computer, I believe. I have flex builder 3 installed source is located here(depending on where you installed): Source for flex 3 sdk C:\Program Files\Adobe\Flex Builder 3\sdks\3.0.0\frameworks\projects\framework\src\mx Source for flex 2 sdk C:\Program Files\Adobe\Flex Builder 3\sdks\2.0.1\frameworks\source\mx Hope this helps and alleviates the need to be online to view the source... A: The open source stuff appears to be at: http://opensource.adobe.com/wiki/display/flexsdk/Downloads I don't know if everything is available there yet, there may be issues with third-party stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/169721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What's the best word processing component for .NET I'm looking for a word processing component for .NET that would act like an embedded MS Word in my WinForm/WPF .NET app. The main goal being for users to be able to create rich formatted text. I don't really want to have to write a highly custom RichTextBox component. Any suggestions? A: We're using the TXTextControl release 14 for .Net and we're very happy about it. It has all the positive things you can ask: cheap, well supported, up to date with latest Word releases, fast and not really hungry for memory or resources. The included word processor sample is very good code and we converted it in a proper "word control" in about 1 day of work and included it in our solution in another day, so also using it is very simple, also if it has a lot of features. Download it from http://www.textcontrol.com/ A: We have used another Aspose words control to generate word documents in asp.net application and it rendered them perfectly. A: I've only used the ActiveX version of TX Text Control, but it is very good and I'm sure their .NET version is as well. A: Obviously I have no idea what your particular project requirements are, but ScintillaNET is a fabulous control and is flexible enough to do a lot more than just syntax highlighting. I can foresee cases where it certainly wouldn't be appropriate, but it is at least worth investigating. After a fair amount of searching it has perfectly filled a void in an application of mine where I need to do extensive contextual highlighting of prose. Edit I'm revoking this comment because I've thought about it a minute longer and the finite number of styles that Scintilla provides would make it inappropriate for rich text editing. However, it is still an excellent solution for any situation where you can determine programmatically how styling will be applied. A: I use TE Edit control from Subsystems in my app. http://www.subsystems.com/tewf.htm. Works as expected. I did look at TXTextControl around the time I was evaluating. I think it might have been cost that put me off. A: I've been using TinyMCE for about a year now and I love it as a developer and the end users love it, too. It was simple to implement and it's easy to configure which controls the user sees, e.g. the Insert Table button or Paste as Plain Text button. It's also LGPL license, so for our uses at least, we had no costs to worry about. https://www.tiny.cloud/ A: I am the Product Manager of TX Text Control. We listened to requests like this. We have powerful rich text controls for .NET, but you are right: Sometimes, they might be too expensive - even if you don't use all the functionality. Therefore, we released a free version of TX Text Control - free as in beer. http://www.textcontrol.com/en_US/sites/tx-text-control-express/ A: if you use WPF, you can check on http://www.wpftexteditor.com A: I am not sure is this topic still active but I have just the same problem now. I am creating a quotation system in .net winforms and ath the end I have to generate the quote, with product items and some text in .doc. I have scanned the whole net including componentsource and I have found this: - txControl.. knows everything I need but 900$ (it has cheaper edition as well but that do not export to doc - aspose.. it is more for asp i have found also the DSOFramer from Microsoft which is an activeX host for Ms Word. Hm free and gives everything.. of course because it is some kind of word automation. A: I'm the project lead of Aspose.Words. My personal opinion is that if you are building any serious piece of software, especially for business or commercial purposes, you ought to have some budget for tools and $900 is not much for what it does. It costs us to develop after all. But we accept everyone's situation is different, so don't hesitate to post a price question in the Aspose.Purchase forums, maybe you can get what you want. A: We have been using Apose Words and Cells since version 1.0. Both components are solid, but support is kind of a pain. Personally, I'm not a fan of having to work with people in a different time zone, especially when the only way to get in touch with them is a message board.
{ "language": "en", "url": "https://stackoverflow.com/questions/169728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I reference an object dynamically? In Javascript, I have an object: obj = { one: "foo", two: "bar" }; Now, I want do do this var a = 'two'; if(confirm('Do you want One')) { a = 'one'; } alert(obj.a); But of course it doesn't work. What would be the correct way of referencing this object dynamically? A: Like this: obj[a] A: short answer: obj[a] long answer: obj.field is just a shorthand for obj["field"], for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax. A: As a side note, global variables are attached to the "window" object, so you can do var myGlobal = 'hello'; var a = 'myGlobal'; alert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal); This will alert "hello, hello, hello"
{ "language": "en", "url": "https://stackoverflow.com/questions/169731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Best .NET comm component or protocol for very low bandwidth communication? What's the best .NET communication component or protocol for very low bandwidth and intermittently connected communication (i.e.: < 10 kilobits/sec)? A: Probably System.Net.Sockets.Socket. There is also a TcpClient and UdpClient in that namespace. A: You probably want a Socket and TCP/IP for the connection a very low overhead and friendly serialization format is protocoll buffers, a good .NET implementation is protobuf-net A: yeap!, sockets is what you're looking for A: RUDP looks pretty promising.
{ "language": "en", "url": "https://stackoverflow.com/questions/169759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you get non-technical folks to appreciate a non-UI problem? Suppose you're working on an enterprise project in which you have to get management signoff in order for you to develop a new feature set. Usually your management has no problem signing off on some bright shiny new UI feature. Unfortunately they have a hard time appreciating some behind-the-scenes issues that are crucial to the application's well-being such as transactions, data integrity, workflow routing, configurability, security, etc. Since they're non-technical and these issues are not immediately visible, it's not obvious to them that this is crucial. How have you convinced them that these infrastructural issues have to be dealt with and that it is important to their business process? A: Same thing folks have been doing for thousands of years: draw pictures. Diagram the problems, use visual metaphors familiar to your audience, drag the problem into their territory. Assuming they're not being intentionally obtuse... A: A big +1 for analogies and metaphors. If possible, find one that will resonate with the personal interests of your audience (if it's 1-2 people). For general metaphors, I often find myself using commuter traffic or subways, for some reason. e.g. We are currently migrating an app from an OODB to Postgres/Hibernate: the bulk of this work is done in Release '4'. Many domain experts have been asking why there are so few user-facing features in R4. I regularly tell them that we have been 'tearing up the city to put in a subway. It is very expensive and undeniably risky, but once it is done, the benefits in R5+ will be astounding, truly.' The true conversation is more involved, but I can return to this theme again and again, well after R4. Months from now, I hope to say "You asked for X and it is now very easy -- precisely because you let us put in that subway back in R4". A: The surest way to get upper level management to buy off on development work is to present it in a quantifiable way. Ideally this quantifiable measure is in $$. You need to explain to them the consequences of skimping on data integrity, security, transactions, etc. and how that will affect the customer\user community and eventually the bottom line. You should be careful in these situations because sometimes management expects these non-functional requirements to "just work." If this is the case, you should either estimate high and work on these items alongside the visible UI work (ignorance is bliss) or you need to document these areas of need as you communicate with management so if things do go bad as you anticipate, it's not your job that is on the line. A: Every craft has its unsexy sides. Things that HAVE to be done, but nobody notices them directly. In a grocery store somebody has to organize how and when to fill the grocery shelves so they always look fresh. In a laundry you need somebody who thinks about how the processes should be optimized so that the customer gets his clothes in time. The tricky part is: The customer won't notice when these subtle things have been done right UNTIL HE NOTICES THEY ARE MISSING! Like when the laundry is not ready on time but two days late, or the veggies in the super market have brown spots and look terrible. Same goes for IT. You don't notice good transactions until your major customer knocks on your door and tells you that an important and expensive project has failed because the database entries of your product were mysteriously mixed up. You don't notice good security until customer credit card information shows up in Elbonia (and soon after word is in the national newspapers warning customers of your company). The thing you really have to hammer in again and again and again is that software is NOT static. It has to be cared for even after its initial development phase is over. It is not just a product you buy once and forget about. Every car manufacturer knows that services is of prime importance to the products they build, simply because things WILL occur that have to be fixed and improved. It's the same with software. So make a presentation, visualize, verbalize, translate your technical information into benefits. Business people don't care about your wish for code aesthetics in a refactoring project, but they WILL understand that your changes will help the product to become more reliable, gain a better reputation and reduce the amount of future service requests. Make them understand by showing them the benefits! A: Unfortunately, it usually takes a disaster or two before this stuff gets the attention it deserves. It really depends what your management is like, but I've had luck with good old honest-to-goodness fearmongering. If you go through a couple of disaster scenarios, and point out someone's going to get blamed if they occur, that can be enough to make their arsecovering instincts kick in and finally pay attention :) A: I'm battling with essentially the same kind of situation. Whether it is sign-off by management or acceptance by a user/sponsor, the problem remains one of different vocabularies, priorities and perspectives. I asked a simmilar question here. I also got diverse answers, tantalizingly close to useful, but not quite definitive enough. Browsing and searching SO using relevant keywords led me to find usable insights in various answers spread out over many unrelated questions. To find and extract these gems led me to pose this question on site-mining. It would have been useful to be able to flag the various answers and see them all in a single list, but alas, that functionality is not yet available in SO. I suggested it on uservoice. Hope you find something you can use from the references I gave. A: Car analogies. Everybody knows that 'system' and it's sufficiently complex to depict the dire situation. A: The right kind of countering question is the secret. * *Is it okay to crash every 5 web pages? *Do we have to protect the credit card numbers? *Is is okay to have to pay contractors to deploy a patch every weekend? *Did you want it now or did you want it to work? A: Robustness. When it comes down to it, you need to talk their language, which is how it affects their bottom line. If its a security or correctness issue, you need to tell them that customers aren't going to want incorrectly acting products, no matter how nice they look. A: A descriptive picture really helps non-technical people understand what you are talking about. For example, below is an example from Sun describing how information is processed in one of their somewhat complex applications. (source: sun.com) Trying to explain this application in words would be impossible to a non-techy. Pointing at the diagram and say look, this part is our weak point, we need to improve it. That will make sense to them. If they feel like they have some understanding of what you are doing, they will be far more willing to support your request. A: I like the idea of Technical Debt, because it enables technical issues to be translated (albeit loosely) into money issues -- and money is something most managers do understand. Although the idea of technical debt was originally applied to architectural issues, it can be used more broadly for any type of situation where there is pressure to take a shortcut -- that is, go into technical debt -- rather than do it right the first time. (Doing it right is the equivalent to saving up to buy something -- it takes time -- rather than buying it on credit and going into debt.) Just as debts can be good (e.g. home loans) and bad (e.g. credit cards), so technical debt can be good and bad. I won't try to characterise the differences completely, but good technical debt can be tracked accurately, so that you know how much in debt you are. So, try to explain your important, non-UI problem in terms of technical debt, and the cost of not fixing it in terms of paying interest on that debt.
{ "language": "en", "url": "https://stackoverflow.com/questions/169765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Not getting the correct count in SQL I am totally new to SQL. I have a simple select query similar to this: SELECT COUNT(col1) FROM table1 There are some 120 records in the table and shown on the GUI. For some reason, this query always returns a number which is less than the actual count. Can somebody please help me? A: Try select count(*) from table1 Edit: To explain further, count(*) gives you the rowcount for a table, including duplicates and nulls. count(isnull(col1,0)) will do the same thing, but slightly slower, since isnull must be evaluated for each row. A: You might have some null values in col1 column. Aggregate functions ignore nulls. try this SELECT COUNT(ISNULL(col1,0)) FROM table1 A: Slightly tangential, but there's also the useful SELECT count(distinct cola) from table1 which gives you number of distinct column in the table. A: You are getting the correct count As per https://learn.microsoft.com COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates an expression for each row in a group and returns the number of nonnull values. COUNT(DISTINCT expression) evaluates an expression for each row in a group and returns the number of unique, non null values. In your case you have passed the column name in COUNT that's why you will get count of not null records, now you're in your table data you may have null values in given column(col1) Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/169784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I dynamically add Panels to other panels at runtime in Java? I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this. When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically. I've been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event. Here is the code that I thought would work: mainPanel.add(new BlurbEditor()); mainPanel.revalidate(); //I've also tried all possible combinations of these too //mainPanel.repaint(); //mainPanel.validate(); This unfortunately is not working. What am I doing wrong? A: Swing/AWT components generally have to have a layout before you add things to them - otherwise the UI won't know where to place the subcomponents. BFreeman has suggested BorderLayout which is one of the easiest ones to use and allows you to 'glue' things to the top, bottom, left, right or center of the parent. There are others such as FlowLayout which is like a textarea - it adds components left-to-right at the top of the parent and wraps onto a new row when it gets to the end. The GridBagLayout which has always been notorious for being impossible to figure out, but does give you nearly all the control you would need. A bit like those HTML tables we used to see with bizarre combinations of rowspan, colspan, width and height attributes - which never seemed to look quite how you wanted them. A: I figured it out. The comments under the accepted answer here explain it: Dynamically added JTable not displaying Basically I just added the following before the mainPanel.add() mainPanel.setLayout(new java.awt.BorderLayout()); A: I was dealing with similar issue, I wanted to change the panel contained in a panel on runtime After some testing, retesting and a lot of failing my pseudo-algorithm is this: parentPanel : contains the panel we want to remove childPanel : panel we want to switch parentPanelLayout : the layout of parentPanel editParentLayout() : builds parentPanel with different childPanel and NEW parentPanelLayout every time parentPanel.remove(childPanel); editParentLayout(); parentPanel.revalidate(); parentPanel.repaint(); A: As with all swing code, don't forget to call any gui update within event dispatch thread. See this for why you must do updates like this // Do long running calculations and other stuff outside the event dispatch thread while (! finished ) calculate(); SwingUtilities.invokeLater(new Runnable(){ public void run() { // update gui here } } A: mainPanel.add(new BlurbEditor()); mainPanel.validate(); mainPanel.repaint(); A: Try mainPanel.invalidate() and then if necessary, mainPanel.validate(). It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.
{ "language": "en", "url": "https://stackoverflow.com/questions/169799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: 2D animation in Python I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images. I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it won't be able to sufficiently scale in terms of performance or capabilities. Requirements are: * *Cross-platform (Linux, MacOS X, Windows) *Low complexity overhead *Plays well with wxpython (at least won't step on each other's toes unduly) *Interactivity. Detect when objects are clicked on, moused over, etc. Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good. Your thoughts? A: You can try pygame, its very easy to handle and similar to SDL under c++ A: Arcade works on any platform with OpenGL 3.3+ (i.e. not the Raspberry Pi, but most other platforms). Although it's intended for simple games, Arcade offers great bitmap and sprite handling, as well as simple graphics primitives such as rectangles, arcs and circles. A: I am a fan of pyglet which is a completely self contained library for doing graphical work under win32, linux, and OS X. It has very low overhead, and you can see this for yourself from the tutorial on the website. It should play well with wxpython, or at least I seem to recall posts to the mailing list about wxpython and pyglet being used together. It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do. mactorii is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P
{ "language": "en", "url": "https://stackoverflow.com/questions/169810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Will there be a functional language which does for the Java community what F# does for the .NET community? Will there be a functional language which does for the Java community what F# does for the .NET community? What functional programming languages are available, or in development, for the JVM? A: Scala would be the language. Though not strictly functional (it's a mix of functional and object-oriented) and it is not strictly for Java (there is a .NET version of Scala), that would be the closest analog to F# in the JVM. A: For now I would say Scala. But for the future, I'd have a look at Fortress. The first implementation of the spec was released on April 1, 2008. And no, that is not a joke. Key featues are: * *Statically typed, but a lot of type inference to avoid clutter *Unicode and 2d rendering of mathematical functions *Designed for parallel execution (for each defaults to it) *Strong support for custom libraries (Guy Steele's influence) *Operator overloading, including the juxtaposition operator More info at the Project Fortress Community website and the Wikipedia Fortress page. A: The first thing that came to my mind was Scala but really Ocaml-Java comes closer as F# is a variant of Ocaml. See this post that compares Ocaml-Java to Scala: OCaml programmers are typically over 10x as productive as Java or C++ programmers for a wide range of practical tasks. Despite being based upon a fundamentally OOP platform, F# goes a long way to capturing the productivity- boosting benefits of OCaml (and the whole ML family). In contrast, Scala fails to capture many of the benefits including some really basic ones and, consequently, writing correct code is much more difficult in Scala than in any real ML. Moreover, the ML family of languages are designed to be succinct but Scala is needlessly verbose for everything from "Hello world!" upwards. The ML family of languages provide extensive type inference (OCaml more than most) but Scala has only rudimentary inference by comparison. OCaml has an unusually expressive type system but Scala adds little to OOP that is of practical importance. A: Arguably none because the JVM lacks tail calls and they are required to make almost all functional code robust with respect to stack consumption. The nearest thing to functional language implementations on the JVM are Clojure, Scala and the OCaml-Java project. Although there are workarounds for the lack of tail calls (e.g. trampolining), none of these language implementations do this because the workarounds introduce even more serious problems, e.g. crippling performance and completely obfuscating debugging. Sun have been talking about tail calls for years and, more recently, have indicated that they intend to implement them imminently. As soon as that is done, I am sure we will see a lot more language diversity on the JVM and, in particular, some production-quality functional language implementations. Until then, I regard all of these languages as toys. Cheers, Jon Harrop. A: There's a good list of programming languages for JVM, including functional programming paradigm and other paradigm languages on: * *en.wikipedia.org/wiki/List_of_JVM_languages My first pick is Scala (multi-paradigm; OO & FP), I spent a 5+ months studing Scala in 2009, and created a quick reference sheet: bchiprog.blogspot.com/2009/05/scala-cheat-sheet.html I noticed there are other programming paradigms that are interesting, other focuses on parallel processing such as X10, Fortress, and Chapel. X10 is implemented on top of Scala - http://www.scala-lang.org/sites/default/files/odersky/scalaliftoff2009.pdf It's really based on what problem you need to solve then pick the language that can best solve it. I think it's developers' wish that there's one language that can solve any type of problem easily and doing it simply. A: Perhaps Clojure. It's not statically typed, but it has more of an emphasis on immutability and concurrency than F#. However, like F# (and unlike Common Lisp), it is intended to be a primarily functional language that is good at consuming OO libraries from the underlying platform. A: @Marc Gravell - functional languages are increasingly used in the guts of enterprise grade financial systems. We use many functional (pure or "semi-pure") at the bank I work for... A: Meanwhile, there is Frege, a pure functional, non-strict language in the spirit of Haskell that compiles to Java, which then is compiled further with javac or the eclipse compiler, depending on the environment (command-line or eclipse). A: Actually, I might be wrong, but I don't expect F# to be as mainstream as the other .NET languages; useful in a few circles (academic, compilers, a few other scenarios) - however, don't forget that C# offers FP usage - and it gets better each time: C# 1.2 has delegates; C# 2.0 has anonymous methods and captures/closures; C# 3.0 has lambdas for simplicity, and Expression for abstraction. Anonymous types (C# 3.0) share some similarity with tuples (in terms of convenience), but obviously are very different beasts, so definitely not a like-for-like comparison. Maybe not quite as optimised as F#, but for most day-to-day FP use-cases, more than sufficient. It is also quite clear that better support for immutability (especially for threading) is very much on the minds of the C# language team for future consideration. My money is on C# getting better at FP, and being the .NET FP offering for most day-to-day purposes. Of course, there will be some F# usage - but (purely subjective) I simply don't see there being a huge migration. A: I would add https://eta-lang.org to the suggestions -- it's basically a Haskell for the JVM. I think the question is in line with the fact that F# is an ML language, while Clojure is a dialect of LISP.
{ "language": "en", "url": "https://stackoverflow.com/questions/169812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to find the distance between the two most widely separated nodes I'm working through previous years ACM Programming Competition problems trying to get better at solving Graph problems. The one I'm working on now is I'm given an arbitrary number of undirected graph nodes, their neighbors and the distances for the edges connecting the nodes. What I NEED is the distance between the two farthest nodes from eachother (the weight distance, not by # of nodes away). Now, I do have Dijkstra's algorithm in the form of: // Dijkstra's Single-Source Algorithm private int cheapest(double[] distances, boolean[] visited) { int best = -1; for (int i = 0; i < size(); i++) { if (!visited[i] && ((best < 0) || (distances[i] < distances[best]))) { best = i; } } return best; } // Dijkstra's Continued public double[] distancesFrom(int source) { double[] result = new double[size()]; java.util.Arrays.fill(result, Double.POSITIVE_INFINITY); result[source] = 0; // zero distance from itself boolean[] visited = new boolean[size()]; for (int i = 0; i < size(); i++) { int node = cheapest(result, visited); visited[node] = true; for (int j = 0; j < size(); j++) { result[j] = Math.min(result[j], result[node] + getCost(node, j)); } } return result; } With this implementation I can give it a particular node and it will give me a list of all the distances from that node. So, I could grab the largest distance in that list of distances but I can't be sure that any particular node is one of the two furthest ones at either end. So the only solution I can think of is to run this Dijkstra's algorithm on every node, go through each returned list of distances and looking for the largest distance. After exhausting each node returning it's list of distances I should have the value of the largest distance between any two nodes (the "road" distance between the two most widely seperated villages). There has got to be an easier way to do this because this seems really computationally expensive. The problem says that there could be sample inputs with up to 500 nodes so I wouldn't want it to take prohibitively long. Is this how I should do it? Here is a sample input for the problem: Total Nodes: 5 Edges: Nodes 2 - Connect - Node 4. Distance/Weight 25 Nodes 2 - Connect - Node 5. Distance/Weight 26 Nodes 3 - Connect - Node 4. Distance/Weight 16 Nodes 1 - Connect - Node 4. Distance/Weight 14 The answer to this sample input is "67 miles". Which is the length of the road between the two most widely separated villages. So should I do it how I described or is there a much simpler and much less computationally expensive way? A: It looks like you can use either of: * *Floyd Warshall algorithm *Johnson's algorithm. I can't give you much guidance about them though - I'm no expert. A: So there's an implementation of Dijkstra which runs O(VlogV + E) giving your approach a complexity of roughly V^2logV + VE. See DADS. But perhaps more intuitive would be to run one of the all pairs shortest path algorithms like Floyd-Warshall or Johnsons. Unfortunately they're all roughly O(V^3) for dense graphs (close to the complete graph where E = V^2). A: Is this the Roads in the North problem? A: You can use your Dijkstra's implementation as follows: * *Pick a random node,(a), run Dijkstra from node a, and find the furthest node from it. Mark that node as node b. *Run Dijkstra again starting at node b, and find the furthest node from it. Mark that node as node c. I don't have proof for this, but I think b and c will be furthest away nodes. You might need to run one more iteration (I'm still thinking about it). A: Multiply the edge weights by -1 and find the shortest path on the new graph. That would be the longest path on the original graph A: If you want the longest shortest path that is sup i,j {inf i,j {n : n=length of a path between i and j}} you should certainly consider a all nodes shortest path algorithm like Flyod-Warshall as mentioned by others. This would be in the order of O(V^3). If you want the longest possible path that is sup i,j {n : n=length of a path between i and j} you could try to use Midhat's idea. (which really is as complex as the original problem as pointed out in the comments) I would recommend to invert the weights with 1/w though, to retain positive weights, given the original weights were strict positive. Another algorithm you might want to look up when dealing with negative weights is the algorithm of Bellman and Ford
{ "language": "en", "url": "https://stackoverflow.com/questions/169814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java - Common Gotchas In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't. I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for. See also: * *Perl - Common gotchas *.NET - Common gotchas A: Manipulating Swing components from outside the event dispatch thread can lead to bugs that are extremely hard to find. This is a thing even we (as seasoned programmers with 3 respective 6 years of java experience) forget frequently! Sometimes these bugs sneak in after having written code right and refactoring carelessly afterwards... See this tutorial why you must. A: Immutable strings, which means that certain methods don't change the original object but instead return a modified object copy. When starting with Java I used to forget this all the time and wondered why the replace method didn't seem to work on my string object. String text = "foobar"; text.replace("foo", "super"); System.out.print(text); // still prints "foobar" instead of "superbar" A: I think i big gotcha that would always stump me when i was a young programmer, was the concurrent modification exception when removing from an array that you were iterating: List list = new ArrayList(); Iterator it = list.iterator(); while(it.hasNext()){ //some code that does some stuff list.remove(0); //BOOM! } A: if you have a method that has the same name as the constructor BUT has a return type. Although this method looks like a constructor(to a noob), it is NOT. passing arguments to the main method -- it takes some time for noobs to get used to. passing . as the argument to classpath for executing a program in the current directory. Realizing that the name of an Array of Strings is not obvious hashCode and equals : a lot of java developers with more than 5 years experience don't quite get it. Set vs List Till JDK 6, Java did not have NavigableSets to let you easily iterate through a Set and Map. A: Integer division 1/2 == 0 not 0.5 A: Using the ? generics wildcard. People see it and think they have to, e.g. use a List<?> when they want a List they can add anything to, without stopping to think that a List<Object> already does that. Then they wonder why the compiler won't let them use add(), because a List<?> really means "a list of some specific type I don't know", so the only thing you can do with that List is get Object instances from it. A: The default hash is non-deterministic, so if used for objects in a HashMap, the ordering of entries in that map can change from run to run. As a simple demonstration, the following program can give different results depending on how it is run: public static void main(String[] args) { System.out.println(new Object().hashCode()); } How much memory is allocated to the heap, or whether you're running it within a debugger, can both alter the result. A: (un)Boxing and Long/long confusion. Contrary to pre-Java 5 experience, you can get a NullPointerException on the 2nd line below. Long msec = getSleepMsec(); Thread.sleep(msec); If getSleepTime() returns a null, unboxing throws. A: When you create a duplicate or slice of a ByteBuffer, it does not inherit the value of the order property from the parent buffer, so code like this will not do what you expect: ByteBuffer buffer1 = ByteBuffer.allocate(8); buffer1.order(ByteOrder.LITTLE_ENDIAN); buffer1.putInt(2, 1234); ByteBuffer buffer2 = buffer1.duplicate(); System.out.println(buffer2.getInt(2)); // Output is "-771489792", not "1234" as expected A: "a,b,c,d,,,".split(",").length returns 4, not 7 as you might (and I certainly did) expect. split ignores all trailing empty Strings returned. That means: ",,,a,b,c,d".split(",").length returns 7! To get what I would think of as the "least astonishing" behaviour, you need to do something quite astonishing: "a,b,c,d,,,".split(",",-1).length to get 7. A: Comparing equality of objects using == instead of .equals() -- which behaves completely differently for primitives. This gotcha ensures newcomers are befuddled when "foo" == "foo" but new String("foo") != new String("foo"). A: I think a very sneaky one is the String.substring method. This re-uses the same underlying char[] array as the original string with a different offset and length. This can lead to very hard-to-see memory problems. For example, you may be parsing extremely large files (XML perhaps) for a few small bits. If you have converted the whole file to a String (rather than used a Reader to "walk" over the file) and use substring to grab the bits you want, you are still carrying around the full file-sized char[] array behind the scenes. I have seen this happen a number of times and it can be very difficult to spot. In fact this is a perfect example of why interface can never be fully separated from implementation. And it was a perfect introduction (for me) a number of years ago as to why you should be suspicious of the quality of 3rd party code. A: Overriding equals() but not hashCode() It can have really unexpected results when using maps, sets or lists. A: Among the common pitfalls, well known but still biting occasionally programmers, there is the classical if (a = b) which is found in all C-like languages. In Java, it can work only if a and b are boolean, of course. But I see too often newbies testing like if (a == true) (while if (a) is shorter, more readable and safer...) and occasionally writing by mistake if (a = true), wondering why the test doesn't work. For those not getting it: the last statement first assign true to a, then do the test, which always succeed! - One that bites lot of newbies, and even some distracted more experienced programmers (found it in our code), the if (str == "foo"). Note that I always wondered why Sun overrode the + sign for strings but not the == one, at least for simple cases (case sensitive). For newbies: == compares references, not the content of the strings. You can have two strings of same content, stored in different objects (different references), so == will be false. Simple example: final String F = "Foo"; String a = F; String b = F; assert a == b; // Works! They refer to the same object String c = "F" + F.substring(1); // Still "Foo" assert c.equals(a); // Works assert c == a; // Fails - And I also saw if (a == b & c == d) or something like that. It works (curiously) but we lost the logical operator shortcut (don't try to write: if (r != null & r.isSomething())!). For newbies: when evaluating a && b, Java doesn't evaluate b if a is false. In a & b, Java evaluates both parts then do the operation; but the second part can fail. [EDIT] Good suggestion from J Coombs, I updated my answer. A: SimpleDateFormat is not thread safe. A: There are two that annoy me quite a bit. Date/Calendar First, the Java Date and Calendar classes are seriously messed up. I know there are proposals to fix them, I just hope they succeed. Calendar.get(Calendar.DAY_OF_MONTH) is 1-based Calendar.get(Calendar.MONTH) is 0-based Auto-boxing preventing thinking The other one is Integer vs int (this goes for any primitive version of an object). This is specifically an annoyance caused by not thinking of Integer as different from int (since you can treat them the same much of the time due to auto-boxing). int x = 5; int y = 5; Integer z = new Integer(5); Integer t = new Integer(5); System.out.println(5 == x); // Prints true System.out.println(x == y); // Prints true System.out.println(x == z); // Prints true (auto-boxing can be so nice) System.out.println(5 == z); // Prints true System.out.println(z == t); // Prints SOMETHING Since z and t are objects, even they though hold the same value, they are (most likely) different objects. What you really meant is: System.out.println(z.equals(t)); // Prints true This one can be a pain to track down. You go debugging something, everything looks fine, and you finally end up finding that your problem is that 5 != 5 when both are objects. Being able to say List<Integer> stuff = new ArrayList<Integer>(); stuff.add(5); is so nice. It made Java so much more usable to not have to put all those "new Integer(5)"s and "((Integer) list.get(3)).intValue()" lines all over the place. But those benefits come with this gotcha. A: Try reading Java Puzzlers which is full of scary stuff, even if much of it is not stuff you bump into every day. But it will destroy much of your confidence in the language. A: List<Integer> list = new java.util.ArrayList<Integer>(); list.add(1); list.remove(1); // throws... The old APIs were not designed with boxing in mind, so overload with primitives and objects. A: The non-unified type system contradicts the object orientation idea. Even though everything doesn't have to be heap-allocated objects, the programmer should still be allowed to treat primitive types by calling methods on them. The generic type system implementation with type-erasure is horrible, and throws most students off when they learn about generics for the first in Java: Why do we still have to typecast if the type parameter is already supplied? Yes, they ensured backward-compatibility, but at a rather silly cost. A: This one I just came across: double[] aList = new double[400]; List l = Arrays.asList(aList); //do intense stuff with l Anyone see the problem? What happens is, Arrays.asList() expects an array of object types (Double[], for example). It'd be nice if it just threw an error for the previous ocde. However, asList() can also take arguments like so: Arrays.asList(1, 9, 4, 4, 20); So what the code does is create a List with one element - a double[]. I should've figured when it took 0ms to sort a 750000 element array... A: this one has trumped me a few times and I've heard quite a few experienced java devs wasting a lot of time. ClassNotFoundException --- you know that the class is in the classpath BUT you are NOT sure why the class is NOT getting loaded. Actually, this class has a static block. There was an exception in the static block and someone ate the exception. they should NOT. They should be throwing ExceptionInInitializerError. So, always look for static blocks to trip you. It also helps to move any code in static blocks to go into static methods so that debugging the method is much more easier with a debugger. A: Floats I don't know many times I've seen floata == floatb where the "correct" test should be Math.abs(floata - floatb) < 0.001 I really wish BigDecimal with a literal syntax was the default decimal type... A: Not really specific to Java, since many (but not all) languages implement it this way, but the % operator isn't a true modulo operator, as it works with negative numbers. This makes it a remainder operator, and can lead to some surprises if you aren't aware of it. The following code would appear to print either "even" or "odd" but it doesn't. public static void main(String[] args) { String a = null; int n = "number".hashCode(); switch( n % 2 ) { case 0: a = "even"; break; case 1: a = "odd"; break; } System.out.println( a ); } The problem is that the hash code for "number" is negative, so the n % 2 operation in the switch is also negative. Since there's no case in the switch to deal with the negative result, the variable a never gets set. The program prints out null. Make sure you know how the % operator works with negative numbers, no matter what language you're working in. A: Going first, here's one I caught today. It had to do with Long/long confusion. public void foo(Object obj) { if (grass.isGreen()) { Long id = grass.getId(); foo(id); } } private void foo(long id) { Lawn lawn = bar.getLawn(id); if (lawn == null) { throw new IllegalStateException("grass should be associated with a lawn"); } } Obviously, the names have been changed to protect the innocent :) A: Another one I'd like to point out is the (too prevalent) drive to make APIs generic. Using well-designed generic code is fine. Designing your own is complicated. Very complicated! Just look at the sorting/filtering functionality in the new Swing JTable. It's a complete nightmare. It's obvious that you are likely to want to chain filters in real life but I have found it impossible to do so without just using the raw typed version of the classes provided. A: System.out.println(Calendar.getInstance(TimeZone.getTimeZone("Asia/Hong_Kong")).getTime()); System.out.println(Calendar.getInstance(TimeZone.getTimeZone("America/Jamaica")).getTime()); The output is the same. A: I had some fun debugging a TreeSet once, as I was not aware of this information from the API: Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeSet.html Objects with correct equals/hashcode implementations were being added and never seen again as the compareTo implementation was inconsistent with equals. A: IMHO 1. Using vector.add(Collection) instead of vector.addall(Collection). The first adds the collection object to vector and second one adds the contents of collection. 2. Though not related to programming exactly, the use of xml parsers that come from multiple sources like xerces, jdom. Relying on different parsers and having their jars in the classpath is a nightmare.
{ "language": "en", "url": "https://stackoverflow.com/questions/169815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Is it possible to query a tree structure table in MySQL in a single query, to any depth? I'm thinking the answer is no, but I'd love it it anybody had any insight into how to crawl a tree structure to any depth in SQL (MySQL), but with a single query More specifically, given a tree structured table (id, data, data, parent_id), and one row in the table, is it possible to get all descendants (child/grandchild/etc), or for that matter all ancestors (parent/grandparent/etc) without knowing how far down or up it will go, using a single query? Or is using some kind of recursion require, where I keep querying deeper until there are no new results? Specifically, I'm using Ruby and Rails, but I'm guessing that's not very relevant. A: Yes, this is possible, it's a called a Modified Preorder Tree Traversal, as best described here Joe Celko's Trees and Hierarchies in SQL for Smarties A working example (in PHP) is provided here http://www.sitepoint.com/article/hierarchical-data-database/2/ A: Daniel Beardsley's answer is not that bad a solution at all when the main questions you are asking are 'what are all my children' and 'what are all my parents'. In response to Alex Weinstein, this method actually results in less updates to nodes on a parent movement than in the Celko technique. In Celko's technique, if a level 2 node on the far left moves to under a level 1 node on the far right, then pretty much every node in the tree needs updating, rather than just the node's children. What I would say however is that Daniel possibly stores the path back to root the wrong way around. I would store them so that the query would be SELECT FROM table WHERE ancestors LIKE "1,2,6%" This means that mysql can make use of an index on the 'ancestors' column, which it would not be able to do with a leading %. A: Here are several resources: * *http://forums.mysql.com/read.php?10,32818,32818#msg-32818 *Managing Hierarchical Data in MySQL *http://lists.mysql.com/mysql/201896 Basically, you'll need to do some sort of cursor in a stored procedure or query or build an adjacency table. I'd avoid recursion outside of the db: depending on how deep your tree is, that could get really slow/sketchy. A: I came across this problem before and had one wacky idea. You could store a field in each record that is concatenated string of it's direct ancestors' ids all the way back to the root. Imagine you had records like this (indentation implies heirarchy and the numbers are id, ancestors. * *1, "1" * *2, "2,1" * *5, "5,2,1" *6, "6,2,1" * *7, "7,6,2,1" *11, "11,6,2,1" *3, "3,1" * *8, "8,3,1" *9, "9,3,1" *10, "10,3,1" Then to select the descendents of id:6, just do this SELECT FROM table WHERE ancestors LIKE "%6,2,1" Keeping the ancestors column up to date might be more trouble than it's worth to you, but it's feasible solution in any DB. A: Celko's technique (nested sets) is pretty good. I also have used an adjacency table with fields "ancestor" and "descendant" and "distance" (e.g. direct children/parents have a distance of 1, grandchildren/grandparents have a distance of 2, etc). This needs to be maintained, but is fairly easy to do for inserts: you use a transaction, then put the direct link (parent, child, distance=1) into the table, then INSERT IGNORE a SELECTion of existing parent&children by adding distances (I can pull up the SQL when I have a chance), which wants an index on each of the 3 fields for performance. Where this approach gets ugly is for deletions... you basically have to mark all the items that have been affected and then rebuild them. But an advantage of this is that it can handle arbitrary acyclic graphs, whereas the nested set model can only do straight hierarchies (e.g. each item except the root has one and only one parent). A: SQL isn't a Turing Complete language, which means you're not going to be able to perform this sort of looping. You can do some very clever things with SQL and tree structures, but I can't think of a way to describe a row which has a certain id "in its hierarchy" for a hierarchy of arbitrary depth. Your best bet is something along the lines of what @Dan suggested, which is to just work your way through the tree in some other, more capable language. You can actually generate a query string in a general-purpose language using a loop, where the query is just some convoluted series of joins (or sub-queries) which reflects the depth of the hierarchy you are looking for. That would be more efficient than looping and multiple queries. A: This can definitely be done and it isn't that complicated for SQL. I've answered this question and provided a working example using mysql procedural code here: MySQL: How to find leaves in specific node Booth: If you are satisfied, you should mark one of the answers as accepted. A: I used the "With Emulator" routine described in https://stackoverflow.com/questions/27013093/recursive-query-emulation-in-mysql (provided by https://stackoverflow.com/users/1726419/yossico). So far, I've gotten very good results (performance wise), but I don't have an abundance of data or a large number of descendents to search through/for. A: You're almost definitely going to want to employ some recursion for that. And if you're doing that, then it would be trivial (in fact easier) to get the entire tree rather than bits of it to a fixed depth. In really rough pseudo-code you'll want something along these lines: getChildren(parent){ children = query(SELECT * FROM table WHERE parent_id = parent.id) return children } printTree(root){ print root children = getChildren(root) for child in children { printTree(child) } } Although in practice you'd rarely want to do something like this. It will be rather inefficient since it's making one request for every row in the table, so it'll only be sensible for either small tables, or trees that aren't nested too deeply. To be honest, in either case you probably want to limit the depth. However, given the popularity of these kinds of data structure, there may very well be some MySQL stuff to help you with this, specifically to cut down on the numbers of queries you need to make. Edit: Having thought about it, it makes very little sense to make all these queries. If you're reading the entire table anyway, then you can just slurp the whole thing into RAM - assuming it's small enough!
{ "language": "en", "url": "https://stackoverflow.com/questions/169817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "58" }
Q: Object-relational mapping: What's the best way to implement getters? What should happen when I call $user->get_email_address()? Option 1: Pull the email address from the database on demand public function get_email_address() { if (!$this->email_address) { $this->read_from_database('email_address'); } return $this->email_address; } Option 2: Pull the email address (and the other User attributes) from the database on object creation public function __construct(..., $id = 0) { if ($id) { $this->load_all_data_from_db($id); } } public function get_email_address() { return $this->email_address; } My basic question is whether it's best to minimize the number of database queries, or whether it's best to minimize the amount of data that gets transferred from the database. Another possibility is that it's best to load the attributes that you'll need the most / contain the least data at object creation and everything else on demand. A follow-up question: What do ORM abstraction frameworks like Activerecord do? A: There really isn't a correct answer for this. Depends on how many users you're loading at once, how many text/blob fields are in your User table, whether your user table loads any associated child objects. As aaronjensen says, this pattern is called lazy loading - and the opposite behaviour (loading everything up front just in case you need it) is known as eager loading. That said, there is a third option you might want to consider, which is lazy-loading the entire User object when any of its properties are accessed: public function get_email_address() { if (!$this->email_address) { $this->load_all_data_from_db($this->id) } return $this->email_address; } Advantages of this approach are that you can create a collection of users (e.g. a list of all users whose passwords are blank, maybe?) based on their IDs only, without the memory hit of fully loading every single user, but then you only require a single database call for each user to populate the rest of the user fields. A: Minimize the number of queries. The optimal # of queries is 0, but if you must query because it's not cached, it's 1. Querying for every property is a sure fire way to a system that will never scale, has massive contention issues, and will cause way more headaches than its worth. I should mention that there is value to lazy loading (which is what you're talking about in step 1) if it's unlikely that you will need the data being lazily loaded. If you can though, it's best to be explicit, and fetch exactly or nearly exactly what you need. The less time you spend querying, the less time your connection is open and the more scalable your system is. A: I would agree with aaronjensen, except when the amount of data you are pulling is to so great that you'll start to use up an excessive amount of memory. I'm thinking where a row has 3 text fields that are all quite large and all you want is the ID field.
{ "language": "en", "url": "https://stackoverflow.com/questions/169818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What are the real benefits of Visual Studio Team System Database Edition (GDR)? Interested if anyone has used VSTS Database Edition extensively and, if so, which features did you find the most useful over the standard Visual Studio database projects? What are the most compelling features as opposed to alternative schema management options or tools like RedGate's SqlCompare etc? Edit: Microsoft just released the RTM version of Database Edition (GDR) which adds support for SQL Server 2008 - link is here. I've previously blogged (briefly) about it here. Has anyone had a chance to do any real work with the GDR? It looks like there are some real enhancements including refactoring support. I'd be really interested to hear if people are using it with SQL Server 2008... Download From: [http://www.microsoft.com/downloads/details.aspx?FamilyID=bb3ad767-5f69-4db9-b1c9-8f55759846ed&displaylang=en] A: If you compare it to tool like RedGates, that are specifically taylored for SQL Server, the benefits are that if you have the proper MSDN subscription you do not have to spend more money for other tools (but keep in mind that RedGate tools are much more mature) and it covers some points (like regression tests and unit tests at the DB level) that other tools do not cover and it make so in a integrate manner with other testing tool of VSTS, so that you can record results in Team System. Compared to a tool like Embarcadero ErStudio (my solution of choice) it misses the cross database features, and this is a big problem, at least for me. If you are a "all Microsoft" shop with the proper MSDN subscription it could be worth spending time on it. A: We use the database edition functionality of Team Suite on Stack Overflow. As Vaibhav said, mostly it is useful because it gives you a one-click way to reverse engineer a database into source control, and keep it up to date. Note that it also has decent Data and Schema compare tools as well. You can compare projects to physical databases and vice-versa. This makes it pretty easy to keep your database up to date, no matter where you make changes -- in the filesystem database project, or in the physical database itself. A: We are currently using the GDR 2008 projects for managing our entire database development and deployment on a greenfield system. We use a TFS build script to call out to the MSBuild task for deploying the databases along with executing the data generation plans for pre populating the testing environment with data. The key with the data generation plans was finding the build task to use which is : TaskName="DataGeneratorTask" AssemblyName="Microsoft.Data.Schema.Tasks, Version=9.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" All of this gdr project work has been unbelievably helpful and I think it is well worth the learning curve to get to know these project types. The value they provide is astronomical in productivity and visibility. It allows us all to view the entire system in a single visual studio solution along with allowing us to start with a clean slate of our system at any point in time with either a click of the deploy command or a custom build configuration. This blog will help with getting the TFSBuild script to run if you're interested. A: The VSDB test integration is so painful to configure that we abandoned it, and that's the only thing it's got that Red-Gate doesn't. Red-Gate's tool is miles more useful. It does live DB and scripts in folders, but also has "snapshots." The aspect of Red-Gate SQL Compare that gives it the win is its Snapshot ability and the fact that your license allows you to deploy their assemblies and use them to perform database maintenance at customer run-time. It has made upgrades in the COTS application that I develop a breeze. A Snapshot is a binary schema representation. You can package them as resources in an assembly, then use the snapshot in a customer run-time schema compare to bring an existing database up to the current rev. A: Probably the best advantages are around being able to version control individual DB schema objects (which you could do with the older "Database Projects"), but have the power to "build"/deploy the project and convert those individual scripts into a complete database. The ability to import scripts and have the Wizard covert individual schema items into separate files is very handy if you've inherited a DB schema. Given that recently the licensing model changed, it makes it even more enticing because it's included with the Developer edition SKU. It also provised support for "Database Unit Tests" which might be useful. From the 2008 GDR, I understand that they now support SQL Server 2008. A: You can do database versioning for one. That is useful. The other thing that is really useful is the ability to define type of seed data for testing. Through this Visual Studio will populate the database with random data and this is great for testing purposes. There are other benefits as well of course. A: It is always useful to put everything under the same source control, so your data-dude can be shelving, checking in, compare with history, and even resolve workitems and bugs using the same tools that other team members are using. Also to be able to have one versionning mechanism across the whole application, in other words, it doesn't make sense to say that my source control has all the versions of my project while your database can't fit with any of these old versions, unless you take a backup or a snapshot of the database with each build.
{ "language": "en", "url": "https://stackoverflow.com/questions/169828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: INotifyPropertyChanging and validations: when do I raise PropertyChanging? INotifyPropertyChanged is fairly self explanatory and I think I'm clear on when to raise that one (i.e. when I've finished updating the values). If I implement INotifyPropertyChanging I'm tending to raise the event as soon as I enter the setter or other method that changes the objects state and then continue with any guards and validations that may occur. So I'm treating the event as a notification that the property may change but hasn't yet been changed, and might not actually finish changing successfully. If consumers of the object are using this property (like let's say LINQ to SQL using the event for change tracking) should I be holding off and only raising the event once I have validated that the the values I've been given are good and the state of the object is valid for the change? What is the contract for this event and what side effects would there be in subscribers? A: If your object is given a value that is invalid for the property and you throw an exception then you shouldn't raise the PropertyChanging event. You should only raise the event when you've decided that the value will change. The typical usage scenario is for changing a simple field: public T Foo { get { return m_Foo; } set { if (m_Foo == value) return; //no need for change (or notification) OnPropertyChanging("Foo"); m_Foo = value; OnPropertyChanged("Foo"); } } A: As an aside - PostSharp has the interesting ability to auto-implement INotifyPropertyChanged - like so. A: If you would like to avoid implementing INotifyPropertyChanged altogether, consider using Update Controls .NET instead. This eliminates almost all of the bookkeeping code.
{ "language": "en", "url": "https://stackoverflow.com/questions/169829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do I write content to another browser window using Javascript? I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas? A: I think this will do the trick. function popUp(){ var newWindow = window.open("","Test","width=300,height=300,scrollbars=1,resizable=1") //read text from textbox placed in parent window var text = document.form.input.value var html = "<html><head></head><body>Hello, <b>"+ text +"</b>." html += "How are you today?</body></html>" newWindow .document.open() newWindow .document.write(html) newWindow .document.close() } A: The reference returned by window.open() is to the child window's window object. So you can do anything you would normally do, here's an example: var myWindow = window.open('...') myWindow.document.getElementById('foo').style.backgroundColor = 'red' Bear in mind that this will only work if the parent and child windows have the same domain. Otherwise cross-site scripting security restrictions will stop you. A: The form solution that Vijesh mentions is the basic idea behind communicating data between windows. If you're looking for some library code, there's a great jQuery plugin for exactly this: WindowMsg (see link at bottom due to weird Stack Overflow auto-linking bug). As I described in my answer here: How can I implement the pop out functionality of chat windows in GMail? WindowMsg uses a form in each window and then the window.document.form['foo'] hash for communication. As Dan mentions above, this does only work if the window's share a domain. Also as mentioned in the other thread, you can use the JSON 2 lib from JSON.org to serialize javascript objects for sending between windows in this manner rather than having to communicate solely using strings. WindowMsg: http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/ A: myWindow.document.writeln(documentString)
{ "language": "en", "url": "https://stackoverflow.com/questions/169833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How can I implement the pop out functionality of chat windows in GMail? I'm not looking for a full implementation, I'm more interested in how they do it. I know they use GWT, but I'd like a more low level answer. Naively, I would start by thinking when you click the popout link they simply open a new window and copy content into it. There are lots of reasons why that won't work out well, so I'm wondering if anyone knows or has ideas on how they do this or how it could be done. A: I recently needed to solve exactly this problem in an app. I ended up using this great little jQuery plugin to do the trick: WindowMsg (see link at bottom) While I'm sure there are other ways to accomplish the same task, that plugin does works thusly: * *first you create a new child window from your original window using window.open *you save a reference to the window object returned by window.open *you call a library method in the child window that adds a hidden form for the library to store data in *you call a library method in the parent window that uses window.document.forms to populate form fields on the child window (the library abstracts all of this stuff so you wouldn't even know there was a form involved unless you looked at the source) window.document.forms works the same on all major browsers so this abstraction in x-browser compatible *finally, the child window refers back to its parent window using window.opener and can communicate back via a parallel hidden form on the parent *the library implements a convenient helper that takes a callback function to run on each side to make the callback chain easy to deal with In my experience working with the library, it would have also been quite nice if they had included the JSON 2 lib from JSON.org. Out of the box, WindowMsg only allows you to send string messages between windows, but with some pretty simple use of the JSON 2 lib, I was able to hack it to allow the sending of full JSON objects between windows. I bet more mature libraries (such as whatever google uses) include that kind of serialization and de-serialization baked in. I am putting this link here because for some reason, the Stack Overflow formatter turns it into an anchor link with no closing tag and I don't want my whole post to be one giant hyperlink! WindowMsg: http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/ A: I would say the easiest way would be to have the data stored on the server (which you probably do already), then just have the new window retrieve that data. Of course that wouldn't persist things like contents of a text-box the user has input, so depending on what the window is for, it may be impractical.. but it's always best to start trying the simplest option!
{ "language": "en", "url": "https://stackoverflow.com/questions/169862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Export pictures in Microsoft Word to TIFF How to export pictures in Microsoft Word to TIFF file using Visual Studio Tools for Office? I can obtain a reference to the pictures as InlineShape object collection, the hard part now is how to save them as TIFF images. A: OK guys, I got the problem solved. Here's the code snippet: private void SaveToImage(Word.InlineShape picShape, string filePath) { picShape.Select(); theApp.Selection.CopyAsPicture(); IDataObject data = Clipboard.GetDataObject(); if (data.GetDataPresent(typeof(Bitmap))) { Bitmap image = (Bitmap)data.GetData(typeof(Bitmap)); image.Save(filePath); } } Hope it helps :) A: Well. not sure if this is helpful, but you if you are okay with jpegs, then one really cool technique for extracting images from Word 2007 file is as follows: * *Rename the .docx file to .zip. *Under the (now) zip file, go to the following path: word/media. *All the images in the document are found here as jpeg files. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/169866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Test cases, "when", "what", and "why"? Being new to test based development, this question has been bugging me. How much is too much? What should be tested, how should it be tested, and why should it be tested? The examples given are in C# with NUnit, but I assume the question itself is language agnostic. Here are two current examples of my own, tests on a generic list object (being tested with strings, the initialisation function adds three items {"Foo", "Bar", "Baz"}): [Test] public void CountChanging() { Assert.That(_list.Count, Is.EqualTo(3)); _list.Add("Qux"); Assert.That(_list.Count, Is.EqualTo(4)); _list[7] = "Quuuux"; Assert.That(_list.Count, Is.EqualTo(8)); _list.Remove("Quuuux"); Assert.That(_list.Count, Is.EqualTo(7)); } [Test] public void ContainsItem() { Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); _list.Add("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(true)); _list.Remove("Qux"); Assert.That(_list.Contains("Qux"), Is.EqualTo(false)); } The code is fairly self-commenting, so I won't go into what's happening, but is this sort of thing taking it too far? Add() and Remove() are tested seperately of course, so what level should I go to with these sorts of tests? Should I even have these sorts of tests? A: I would say that what you're actually testing are equivalence classes. In my view, there is no difference between a adding to a list that has 3 items or 7 items. However, there is a difference between 0 items, 1 item and >1 items. I would probably have 3 tests each for Add/Remove methods for these cases initially. Once bugs start coming in from QA/users, I would add each such bug report as a test case; see the bug reproduce by getting a red bar; fix the bug by getting a green bar. Each such 'bug-detecting' test is there to stay - it is my safety net (read: regression test) that even if I make this mistake again, I will have instant feedback. A: Think of your tests as a specification. If your system can break (or have material bugs) without your tests failing, then you don't have enough test coverage. If one single point of failure causes many tests to break, you probably have too much (or are too tightly coupled). This is really hard to define in an objective way. I suppose I'd say err on the side of testing too much. Then when tests start to annoy you, those are the particular tests to refactor/repurpose (because they are too brittle, or test the wrong thing, and their failures aren't useful). A: A few tips: * *Each testcase should only test one thing. That means that the structure of the testcase should be "setup", "execute", "assert". In your examples, you mix these phases. Try splitting your test-methods up. That makes it easier to see exactly what you are testing. *Try giving your test-methods a name that describes what it is testing. I.e. the three testcases contained in your ContainsItem() becomes: containsReportsFalseIfTheItemHasNotBeenAdded(), containsReportsTrueIfTheItemHasBeenAdded(), containsReportsFalseIfTheItemHasBeenAddedThenRemoved(). I find that forcing myself to come up with a descriptive name like that helps me conceptualize what I have to test before I code the actual test. *If you do TDD, you should write your test firsts and only add code to your implementation when you have a failing test. Even if you don't actually do this, it will give you an idea of how many tests are enough. Alternatively use a coverage tool. For a simple class like a container, you should aim for 100% coverage. A: Is _list an instance of a class you wrote? If so, I'd say testing it is reasonable. Though in that case, why are you building a custom List class? If it's not code you wrote, don't test it unless you suspect it's in some way buggy. I try to test code that's independent and modular. If there's some sort of God-function in code I have to maintain, I strip out as much of it as possible into sub-functions and test them independantly. Then the God function can be written to be "obviously correct" -- no branches, no logic, just passing results from one well-tested subfunction to another.
{ "language": "en", "url": "https://stackoverflow.com/questions/169877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Rspec - problems with switching from plugins to gems When dropping the use of rspec and rspec-rails plugins and switching to the gem versions instead, is there anything extra I have to change in spec_helper.rb or something to make the specs in my app see the change? I can no longer get my specs to run successfully anymore after deleting the plugins and installing the gems (1.1.8). More specifically, this is what I did: * *delete previously-installed rspec and rspec-rails plugins from vendors dir *sudo installed both rspec and rspec-rails gems (1.1.8 were the latest as of this writing) When running script/autospec, I get this message: /Library/Ruby/Site/1.8/rubygems.rb:578:in report_activate_error': RubyGem version error: hoe(1.5.0 not >= 1.7.0) (Gem::LoadError) from /Library/Ruby/Site/1.8/rubygems.rb:134:inactivate' from /Library/Ruby/Site/1.8/rubygems.rb:158:in activate' from /Library/Ruby/Site/1.8/rubygems.rb:157:ineach' from /Library/Ruby/Site/1.8/rubygems.rb:157:in activate' from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:inrequire' from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in require' from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:innew_constants_in' from /Library/Ruby/Gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in require' from /Volumes/tangoflash/code/tangoflash/spec/spec_helper.rb:5 from spec/helpers/sessions_helper_spec.rb:1:inrequire' from spec/helpers/sessions_helper_spec.rb:1 When attempting to run a single rspec example via textmate, I get: /Library/Ruby/Site/1.8/rubygems.rb:578:in report_activate_error': RubyGem version error: hoe(1.5.0 not >= 1.7.0) (Gem::LoadError) from /Library/Ruby/Site/1.8/rubygems.rb:134:inactivate' from /Library/Ruby/Site/1.8/rubygems.rb:158:in activate' from /Library/Ruby/Site/1.8/rubygems.rb:157:ineach' from /Library/Ruby/Site/1.8/rubygems.rb:157:in activate' from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:inrequire' from /Users/allanlibunao/Library/Application Support/TextMate/Bundles/RSpec.tmbundle/Support/lib/spec/mate.rb:14 from /tmp/temp_textmate.KQTYKh:3:in `require' from /tmp/temp_textmate.KQTYKh:3 Any help would be awesome. A: From your error message it looks like you do not have a recent version of the hoe gem installed. Try doing a gem install hoe --version '> 1.7.0 and see if it helps. It may be that when you installed the rspec and rspec-rails gems you did not get the dependencies as well and there may be other dependent gems missing.
{ "language": "en", "url": "https://stackoverflow.com/questions/169888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the best process / app for automated deployment of PHP apps? There's another post on SO relating to .NET -- not us. Pure PHP. Trying to find the best way/process to deploy stable version of our PHP app. I've seen an article on Capistrano, but am curious what else is out there. Aside from the obvious reasons, I'm also looking to add some scripting so that the SVN rev number gets added in there as well. Much thanks. A: I've used a home-grown script for quite some time. It will (based on an application configuration file): * *Run svn export on the repository based on a tag. *Package the export into a tar or zip file, which includes the tag in the name. *Use scp to copy the package to the appropriate server (QA or release). *Connect to the server with ssh to install the package and run post-install scripts. The application configuration file is part of the project. It can tell the script (at step 2) to strip paths and otherwise process specified files. It also specifies server names and how to handle externals. I've recently migrated the script to support Git as well as Subversion. I'm also probably going to migrate it to PHP since we're now running in a mixed (Linux and Windows) set up, with Linux now in the minority. I have plans to automatically call the script with post-commit hooks, but haven't had the need to implement that just yet. A: Coincidentally, I was just reading about an Apache Ant/gnu make like build tool called Phing. What I like about it is the ability to write custom extensions in PHP! A: I don't know if it works for deploying an app live, but phpUnderControl is a continuous integration suite (which I'm just now starting to look into). If it doesn't support doing deployments natively, it can probably be extended to do them. A: Chris Hartjes has a nice view on this: Deployment is not a 4 letter word A: We're using Webistrano, which is a web frontend for Capistrano, to deploy a few dozen projects. It's built as a Ruby on Rails app, and provides a nice, centralized and consistent user interface for Capistrano deployments. Instead of having cap recipes in every project, and running command-line tools, Webistrano stores the recipes in its database, and allows you to attach the recipes to multiple projects and stages. This reduces duplication of scripts. Also nice is that all deployment logs are stored so there's an auditing trail. Who deployed which revision to the live server, that sort of thing. As you requested, the Revision number is stored in the deployed project as well. All in all, we're very pleased with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/169889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: In Flot, is it possible to eliminate or hide grid ticks without eliminating the corresponding label? The Flot API documentation describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines without also removing the x-axis labels. I've tried changing the tickColor, ticks, and tickSize options with no success. I want to create beautiful, Tufte-compatible graphs such as these: http://www.robgoodlatte.com/wp-content/uploads/2007/05/tufte_mint.gif http://www.argmax.com/mt_blog/archive/RealGDP_graph.jpg I find the vertical ticks on my graphs to be chart junk. I am working with a time series that I am displaying as vertical bars so the vertical ticks often cut through the bars in a way that is visually noisy. A: This post comes over two years later than OP and Flot (now version 0.6) might have evolved a lot during that time or maybe there's better options than it around but in either case here's my contribution. I accidentally bumped into a workaround for this problem: set grid's tick color's alpha channel to fully transparent. For example: var options = { grid: {show: true, color: "rgb(48, 48, 48)", tickColor: "rgba(255, 255, 255, 0)", backgroundColor: "rgb(255, 255, 255)"} }; Works for me. A: After some digging around, I'm quite sure that it is not possible through the Flot API. Nevertheless, if you get really dirty, you could do it - I have published a modified version of one example which does it. View source shows the whole uglyness. A: To Avoid ticks in the options just give ticks:[] in the corresponding axis A: As Laurimann noted, Flot continues to evolve. The ability to control this has been added to the API (as noted in the flot issue Nelson linked to). If you download the latest version (which is still labeled 0.6), you can disable lines on an axis with "tickLength", like so: xaxis: { tickLength: 0 } Rather annoyingly, this addition hasn't been updated in the API documentation. A: Starting June 2009 there's flot issue 167 which is a request for this exact feature. Includes two implementations and some agreement from the flot author that it's a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/169894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to package Twisted program with py2exe? I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error. And I found the py2exe said: The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] So how do I solve this problem? Thanks. A: I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out. You can explicitly specify modules to include on the py2exe command line: python setup.py py2exe -p win32com -i twisted.web.resource Something like that. Read up on the options and experiment. A: Had same issue with email module. I got it working by explicitly including modules in setup.py: OLD setup.py: setup(console = ['main.py']) New setup.py: setup(console = ['main.py'], options={"py2exe":{"includes":["email.mime.multipart","email.mime.text"]}})
{ "language": "en", "url": "https://stackoverflow.com/questions/169897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Projective transformation Given two image buffers (assume it's an array of ints of size width * height, with each element a color value), how can I map an area defined by a quadrilateral from one image buffer into the other (always square) image buffer? I'm led to understand this is called "projective transformation". I'm also looking for a general (not language- or library-specific) way of doing this, such that it could be reasonably applied in any language without relying on "magic function X that does all the work for me". An example: I've written a short program in Java using the Processing library (processing.org) that captures video from a camera. During an initial "calibrating" step, the captured video is output directly into a window. The user then clicks on four points to define an area of the video that will be transformed, then mapped into the square window during subsequent operation of the program. If the user were to click on the four points defining the corners of a door visible at an angle in the camera's output, then this transformation would cause the subsequent video to map the transformed image of the door to the entire area of the window, albeit somewhat distorted. A: Using linear algebra is much easier than all that geometry! Plus you won't need to use sine, cosine, etc, so you can store each number as a rational fraction and get the exact numerical result if you need it. What you want is a mapping from your old (x,y) co-ordinates to your new (x',y') co-ordinates. You can do it with matrices. You need to find the 2-by-4 projection matrix P such that P times the old coordinates equals the new co-ordinates. We'll assume that you're mapping lines to lines (not, for instance, straight lines to parabolas). Because you have a projection (parallel lines don't stay parallel) and translation (sliding), you need a factor of (xy) and (1), too. Drawn as matrices: [x ] [a b c d]*[y ] = [x'] [e f g h] [x*y] [y'] [1 ] You need to know a through h so solve these equations: a*x_0 + b*y_0 + c*x_0*y_0 + d = i_0 a*x_1 + b*y_1 + c*x_1*y_1 + d = i_1 a*x_2 + b*y_2 + c*x_2*y_2 + d = i_2 a*x_3 + b*y_3 + c*x_3*y_3 + d = i_3 e*x_0 + f*y_0 + g*x_0*y_0 + h = j_0 e*x_1 + f*y_1 + g*x_1*y_1 + h = j_1 e*x_2 + f*y_2 + g*x_2*y_2 + h = j_2 e*x_3 + f*y_3 + g*x_3*y_3 + h = j_3 Again, you can use linear algebra: [x_0 y_0 x_0*y_0 1] [a e] [i_0 j_0] [x_1 y_1 x_1*y_1 1] * [b f] = [i_1 j_1] [x_2 y_2 x_2*y_2 1] [c g] [i_2 j_2] [x_3 y_3 x_3*y_3 1] [d h] [i_3 j_3] Plug in your corners for x_n,y_n,i_n,j_n. (Corners work best because they are far apart to decrease the error if you're picking the points from, say, user-clicks.) Take the inverse of the 4x4 matrix and multiply it by the right side of the equation. The transpose of that matrix is P. You should be able to find functions to compute a matrix inverse and multiply online. Where you'll probably have bugs: * *When computing, remember to check for division by zero. That's a sign that your matrix is not invertible. That might happen if you try to map one (x,y) co-ordinate to two different points. *If you write your own matrix math, remember that matrices are usually specified row,column (vertical,horizontal) and screen graphics are x,y (horizontal,vertical). You're bound to get something wrong the first time. A: EDIT The assumption below of the invariance of angle ratios is incorrect. Projective transformations instead preserve cross-ratios and incidence. A solution then is: * *Find the point C' at the intersection of the lines defined by the segments AD and CP. *Find the point B' at the intersection of the lines defined by the segments AD and BP. *Determine the cross-ratio of B'DAC', i.e. r = (BA' * DC') / (DA * B'C'). *Construct the projected line F'HEG'. The cross-ratio of these points is equal to r, i.e. r = (F'E * HG') / (HE * F'G'). *F'F and G'G will intersect at the projected point Q so equating the cross-ratios and knowing the length of the side of the square you can determine the position of Q with some arithmetic gymnastics. Hmmmm....I'll take a stab at this one. This solution relies on the assumption that ratios of angles are preserved in the transformation. See the image for guidance (sorry for the poor image quality...it's REALLY late). The algorithm only provides the mapping of a point in the quadrilateral to a point in the square. You would still need to implement dealing with multiple quad points being mapped to the same square point. Let ABCD be a quadrilateral where A is the top-left vertex, B is the top-right vertex, C is the bottom-right vertex and D is the bottom-left vertex. The pair (xA, yA) represent the x and y coordinates of the vertex A. We are mapping points in this quadrilateral to the square EFGH whose side has length equal to m. Compute the lengths AD, CD, AC, BD and BC: AD = sqrt((xA-xD)^2 + (yA-yD)^2) CD = sqrt((xC-xD)^2 + (yC-yD)^2) AC = sqrt((xA-xC)^2 + (yA-yC)^2) BD = sqrt((xB-xD)^2 + (yB-yD)^2) BC = sqrt((xB-xC)^2 + (yB-yC)^2) Let thetaD be the angle at the vertex D and thetaC be the angle at the vertex C. Compute these angles using the cosine law: thetaD = arccos((AD^2 + CD^2 - AC^2) / (2*AD*CD)) thetaC = arccos((BC^2 + CD^2 - BD^2) / (2*BC*CD)) We map each point P in the quadrilateral to a point Q in the square. For each point P in the quadrilateral, do the following: * *Find the distance DP: DP = sqrt((xP-xD)^2 + (yP-yD)^2) *Find the distance CP: CP = sqrt((xP-xC)^2 + (yP-yC)^2) *Find the angle thetaP1 between CD and DP: thetaP1 = arccos((DP^2 + CD^2 - CP^2) / (2*DP*CD)) *Find the angle thetaP2 between CD and CP: thetaP2 = arccos((CP^2 + CD^2 - DP^2) / (2*CP*CD)) *The ratio of thetaP1 to thetaD should be the ratio of thetaQ1 to 90. Therefore, calculate thetaQ1: thetaQ1 = thetaP1 * 90 / thetaD *Similarly, calculate thetaQ2: thetaQ2 = thetaP2 * 90 / thetaC *Find the distance HQ: HQ = m * sin(thetaQ2) / sin(180-thetaQ1-thetaQ2) *Finally, the x and y position of Q relative to the bottom-left corner of EFGH is: x = HQ * cos(thetaQ1) y = HQ * sin(thetaQ1) You would have to keep track of how many colour values get mapped to each point in the square so that you can calculate an average colour for each of those points. A: I think what you're after is a planar homography, have a look at these lecture notes: http://www.cs.utoronto.ca/~strider/vis-notes/tutHomography04.pdf If you scroll down to the end you'll see an example of just what you're describing. I expect there's a function in the Intel OpenCV library which will do just this. A: There is a C++ project on CodeProject that includes source for projective transformations of bitmaps. The maths are on Wikipedia here. Note that so far as i know, a projective transformation will not map any arbitrary quadrilateral onto another, but will do so for triangles, you may also want to look up skewing transforms. A: If this transformation has to look good (as opposed to the way a bitmap looks if you resize it in Paint), you can't just create a formula that maps destination pixels to source pixels. Values in the destination buffer have to be based on a complex averaging of nearby source pixels or else the results will be highly pixelated. So unless you want to get into some complex coding, use someone else's magic function, as smacl and Ian have suggested. A: Here's how would do it in principle: * *map the origin of A to the origin of B via a traslation vector t. *take unit vectors of A (1,0) and (0,1) and calculate how they would be mapped onto the unit vectors of B. *this gives you a transformation matrix M so that every vector a in A maps to M a + t *invert the matrix and negate the traslation vector so for every vector b in B you have the inverse mapping b -> M-1 (b - t) *once you have this transformation, for each point in the target area in B, find the corresponding in A and copy. The advantage of this mapping is that you only calculate the points you need, i.e. you loop on the target points, not the source points. It was a widely used technique in the "demo coding" scene a few years back.
{ "language": "en", "url": "https://stackoverflow.com/questions/169902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Can I listen on a port (using HttpListener or other .NET code) on Vista without requiring administrator priveleges? I'm using HttpListener to allow a user to set up a proxy on a user-defined port. When I start the HttpListener, I get an exception if the application isn't running under administrator privileges in Vista. From what I've read, this is expected behavior - administrator privileges are required to start listening on a port. But I'm sure there are ways around this, as I run plenty of programs (like Skype) which listen on a port without requiring elevation to administrator. Is there a way to do this with HttpListener? If not, can I make other API calls in .NET code to set up the port? A: I've never used an HttpListener, but from your description it sounds more like you want to listen on a regular TCP port, instead of embedding your application into a server URL namespace (which is what HttpListener appears to do). You should be able to use regular socket functions (System.Net.Sockets.TcpListener) to open and listen on a TCP port without requiring administrator privileges. I'm almost certain Skype doesn't use an HttpListener. A: Well I had to deal with something similar. My Computer is in a restricted domain, so I don't have administrator privileges. After some research and reading I found this thread and the netsh hints made me use temporary acl bindings just for developing tests. On my computer these rule exists. There's this entry: Run 'netsh http show urlacl' (as shown above) [...] Reservierte URL : http://+:80/Temporary_Listen_Addresses/ Benutzer: \Jeder Abhören: Yes Delegieren: No SDDL: D:(A;;GX;;;WD) [...] So I can use the HttpListener as non-admin (Jeder): [...] HttpListener l = new HttpListener(); string prefix = "http://+:80/Temporary_Listen_Addresses/"; l.Prefixes.Add(prefix); l.Start(); // does not throw any "Permission Denied/Access Denied/Zugriff verweigert" [...] May this helps anybody finding this thread. A: While you can write your own HTTP server using normal TCP/IP (it's relatively simple), it is easier to use HttpListener, which takes advantage of the HTTP.SYS functionality added in Windows XP SP2. However, HTTP.SYS adds the concept of URL ACLs. This is partly because HTTP.SYS allows you to bind to sub-namespaces on port 80. Using TCP/IP directly avoids this requirement, but means that you can't bind to a port that's already in use. On Windows XP, you can use the HttpCfg.exe program to set up a URL ACL granting your user account the right to bind to a particular URL. It's in the Platform SDK samples. On Windows Vista, HTTPCFG is still supported, but the functionality has been absorbed into NETSH: netsh http show urlacl ...will show a list of existing URL ACLs. The ACLs are expressed in SDDL. netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\User listen=yes ...will configure the MyURI namespace so that DOMAIN\User can listen to requests. A: If you need to handle requests only from you own computer (usually for test purposes), you can write localhost instead of * in prefix. For example, instead of "http://*:9669/" you can write "http://localhost:9669/". This works fine with HttpListener and doesn't require administrative privileges (at least on Windows 7). A: In XP, you had to use a command-line (httpcfg) to open up the port first, otherwise it wouldn't work for non-admins. See here - the page explains the issue, and there is a zip at the bottom to make it usable.
{ "language": "en", "url": "https://stackoverflow.com/questions/169904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Where is the history of the 'run' dialogue saved on Windows XP? I want to write a script which cleans the 'run' dialogue automatically every log off. Where is the history stored? A: From: How to Remove Individual Entries from Run Command History Where is the Run MRU (Most Recently Used) List? The RUNMRU list is stored in the Windows Registry in the following location: HKEY_CURRENT_USER\ Software\ Microsoft\ Windows\ CurrentVersion\ Explorer\ RunMRU\ Is There a Program to Delete Individual Entries from the RUNMRU List? Many of my customers would rather not edit the Windows registry to remove these individual entries, so I setup a VBScript that you can download and run to delete individual commands from this list. Follow these instructions to download and use this program to clear unwanted entries from the Run Command history. 1) Click on the following link and download the EditRunMRUList.vbs script to your desktop Download EditRunMRUList.vbs A: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU A: Never use registry, just use Win32 SH api to clean it.
{ "language": "en", "url": "https://stackoverflow.com/questions/169905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I base64 encode a string efficiently using Excel VBA? I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from dbb and marxidad)? A: As Mark C points out, you can use the MSXML Base64 encoding functionality as described here. I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references: Function EncodeBase64(text As String) As String Dim arrData() As Byte arrData = StrConv(text, vbFromUnicode) Dim objXML As Variant Dim objNode As Variant Set objXML = CreateObject("MSXML2.DOMDocument") Set objNode = objXML.createElement("b64") objNode.dataType = "bin.base64" objNode.nodeTypedValue = arrData EncodeBase64 = Replace(objNode.Text, vbLf, "") Set objNode = Nothing Set objXML = Nothing End Function A: You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp: Function EncodeBase64(text As String) As String Dim arrData() As Byte arrData = StrConv(text, vbFromUnicode) Dim objXML As MSXML2.DOMDocument Dim objNode As MSXML2.IXMLDOMElement Set objXML = New MSXML2.DOMDocument Set objNode = objXML.createElement("b64") objNode.dataType = "bin.base64" objNode.nodeTypedValue = arrData EncodeBase64 = Replace(objNode.Text, vbLf, "") Set objNode = Nothing Set objXML = Nothing End Function A: This code works very fast. It comes from here Option Explicit Private Const clOneMask = 16515072 '000000 111111 111111 111111 Private Const clTwoMask = 258048 '111111 000000 111111 111111 Private Const clThreeMask = 4032 '111111 111111 000000 111111 Private Const clFourMask = 63 '111111 111111 111111 000000 Private Const clHighMask = 16711680 '11111111 00000000 00000000 Private Const clMidMask = 65280 '00000000 11111111 00000000 Private Const clLowMask = 255 '00000000 00000000 11111111 Private Const cl2Exp18 = 262144 '2 to the 18th power Private Const cl2Exp12 = 4096 '2 to the 12th Private Const cl2Exp6 = 64 '2 to the 6th Private Const cl2Exp8 = 256 '2 to the 8th Private Const cl2Exp16 = 65536 '2 to the 16th Public Function Encode64(sString As String) As String Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long For lTemp = 0 To 63 'Fill the translation table. Select Case lTemp Case 0 To 25 bTrans(lTemp) = 65 + lTemp 'A - Z Case 26 To 51 bTrans(lTemp) = 71 + lTemp 'a - z Case 52 To 61 bTrans(lTemp) = lTemp - 4 '1 - 0 Case 62 bTrans(lTemp) = 43 'Chr(43) = "+" Case 63 bTrans(lTemp) = 47 'Chr(47) = "/" End Select Next lTemp For lTemp = 0 To 255 'Fill the 2^8 and 2^16 lookup tables. lPowers8(lTemp) = lTemp * cl2Exp8 lPowers16(lTemp) = lTemp * cl2Exp16 Next lTemp iPad = Len(sString) Mod 3 'See if the length is divisible by 3 If iPad Then 'If not, figure out the end pad and resize the input. iPad = 3 - iPad sString = sString & String(iPad, Chr(0)) End If bIn = StrConv(sString, vbFromUnicode) 'Load the input string. lLen = ((UBound(bIn) + 1) \ 3) * 4 'Length of resulting string. lTemp = lLen \ 72 'Added space for vbCrLfs. lOutSize = ((lTemp * 2) + lLen) - 1 'Calculate the size of the output buffer. ReDim bOut(lOutSize) 'Make the output buffer. lLen = 0 'Reusing this one, so reset it. For lChar = LBound(bIn) To UBound(bIn) Step 3 lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2) 'Combine the 3 bytes lTemp = lTrip And clOneMask 'Mask for the first 6 bits bOut(lPos) = bTrans(lTemp \ cl2Exp18) 'Shift it down to the low 6 bits and get the value lTemp = lTrip And clTwoMask 'Mask for the second set. bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12) 'Shift it down and translate. lTemp = lTrip And clThreeMask 'Mask for the third set. bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6) 'Shift it down and translate. bOut(lPos + 3) = bTrans(lTrip And clFourMask) 'Mask for the low set. If lLen = 68 Then 'Ready for a newline bOut(lPos + 4) = 13 'Chr(13) = vbCr bOut(lPos + 5) = 10 'Chr(10) = vbLf lLen = 0 'Reset the counter lPos = lPos + 6 Else lLen = lLen + 4 lPos = lPos + 4 End If Next lChar If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf. If iPad = 1 Then 'Add the padding chars if any. bOut(lOutSize) = 61 'Chr(61) = "=" ElseIf iPad = 2 Then bOut(lOutSize) = 61 bOut(lOutSize - 1) = 61 End If Encode64 = StrConv(bOut, vbUnicode) 'Convert back to a string and return it. End Function Public Function Decode64(sString As String) As String Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String Dim lTemp As Long sString = Replace(sString, vbCr, vbNullString) 'Get rid of the vbCrLfs. These could be in... sString = Replace(sString, vbLf, vbNullString) 'either order. lTemp = Len(sString) Mod 4 'Test for valid input. If lTemp Then Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.") End If If InStrRev(sString, "==") Then 'InStrRev is faster when you know it's at the end. iPad = 2 'Note: These translate to 0, so you can leave them... ElseIf InStrRev(sString, "=") Then 'in the string and just resize the output. iPad = 1 End If For lTemp = 0 To 255 'Fill the translation table. Select Case lTemp Case 65 To 90 bTrans(lTemp) = lTemp - 65 'A - Z Case 97 To 122 bTrans(lTemp) = lTemp - 71 'a - z Case 48 To 57 bTrans(lTemp) = lTemp + 4 '1 - 0 Case 43 bTrans(lTemp) = 62 'Chr(43) = "+" Case 47 bTrans(lTemp) = 63 'Chr(47) = "/" End Select Next lTemp For lTemp = 0 To 63 'Fill the 2^6, 2^12, and 2^18 lookup tables. lPowers6(lTemp) = lTemp * cl2Exp6 lPowers12(lTemp) = lTemp * cl2Exp12 lPowers18(lTemp) = lTemp * cl2Exp18 Next lTemp bIn = StrConv(sString, vbFromUnicode) 'Load the input byte array. ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1) 'Prepare the output buffer. For lChar = 0 To UBound(bIn) Step 4 lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _ lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3)) 'Rebuild the bits. lTemp = lQuad And clHighMask 'Mask for the first byte bOut(lPos) = lTemp \ cl2Exp16 'Shift it down lTemp = lQuad And clMidMask 'Mask for the second byte bOut(lPos + 1) = lTemp \ cl2Exp8 'Shift it down bOut(lPos + 2) = lQuad And clLowMask 'Mask for the third byte lPos = lPos + 3 Next lChar sOut = StrConv(bOut, vbUnicode) 'Convert back to a string. If iPad Then sOut = Left$(sOut, Len(sOut) - iPad) 'Chop off any extra bytes. Decode64 = sOut End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/169907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: View MS Access Report in .net ReportViewer control Is it possible to view an MS Access report in the .Net ReportViewer control? A: I dont think so...you first need to migrate the reports to SSRS. http://www.microsoft.com/technet/prodtechnol/sql/2000/deploy/migratereports.mspx
{ "language": "en", "url": "https://stackoverflow.com/questions/169908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to convert a string into double and vice versa? I want to convert a string into a double and after doing some math on it, convert it back to a string. How do I do this in Objective-C? Is there a way to round a double to the nearest integer too? A: Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".) NSString *tempStr = @"8,765.4"; // localization allows other thousands separators, also. NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init]; [myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default? [myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; // next line is very important! [myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial NSNumber *tempNum = [myNumFormatter numberFromString:tempStr]; NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", tempStr, tempNum, [tempNum intValue]); [myNumFormatter release]; // good citizen A: To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string. Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all. It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead. A: olliej's rounding method is wrong for negative numbers * *2.4 rounded is 2 (olliej's method gets this right) *−2.4 rounded is −2 (olliej's method returns -1) Here's an alternative int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5)) You could of course use a rounding function from math.h A: Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue: [[NSNumber numberWithInt:myInt] stringValue] stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt] will give you a properly localized reprsentation of myInt. A: // Converting String in to Double double doubleValue = [yourString doubleValue]; // Converting Double in to String NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue]; // .20f takes the value up to 20 position after decimal // Converting double to int int intValue = (int) doubleValue; or int intValue = [yourString intValue]; A: For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact. int myInt = (int)round( [@"1.6" floatValue] ); NSString* myString = [@(myInt) description]; (Boxes it up as a NSNumber and converts to a string using the NSObjects' description method) A: You can convert an NSString into a double with double myDouble = [myString doubleValue]; Rounding to the nearest int can then be done as int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5)) I'm honestly not sure if there's a more streamlined way to convert back into a string than NSString* myNewString = [NSString stringWithFormat:@"%d", myInt]; A: For rounding, you should probably use the C functions defined in math.h. int roundedX = round(x); Hold down Option and double click on round in Xcode and it will show you the man page with various functions for rounding different types. A: This is the easiest way I know of: float myFloat = 5.3; NSInteger myInt = (NSInteger)myFloat; A: from this example here, you can see the the conversions both ways: NSString *str=@"5678901234567890"; long long verylong; NSRange range; range.length = 15; range.location = 0; [[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong]; NSLog(@"long long value %lld",verylong); A: I ended up using this handy macro: #define STRING(value) [@(value) stringValue] A: convert text entered in textfield to integer double mydouble=[_myTextfield.text doubleValue]; rounding to the nearest double mydouble=(round(mydouble)); rounding to the nearest int(considering only positive values) int myint=(int)(mydouble); converting from double to string myLabel.text=[NSString stringWithFormat:@"%f",mydouble]; or NSString *mystring=[NSString stringWithFormat:@"%f",mydouble]; converting from int to string myLabel.text=[NSString stringWithFormat:@"%d",myint]; or NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];
{ "language": "en", "url": "https://stackoverflow.com/questions/169925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "147" }
Q: Where can I find some good information about how the new canvas HTML element works? I keep reading about how great this new Canvas element for HTML5 is and I see amazing demos done with just javascript and no flash. Where can I find some good information on how to some of these things myself? A: The specification defines the API and behaviour. This tutorial should help you get started. A: There's the original Apple tutorial Also the draft html5 spec And of course you can (as people have) ask questions about specific features, etc on SO :D A: I've been using this HTML5 Canvas Cheat Sheet, it is thorough and easy to read. http://blog.nihilogic.dk/2009/02/html5-canvas-cheat-sheet.html A: This page is a 14 part series that shows you how to create a simple platform game using the canvas element. A: Ajaxian has a great collection of articles / posts regarding new Canvas innovations and developments. This can show you what others are already doing. A: This isn't super deep, but it is easy to read and gives great examples: https://developer.mozilla.org/en/canvas_tutorial It is where I got my start (I now have a couple iOS apps out there using js + canvas)
{ "language": "en", "url": "https://stackoverflow.com/questions/169928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JUnit Eclipse plugin source-code? I'm looking into writing an Eclipse plugin for FlexUnit and was wondering where I could get the sources for the JUnit Eclipse plugin. I checked the JUnit sources at sourceforge but couldn't spot any code that looked like the plugin code. Any idea where this code is available? A: You can find it on Eclipse's repository: http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.pde.junit/ A: There are now git mirrors of the CVS repositories: * *org.eclipse.jdt.junit: git://dev.eclipse.org/org.eclipse.jdt/org.eclipse.jdt.junit.git *org.eclipse.jdt.junit.core: git://dev.eclipse.org/org.eclipse.jdt/org.eclipse.jdt.junit.core.git *org.eclipse.jdt.junit.runtime: git://dev.eclipse.org/org.eclipse.jdt/org.eclipse.jdt.junit.runtime.git *org.eclipse.jdt.junit4.runtime: git://dev.eclipse.org/org.eclipse.jdt/org.eclipse.jdt.junit4.runtime.git A: Since you are in all likelihood using Eclipse, there's a far easier way to import it right into your workspace. The source is bundled with your eclipse distribution. Just do File -> Import -> Plug-ins and Fragments Keep defaults ("Active target platform", "Select from all plug-ins" & "Projects with source folders" Hit next, and select the JUnit plugin-packages and hit Finish, and they will be imported as Eclipse projects into your workspace.
{ "language": "en", "url": "https://stackoverflow.com/questions/169929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is a reasonable size for an iPhone App? I'm wondering what's a reasonable size for iPhone Apps. Right now I'm working on an iPhone game, and of course it loads fast into my device since I'm connected directly to it through a USB cable, but I've no idea how long it would actually take to download from the App Store. In my case it's about 2mb in size, which is reasonable for a desktop or even a flash game, but I've no idea if this is reasonable size for the iPhone. My other concern is what's the non-wifi download limit of the App Store? Occasionally there are Apps that won't download unless you've got a wifi connection. And personally I've never downloaded such apps, since it gives me a bad impression. So I'd definitely want to stay below that limit. Also since I'm already asking about app sizes, it would be probably be useful to collect good sizes for other types of apps as well. Thanks! A: The 3g network is fast. I wouldn't limit your development based on this - do exactly what you need to do to make your game as good as it can be, and people will download it even if it takes a tiny bit longer. I've downloaded 10MB+ applications from the store over 3g and it might as well be a slow wi-fi connection, it's just that fast. Also remember that many people purchase on their computers (hence a fast connection) and then just sync to the iPhone, especially those that are in areas with slower cellular networks. Bottom line, size won't affect downloads, ratings will. A: Besides the resonable numbers being somewhat lower the limits: Maximum app size ist 2GB Application larger than 20MB won't be downloadable over a cellular connection A: Looking through some of the games i have on my phone they weigh in around 7 or 8 mb a pop. I think your 2mb will be fine. One thing i can tell you for sure is that if you want to be distributable over the cell network your application has to be under 50 mb. If you exceed this it will have to be downloaded using wifi or itunes on a computer. A: I would try and keep it as small as possible. The app-store could probably support, say, a 100MB application, but it wont be nice to install for users. The problem is installing via the phone - all you get is a simple progress bar, and most people have their phone auto-lock after 1 minute.. So, ideally the app would download in under a minute on an average connection..
{ "language": "en", "url": "https://stackoverflow.com/questions/169936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you handle cookies with webrequest/response as in a proxy? How do you handle cookies and with webrequest/response as in a proxy? I'm not sure how to do this...or if I even can. A: Can you clarify what you mean? What is the setup here? If you want to perform multiple related operations, then WebClient may be more appropriate; this might (I haven't checked - never needed it) retain cookies between calls on the same WebClient instance (and is a lot easier to use, too).
{ "language": "en", "url": "https://stackoverflow.com/questions/169943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using the .NET Framework security system I was wondering - do any of you actually use the various classes in the System.Security.Permissions namespace? I mainly develop desktop/server-side components (i.e., no web) and the general assumption is that FullTrust is always available and no testing is performed on environments for which this is not the case. Apart from MS source code (EnterpriseLibrary and such), I have yet to see actual, in-use source code that makes use of said constructs. Is this prevalent, or are we the exception? I know, of course, that not doing this kind of testing is a problem on our side... A: The .NET code access security is more relevant when users run code directly off a server over the internet, in which case they can't necessarily trust it to automatically do things such as access the file system. I don't know of anyone who makes their code available like that, though. A: I make lots of use of PrincipalPermissionAttribute to demand the user has necessary access rights (using roles) from the Thread's Principal - saves a lot of manual checking in my business code (obviously the UI should check too and disable buttons etc - this is just the double-check at the back-end). I find Principal-based security to be very versatily, especially with a custom Principal. But I don't use the CAS stuff. A: If you deploy your desktop applications with ClickOnce, then the security sandbox can come into play. A: I have never seen anyone make use of the permit, assert functionality. I suspect a number of developers are not actually aware of the functionality. I think it could be useful to restrict calls to dangerous functions. Its going to depend on what you are doing but who wants to make a deployment more complex than it already is?
{ "language": "en", "url": "https://stackoverflow.com/questions/169951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to prevent a script from running simultaneously? I want to prevent my script running more than once at a time. My current approach is * *create a semaphore file containing the pid of the running process *read the file, if my process-id is not in it exit (you never know...) *at the end of the processing, delete the file In order to prevent the process from hanging, I set up a cron job to periodically check the file if its older then the maximum allowed running time and kills the process if it’s still running. Is there a risk that I'm killing a wrong process? Is there a better way to perform this as a whole?
{ "language": "en", "url": "https://stackoverflow.com/questions/169964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "71" }
Q: When should I use a List vs a LinkedList When is it better to use a List vs a LinkedList? A: My previous answer was not enough accurate. As truly it was horrible :D But now I can post much more useful and correct answer. I did some additional tests. You can find it's source by the following link and reCheck it on your environment by your own: https://github.com/ukushu/DataStructuresTestsAndOther.git Short results: * *Array need to use: * *So often as possible. It's fast and takes smallest RAM range for same amount information. *If you know exact count of cells needed *If data saved in array < 85000 b (85000/32 = 2656 elements for integer data) *If needed high Random Access speed *List need to use: * *If needed to add cells to the end of list (often) *If needed to add cells in the beginning/middle of the list (NOT OFTEN) *If data saved in array < 85000 b (85000/32 = 2656 elements for integer data) *If needed high Random Access speed *LinkedList need to use: * *If needed to add cells in the beginning/middle/end of the list (often) *If needed only sequential access (forward/backward) *If you need to save LARGE items, but items count is low. *Better do not use for large amount of items, as it's use additional memory for links. More details: Interesting to know: * *LinkedList<T> internally is not a List in .NET. It's even does not implement IList<T>. And that's why there are absent indexes and methods related to indexes. *LinkedList<T> is node-pointer based collection. In .NET it's in doubly linked implementation. This means that prior/next elements have link to current element. And data is fragmented -- different list objects can be located in different places of RAM. Also there will be more memory used for LinkedList<T> than for List<T> or Array. *List<T> in .Net is Java's alternative of ArrayList<T>. This means that this is array wrapper. So it's allocated in memory as one contiguous block of data. If allocated data size exceeds 85000 bytes, it will be moved to Large Object Heap. Depending on the size, this can lead to heap fragmentation(a mild form of memory leak). But in the same time if size < 85000 bytes -- this provides a very compact and fast-access representation in memory. *Single contiguous block is preferred for random access performance and memory consumption but for collections that need to change size regularly a structure such as an Array generally need to be copied to a new location whereas a linked list only needs to manage the memory for the newly inserted/deleted nodes. A: A common circumstance to use LinkedList is like this: Suppose you want to remove many certain strings from a list of strings with a large size, say 100,000. The strings to remove can be looked up in HashSet dic, and the list of strings is believed to contain between 30,000 to 60,000 such strings to remove. Then what's the best type of List for storing the 100,000 Strings? The answer is LinkedList. If the they are stored in an ArrayList, then iterating over it and removing matched Strings whould take up to billions of operations, while it takes just around 100,000 operations by using an iterator and the remove() method. LinkedList<String> strings = readStrings(); HashSet<String> dic = readDic(); Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()){ String string = iterator.next(); if (dic.contains(string)) iterator.remove(); } A: In most cases, List<T> is more useful. LinkedList<T> will have less cost when adding/removing items in the middle of the list, whereas List<T> can only cheaply add/remove at the end of the list. LinkedList<T> is only at it's most efficient if you are accessing sequential data (either forwards or backwards) - random access is relatively expensive since it must walk the chain each time (hence why it doesn't have an indexer). However, because a List<T> is essentially just an array (with a wrapper) random access is fine. List<T> also offers a lot of support methods - Find, ToArray, etc; however, these are also available for LinkedList<T> with .NET 3.5/C# 3.0 via extension methods - so that is less of a factor. A: Thinking of a linked list as a list can be a bit misleading. It's more like a chain. In fact, in .NET, LinkedList<T> does not even implement IList<T>. There is no real concept of index in a linked list, even though it may seem there is. Certainly none of the methods provided on the class accept indexes. Linked lists may be singly linked, or doubly linked. This refers to whether each element in the chain has a link only to the next one (singly linked) or to both the prior/next elements (doubly linked). LinkedList<T> is doubly linked. Internally, List<T> is backed by an array. This provides a very compact representation in memory. Conversely, LinkedList<T> involves additional memory to store the bidirectional links between successive elements. So the memory footprint of a LinkedList<T> will generally be larger than for List<T> (with the caveat that List<T> can have unused internal array elements to improve performance during append operations.) They have different performance characteristics too: Append * *LinkedList<T>.AddLast(item) constant time *List<T>.Add(item) amortized constant time, linear worst case Prepend * *LinkedList<T>.AddFirst(item) constant time *List<T>.Insert(0, item) linear time Insertion * *LinkedList<T>.AddBefore(node, item) constant time *LinkedList<T>.AddAfter(node, item) constant time *List<T>.Insert(index, item) linear time Removal * *LinkedList<T>.Remove(item) linear time *LinkedList<T>.Remove(node) constant time *List<T>.Remove(item) linear time *List<T>.RemoveAt(index) linear time Count * *LinkedList<T>.Count constant time *List<T>.Count constant time Contains * *LinkedList<T>.Contains(item) linear time *List<T>.Contains(item) linear time Clear * *LinkedList<T>.Clear() linear time *List<T>.Clear() linear time As you can see, they're mostly equivalent. In practice, the API of LinkedList<T> is more cumbersome to use, and details of its internal needs spill out into your code. However, if you need to do many insertions/removals from within a list, it offers constant time. List<T> offers linear time, as extra items in the list must be shuffled around after the insertion/removal. A: The difference between List and LinkedList lies in their underlying implementation. List is array based collection (ArrayList). LinkedList is node-pointer based collection (LinkedListNode). On the API level usage, both of them are pretty much the same since both implement same set of interfaces such as ICollection, IEnumerable, etc. The key difference comes when performance matter. For example, if you are implementing the list that has heavy "INSERT" operation, LinkedList outperforms List. Since LinkedList can do it in O(1) time, but List may need to expand the size of underlying array. For more information/detail you might want to read up on the algorithmic difference between LinkedList and array data structures. http://en.wikipedia.org/wiki/Linked_list and Array Hope this help, A: When you need built-in indexed access, sorting (and after this binary searching), and "ToArray()" method, you should use List. A: Essentially, a List<> in .NET is a wrapper over an array. A LinkedList<> is a linked list. So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list. Probably the two most important factors in your decision of which to use would come down to: * *Linked lists have much better insertion/removal performance, so long as the insertions/removals are not on the last element in the collection. This is because an array must shift all remaining elements that come after the insertion/removal point. If the insertion/removal is at the tail end of the list however, this shift is not needed (although the array may need to be resized, if its capacity is exceeded). *Arrays have much better accessing capabilities. Arrays can be indexed into directly (in constant time). Linked lists must be traversed (linear time). A: The primary advantage of linked lists over arrays is that the links provide us with the capability to rearrange the items efficiently. Sedgewick, p. 91 A: Linked lists provide very fast insertion or deletion of a list member. Each member in a linked list contains a pointer to the next member in the list so to insert a member at position i: * *update the pointer in member i-1 to point to the new member *set the pointer in the new member to point to member i The disadvantage to a linked list is that random access is not possible. Accessing a member requires traversing the list until the desired member is found. A: Edit Please read the comments to this answer. People claim I did not do proper tests. I agree this should not be an accepted answer. As I was learning I did some tests and felt like sharing them. Original answer... I found interesting results: // Temporary class to show the example class Temp { public decimal A, B, C, D; public Temp(decimal a, decimal b, decimal c, decimal d) { A = a; B = b; C = c; D = d; } } Linked list (3.9 seconds) LinkedList<Temp> list = new LinkedList<Temp>(); for (var i = 0; i < 12345678; i++) { var a = new Temp(i, i, i, i); list.AddLast(a); } decimal sum = 0; foreach (var item in list) sum += item.A; List (2.4 seconds) List<Temp> list = new List<Temp>(); // 2.4 seconds for (var i = 0; i < 12345678; i++) { var a = new Temp(i, i, i, i); list.Add(a); } decimal sum = 0; foreach (var item in list) sum += item.A; Even if you only access data essentially it is much slower!! I say never use a linkedList. Here is another comparison performing a lot of inserts (we plan on inserting an item at the middle of the list) Linked List (51 seconds) LinkedList<Temp> list = new LinkedList<Temp>(); for (var i = 0; i < 123456; i++) { var a = new Temp(i, i, i, i); list.AddLast(a); var curNode = list.First; for (var k = 0; k < i/2; k++) // In order to insert a node at the middle of the list we need to find it curNode = curNode.Next; list.AddAfter(curNode, a); // Insert it after } decimal sum = 0; foreach (var item in list) sum += item.A; List (7.26 seconds) List<Temp> list = new List<Temp>(); for (var i = 0; i < 123456; i++) { var a = new Temp(i, i, i, i); list.Insert(i / 2, a); } decimal sum = 0; foreach (var item in list) sum += item.A; Linked List having reference of location where to insert (.04 seconds) list.AddLast(new Temp(1,1,1,1)); var referenceNode = list.First; for (var i = 0; i < 123456; i++) { var a = new Temp(i, i, i, i); list.AddLast(a); list.AddBefore(referenceNode, a); } decimal sum = 0; foreach (var item in list) sum += item.A; So only if you plan on inserting several items and you also somewhere have the reference of where you plan to insert the item then use a linked list. Just because you have to insert a lot of items it does not make it faster because searching the location where you will like to insert it takes time. A: This is adapted from Tono Nam's accepted answer correcting a few wrong measurements in it. The test: static void Main() { LinkedListPerformance.AddFirst_List(); // 12028 ms LinkedListPerformance.AddFirst_LinkedList(); // 33 ms LinkedListPerformance.AddLast_List(); // 33 ms LinkedListPerformance.AddLast_LinkedList(); // 32 ms LinkedListPerformance.Enumerate_List(); // 1.08 ms LinkedListPerformance.Enumerate_LinkedList(); // 3.4 ms //I tried below as fun exercise - not very meaningful, see code //sort of equivalent to insertion when having the reference to middle node LinkedListPerformance.AddMiddle_List(); // 5724 ms LinkedListPerformance.AddMiddle_LinkedList1(); // 36 ms LinkedListPerformance.AddMiddle_LinkedList2(); // 32 ms LinkedListPerformance.AddMiddle_LinkedList3(); // 454 ms Environment.Exit(-1); } And the code: using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace stackoverflow { static class LinkedListPerformance { class Temp { public decimal A, B, C, D; public Temp(decimal a, decimal b, decimal c, decimal d) { A = a; B = b; C = c; D = d; } } static readonly int start = 0; static readonly int end = 123456; static readonly IEnumerable<Temp> query = Enumerable.Range(start, end - start).Select(temp); static Temp temp(int i) { return new Temp(i, i, i, i); } static void StopAndPrint(this Stopwatch watch) { watch.Stop(); Console.WriteLine(watch.Elapsed.TotalMilliseconds); } public static void AddFirst_List() { var list = new List<Temp>(); var watch = Stopwatch.StartNew(); for (var i = start; i < end; i++) list.Insert(0, temp(i)); watch.StopAndPrint(); } public static void AddFirst_LinkedList() { var list = new LinkedList<Temp>(); var watch = Stopwatch.StartNew(); for (int i = start; i < end; i++) list.AddFirst(temp(i)); watch.StopAndPrint(); } public static void AddLast_List() { var list = new List<Temp>(); var watch = Stopwatch.StartNew(); for (var i = start; i < end; i++) list.Add(temp(i)); watch.StopAndPrint(); } public static void AddLast_LinkedList() { var list = new LinkedList<Temp>(); var watch = Stopwatch.StartNew(); for (int i = start; i < end; i++) list.AddLast(temp(i)); watch.StopAndPrint(); } public static void Enumerate_List() { var list = new List<Temp>(query); var watch = Stopwatch.StartNew(); foreach (var item in list) { } watch.StopAndPrint(); } public static void Enumerate_LinkedList() { var list = new LinkedList<Temp>(query); var watch = Stopwatch.StartNew(); foreach (var item in list) { } watch.StopAndPrint(); } //for the fun of it, I tried to time inserting to the middle of //linked list - this is by no means a realistic scenario! or may be //these make sense if you assume you have the reference to middle node //insertion to the middle of list public static void AddMiddle_List() { var list = new List<Temp>(); var watch = Stopwatch.StartNew(); for (var i = start; i < end; i++) list.Insert(list.Count / 2, temp(i)); watch.StopAndPrint(); } //insertion in linked list in such a fashion that //it has the same effect as inserting into the middle of list public static void AddMiddle_LinkedList1() { var list = new LinkedList<Temp>(); var watch = Stopwatch.StartNew(); LinkedListNode<Temp> evenNode = null, oddNode = null; for (int i = start; i < end; i++) { if (list.Count == 0) oddNode = evenNode = list.AddLast(temp(i)); else if (list.Count % 2 == 1) oddNode = list.AddBefore(evenNode, temp(i)); else evenNode = list.AddAfter(oddNode, temp(i)); } watch.StopAndPrint(); } //another hacky way public static void AddMiddle_LinkedList2() { var list = new LinkedList<Temp>(); var watch = Stopwatch.StartNew(); for (var i = start + 1; i < end; i += 2) list.AddLast(temp(i)); for (int i = end - 2; i >= 0; i -= 2) list.AddLast(temp(i)); watch.StopAndPrint(); } //OP's original more sensible approach, but I tried to filter out //the intermediate iteration cost in finding the middle node. public static void AddMiddle_LinkedList3() { var list = new LinkedList<Temp>(); var watch = Stopwatch.StartNew(); for (var i = start; i < end; i++) { if (list.Count == 0) list.AddLast(temp(i)); else { watch.Stop(); var curNode = list.First; for (var j = 0; j < list.Count / 2; j++) curNode = curNode.Next; watch.Start(); list.AddBefore(curNode, temp(i)); } } watch.StopAndPrint(); } } } You can see the results are in accordance with theoretical performance others have documented here. Quite clear - LinkedList<T> gains big time in case of insertions. I haven't tested for removal from the middle of list, but the result should be the same. Of course List<T> has other areas where it performs way better like O(1) random access. A: Use LinkedList<> when * *You don't know how many objects are coming through the flood gate. For example, Token Stream. *When you ONLY wanted to delete\insert at the ends. For everything else, it is better to use List<>. A: I do agree with most of the point made above. And I also agree that List looks like a more obvious choice in most of the cases. But, I just want to add that there are many instance where LinkedList are far better choice than List for better efficiency. * *Suppose you are traversing through the elements and you want to perform lot of insertions/deletion; LinkedList does it in linear O(n) time, whereas List does it in quadratic O(n^2) time. *Suppose you want to access bigger objects again and again, LinkedList become very more useful. *Deque() and queue() are better implemented using LinkedList. *Increasing the size of LinkedList is much easier and better once you are dealing with many and bigger objects. Hope someone would find these comments useful. A: I asked a similar question related to performance of the LinkedList collection, and discovered Steven Cleary's C# implement of Deque was a solution. Unlike the Queue collection, Deque allows moving items on/off front and back. It is similar to linked list, but with improved performance. A: In .NET, Lists are represented as Arrays. Therefore using a normal List would be quite faster in comparison to LinkedList.That is why people above see the results they see. Why should you use the List? I would say it depends. List creates 4 elements if you don't have any specified. The moment you exceed this limit, it copies stuff to a new array, leaving the old one in the hands of the garbage collector. It then doubles the size. In this case, it creates a new array with 8 elements. Imagine having a list with 1 million elements, and you add 1 more. It will essentially create a whole new array with double the size you need. The new array would be with 2Mil capacity however, you only needed 1Mil and 1. Essentially leaving stuff behind in GEN2 for the garbage collector and so on. So it can actually end up being a huge bottleneck. You should be careful about that.
{ "language": "en", "url": "https://stackoverflow.com/questions/169973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "456" }
Q: Mock testing and PHP's magic __get method I'm having problems when trying to mock objects with __get and __set methods (using simpletest). Writing mock responses for __get doesn't smell right - the tests seem too tightly tied to implementation. Any recommendations for testing, or should I just avoid the magic methods completely? A: I had the same problem and found the solution in the SimpleTest test cases: From mock_objects_test.php: class ClassWithSpecialMethods { function __get($name) { } function __set($name, $value) { } function __isset($name) { } function __unset($name) { } function __call($method, $arguments) { } function __toString() { } } Mock::generate('ClassWithSpecialMethods'); ... snip ... function testReturnFromSpecialAccessor() { $mock = new MockClassWithSpecialMethods(); $mock->setReturnValue('__get', '1st Return', array('first')); $mock->setReturnValue('__get', '2nd Return', array('second')); $this->assertEqual($mock->first, '1st Return'); $this->assertEqual($mock->second, '2nd Return'); } function testcanExpectTheSettingOfValue() { $mock = new MockClassWithSpecialMethods(); $mock->expectOnce('__set', array('a', 'A')); $mock->a = 'A'; } A bit clunky, but it works. On the other hand, I think you're better off avoiding them... the large corporate system I'm working on uses them heavily and it's a nightmare to understand/visualise/debug/do anything with!
{ "language": "en", "url": "https://stackoverflow.com/questions/169981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is your experience with auditing features (Oracle)? Did you ever use Oracle auditing features on a production db? How did that impact on performances, and are there differences you noticed between different versions of Oracle? A: Perfomance-wise, you'd need to auditing a hell of a lot of information for Oracle 10.2 FGA to be a significant problem. I haven't used earlier versions or 11g. Even simply for manageability reasons, you need to look at auditing only pertinent information... From the top of my head, I don't see why CPU/IO utilization would ever go more than a few percent over normal utilization for most enterprise applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/169989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can you load the FLVPlayback skin SWF in another directory? Per this Adobe KB tech note is there any way around having to place the FLVPlayback skin SWF in same directory as HTML file the container SWF is loaded from? It pains me to have to put a SWF in my site's root directory. I think loading the Flash video in an iframe would solve this problem, but is that a good practice? I generally shy away from using iframes because of padding, margin, and sizing issues between browsers. Maybe that's not an issue anymore with CSS. A: Well, you can place the skin in another directory as long as you specify the path (relative to the loading HTML) in the "skin" parameter for your FLV playback component in the component inspector. Troubleshooting is very easy if you use the Net panel in Firebug or a similar tool. Using an iframe works and don't cause rendering problems as long as you take care that there's no margin or padding inside the iframe. However, you will need another HTML file which can make maintaining your site more of a hassle. If you are publishing a lot of video files, you might find that it's more convenient to use a standalone player such as the JW Media Player. A: You can set a different URL for the FLVPlayback component in two ways: 1) In the Component Parameters section of the Properties window, way at the bottom of the list of skins is the option Custom URL. Set its path there. 2) You can set it by Actionscript using the 'skin' parameter for your FLVPlayback instance, eg: myFlv.skin="path/to/myRadSkin.swf". This is the only way you can set the skin dynamically if you need to. To use #2, your instance has to have been created in-code using the new statement. You can't dynamically change the skin of an existing instance that you dragged to the stage.
{ "language": "en", "url": "https://stackoverflow.com/questions/169996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FCKeditor vs TinyMCE and XHTML Compliance I'm after (short) opinions on FCKeditor vs TinyMCE and whether either or both are XHTML compliant. In the interest of keeping with the spirit of stackoverflow, if someone has already made your point, just upvote them. A: TinyMCE produces absolute garbage. FCK produces less garbage, but can also conflict with browser-in-built styling (by default FCK styles with tags rather than style attributes, eg <strong> rather than <span style="font-weight: bold;">, however hitting cmd-b in Safari produces the latter, and FCK will be unaware of it, thus allowing you to nest styles to no effect, and not allowing you to use FCK functionality to reverse in-built functionality). Both produce garbage in IE but that is because IE's DOM is insane. For instance: http://annevankesteren.nl/2005/07/contenteditable A: From my experience FCKEditor does indeed produce XHTML compliant code, but that code is slightly different depending on what browser you're in. Mostly, this was related to the enter key producing either a break or a paragraph, and I think it may have been configurable. A: Afaik, they both allow the browser to mess with the code they produce, which doesn't result in XHTML compliance. XStandard is the only rich web editor I'm aware of that produces XHTML compliant code, but unfortunately it requires a client-side install, which rules it out for real web stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/170001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to remove only the parent element and not its child elements in JavaScript? Let's say: <div> pre text <div class="remove-just-this"> <p>child foo</p> <p>child bar</p> nested text </div> post text </div> to this: <div> pre text <p>child foo</p> <p>child bar</p> nested text post text </div> I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this. A: Replace div with its contents: const wrapper = document.querySelector('.remove-just-this'); wrapper.outerHTML = wrapper.innerHTML; <div> pre text <div class="remove-just-this"> <p>child foo</p> <p>child bar</p> nested text </div> post text </div> A: The library-independent method is to insert all child nodes of the element to be removed before itself (which implicitly removes them from their old position), before you remove it: while (nodeToBeRemoved.firstChild) { nodeToBeRemoved.parentNode.insertBefore(nodeToBeRemoved.firstChild, nodeToBeRemoved); } nodeToBeRemoved.parentNode.removeChild(nodeToBeRemoved); This will move all child nodes to the correct place in the right order. A: You should make sure to do this with the DOM, not innerHTML (and if using the jQuery solution provided by jk, make sure that it moves the DOM nodes rather than using innerHTML internally), in order to preserve things like event handlers. My answer is a lot like insin's, but will perform better for large structures (appending each node separately can be taxing on redraws where CSS has to be reapplied for each appendChild; with a DocumentFragment, this only occurs once as it is not made visible until after its children are all appended and it is added to the document). var fragment = document.createDocumentFragment(); while(element.firstChild) { fragment.appendChild(element.firstChild); } element.parentNode.replaceChild(fragment, element); A: $('.remove-just-this > *').unwrap() A: More elegant way is $('.remove-just-this').contents().unwrap(); A: Whichever library you are using you have to clone the inner div before removing the outer div from the DOM. Then you have to add the cloned inner div to the place in the DOM where the outer div was. So the steps are: * *Save a reference to the outer div's parent in a variable *Copy the inner div to another variable. This can be done in a quick and dirty way by saving the innerHTML of the inner div to a variable or you can copy the inner tree recursively node by node. *Call removeChild on the outer div's parent with the outer div as the argument. *Insert the copied inner content to the outer div's parent in the correct position. Some libraries will do some or all of this for you but something like the above will be going on under the hood. A: And, since you tried in mootools as well, here's the solution in mootools. var children = $('remove-just-this').getChildren(); children.replaces($('remove-just-this'); Note that's totally untested, but I have worked with mootools before and it should work. http://mootools.net/docs/Element/Element#Element:getChildren http://mootools.net/docs/Element/Element#Element:replaces A: I was looking for the best answer performance-wise while working on an important DOM. eyelidlessness's answer was pointing out that using javascript the performances would be best. I've made the following execution time tests on 5,000 lines and 400,000 characters with a complexe DOM composition inside the section to remove. I'm using an ID instead of a class for convenient reason when using javascript. Using $.unwrap() $('#remove-just-this').contents().unwrap(); 201.237ms Using $.replaceWith() var cnt = $("#remove-just-this").contents(); $("#remove-just-this").replaceWith(cnt); 156.983ms Using DocumentFragment in javascript var element = document.getElementById('remove-just-this'); var fragment = document.createDocumentFragment(); while(element.firstChild) { fragment.appendChild(element.firstChild); } element.parentNode.replaceChild(fragment, element); 147.211ms Conclusion Performance-wise, even on a relatively big DOM structure, the difference between using jQuery and javascript is not huge. Surprisingly $.unwrap() is most costly than $.replaceWith(). The tests have been done with jQuery 1.12.4. A: Use modern JS! const node = document.getElementsByClassName('.remove-just-this')[0]; node.replaceWith(...node.childNodes); // or node.children, if you don't want textNodes oldNode.replaceWith(newNode) is valid ES5 ...array is the spread operator, passing each array element as a parameter A: Using jQuery you can do this: var cnt = $(".remove-just-this").contents(); $(".remove-just-this").replaceWith(cnt); Quick links to the documentation: * *contents( ) : jQuery *replaceWith( content : [String | Element | jQuery] ) : jQuery A: if you'd like to do this same thing in pyjamas, here's how it's done. it works great (thank you to eyelidness). i've been able to make a proper rich text editor which properly does styles without messing up, thanks to this. def remove_node(doc, element): """ removes a specific node, adding its children in its place """ fragment = doc.createDocumentFragment() while element.firstChild: fragment.appendChild(element.firstChild) parent = element.parentNode parent.insertBefore(fragment, element) parent.removeChild(element) A: If you are dealing with multiple rows, as it was in my use case you are probably better off with something along these lines: $(".card_row").each(function(){ var cnt = $(this).contents(); $(this).replaceWith(cnt); }); A: The solution with replaceWith only works when there is one matching element. When there are more matching elements use this: $(".remove-just-this").contents().unwrap();
{ "language": "en", "url": "https://stackoverflow.com/questions/170004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "98" }
Q: Please comment on this simple software protection schema I was asked implement a licensing schema for our product. They are very expensive products with few customers sparsely distributed around the world and basically every one of them has a design environment (a windows application installed on single windows machines, from 1 to 150 client machines per customer) and a web server that hosts production environment (1 to 8 machines per customer). Our product is licensed for server usage so customers can use any number of clients; we've decided not to license the server part (because it's subject to SLA agreements) but only the client, because, after some time without capability to use the client the system becomes basically useless. Our basic assumption is that the customer is "honest enough" and only thing we would like to cover is stopping the client design environment if not properly licensed with a time expiration license. I've evaluated different licensing product and they are or too expensive or too difficult to manage, so I've come up with this simple solution: * *The license will be a simple signed XML file, signed using the standard XML Signature feature of w3c, using a private key that will be given to the admin department on a USB key; if they lose of copy it then the licensing schema will fail but it will be their fault *The client will open the license file on startup and check its validity using a public key embedded in the binaries *If license XML is valid and the data in it (expiration date and product name) are correct than the designer work; if not, an appropriate message will be shown Any ideas about possible problems or how to improve the scenario? A: I have yet to see a licensing scheme that wasn't broken in a few weeks provided there was sufficient interest. Your scheme looks very good (though be certain that if someone really wants to, they'll break it). Whatever you do, you should follow Eric Sink's advice: The goal should simply be to "keep honest people honest". If we go further than this, only two things happen: * *We fight a battle we cannot win. Those who want to cheat will succeed. *We hurt the honest users of our product by making it more difficult to use. Since you're implementing a license scheme for a program designed for corporate use, you can go even simpler and just keep some kind of id and expiration date along with a simple signature on the client and refuse to start if the license expired or signature failed. It's not that hard to break it, but no licensing scheme is and if you consider your customers honest, this will be more than enough. A: It's not completely clear from your question how your scheme works. Does every instance of the client software have a different key? How long does the license last? Do you have a different key per customer? How is the license paid for? How is a license renewed? If you are trying to control numbers of usages of the client code then only the first one above will do it. At the end of the day, in the world you appear to inhabit, I suspect that you are going to have to live in trust that there are no blatant infringements of your license. Most decent sized organisations (which it sounds like your customers would be) have a responsibility not to infringe which can lead them to serious consequences if they break the license agreements. They will be audited on it periodically too and you probably have some statutory rights to go and check their usage (if not you should write it into your license agreement). Where it becomes very dangerous for you is if the contents of the USB keys find their way onto the web. In that regard any scheme which uses a published key is vulnerable to a wilful disclosure of the secrets. I'm certain there is a lot of literature on this subject, so it is probably worth you continuing your research. BTW I'm not sure about your reference to SLAs in the middle part about your server licensing. Licensing and SLAs are very different. A license is the clients obligation an SLA is yours. A: if you give them the private key, what is to prevent them from creating more signed XML files instead of buying additional licenses from you? or is it a site-license? if the latter, what is to prevent them from creating licenses for other people/sites? in general, development licensing schemes tie the license to a particular machine using the MAC address and/or hard drive serial number, or sometimes just with an activation key (which is usually just a hash of the hardware info) and typically the encoding is done with a private key that you keep secret, and the license is verified with a public key; the client never has the private key, otherwise they can - if so inclined - generate their own licenses A: I agree with Steven A. Lowe (I don't have 15 reputation, so I couldn't vote him up). This also seems too complicated. Do you want it to be unbreakable? you can't. Any sufficiently motivated guru would find a way around it. Sometimes a simple licensing scheme works best: I suggest a simple encrypted file that the admin puts somewhere the client can access - it would contain the client name and expiry date. You use the client name from the file in all printed reports (that's what most PHBs care About, that way they would not use the license that prints somebody else's name).
{ "language": "en", "url": "https://stackoverflow.com/questions/170006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Your Scrum definition of Done While Scrum is easy in theory and hard in practice, I wanted to hear your definition of Done; i.e. what are the gates (unit test, code coverage > 80%, code reviews, load tests, perf.test, functional tests, etc.) your product has to go through before you can label the product "Done" A: I'd say it is up to your team to decide. Talk with the product owner. Ideally done would be when a story is in Production and being used. However, there is a time gap between when a story is development complete and in Live. Makes it hard to track how long a story took to develop. In my team, our definition of done is, when the developer completes a story,and does a "show and tell" to the rest of the team(testers, product owner), and if everyone is happy it goes into the subversion trunk. Further testing is done off a automated build from trunk. A: In a perfect world, the product shall be in a shippable state at the end of every iteration. Now this actually depends on your product, your market, your customers and might not be possible. If you cannot achieve this, then the next planning horizon apply: the release. The Team as a whole should decide what is required to ship the product and plan accordingly. What helps here is to define "done" at the task level. Defining done here is much more simple: one task is done when you can start another one: everything is tested, integrated. The Team can alo define this state: documented, reviewed, included in automatic build, no known problem, accpeted by On-Site Customer ... Having all your tasks really "done", Having all tour backlog items (or User stories, whateveryou call them) realy "done" allow to be "done" at every iteration, which helps preserving the product in a shippable or deployable state. A: There are three nice articles by Mitch Lacey, Dhaval Panchal and Mayank Gupta on this on the ScrumAlliance website. EDIT: Basically the whole point is that done is defined on a project-by-project basis by the team. The basic need is to agree on the definition, not what the definition is. A: We at TargetProcess use the following definition of Done for user story: * *Short Spec created *Implemented/Unit Tests created *Acceptance Tests created *100% Acceptance tests passed *Product Owner demo passed *Known bugs fixed A: Everything that will make your "stabilization period" (ie work required between the code freeze and the release to the client) shorter.
{ "language": "en", "url": "https://stackoverflow.com/questions/170009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: In PHP will a session be created if a browser is not used I have an API that is dependent on certain state information between requests. As an easy first version of the code, I am simply using PHP session's to store the state information instead of something more advanced (APC, memcache, DB). Throughout my initial testing in a web browser, everything worked perfectly. However, it seems that when clients try to connect through non-browser methods such as Curl or wget, the state information is not being preserved. Will a PHP session only be created if a browser is requesting the page? I am explicitly starting the session with session_start() as well as naming it before hand with session_name(). An added note. I learned that one of the major problems I was having was that I was naming the session instead of setting the session id via session_id($id); My intention in using session_name() was to retrieve the same session that was previously created, and the correct way to do this is by setting the session_id not the session_name. It seems that session information will be persisted on the server as noted below (THANK YOU). But to keep this you must pass the session id, or, as in my case, any other id that would uniquely identify the user. Use this id as the session_id and your sessions will function as expected. A: Session Cookies Remember that HTTP is stateless, so sessions are tracked on your server, but the client has to identify itself with each request. When you declare session_start(), your browser is usually setting a cookie (the "PHP Session Id"), and then identifying itself by sending the cookie value with each request. When a script is called using a request with a session value, then the session_start() function will try to look up the session. To prove this to yourself, notice that sessions die when you clear your cookies.. many will die even as soon as you quit the browser, if the cookie is a "session" cookie (a temporary one). You mentioned that you're naming the session.. take a look in your browser cookies and see if you can find a cookie with the same name. All of this is to say that cookies are playing an active role in your sessions, so if the client doesn't support cookies, then you can't do a session the way you're currently doing it.. at least not for those alternative clients. A session will be created on the server; the question is whether or not the client is participating. If cookies aren't an option for your client, you're going to have to find another way to pass a session id to the server. This can be done in the query string, for example, although it's a considered a bit less private to send a session id in this way. mysite.com?PHPSESSID=10alksdjfq9e How do to this specifically may vary with your version of PHP, but it's basically just a configuration. If the proper runtime options are set, PHP will transparently add the session id as a query parameter to links on the page (same-source only, of course). You can find the specifics for setting that up on the PHP website. Sidenote: Years ago, this was a common problem when attempting to implement a session. Cookies were newer and many people were turning off the cookie support in their browsers because of purported security concerns. Sidenote: @Uberfuzzy makes a good point- Using sessions with curl or wget is actually possible. The problem is that it's less automatic. A user might dump header values into a file and use the values on future requests. curl has some "cookie awareness" flags, which allow you to handle this more easily, but you still must explicitly do it. Then again, you could use this to your advantage. If curl is available on your alternative client, then you can plausibly make the call yourself, using the cookie awareness flags. Refer to the curl manual. A: If you call session_start(), then a session will be created if the client isn't in an existing one. If the client doesn't support (or is configured to ignore) the cookies or querystring mechanism used to maintain the session, a new session will be created on every request. This may bloat your session storage mechanism with unused sessions. It might be a better idea to only call session_start() when you have something to store in the session (e.g. user login, or something else that robots aren't likely to do), if you feel this is likely to be a problem. A: Will a PHP session only be created if a browser is requesting the page? Short answer: Yes. Sessions were created specifically to solve the HTTP stateless problem by leveraging browser features. APC, memcached, DB, etc. don't matter. Those are just storage methods for the session, and will suffer from the same problem. Longer answer: The concept of sessions were created to account for the fact that HTTP is a stateless protocol, and it turns out that state's pretty important for a wide variety of software applications. The most common way of implementing sessions is with cookies. PHP sends the session ID in a cookie, and the browser sends the cookie with the session ID back. This ID is used on the server to find whatever information you've stored in the session. PHP has the capacity to include and read a session ID at the end of a URLs, but this assumes that users will navigate to pages on your site/application by clicking links that include a generated session ID. In your specific case, it is possible to use cookies with curl (and possibly wget). Curl is a web browser, just one without a GUI. If it's the command line curl program you're using (as opposed to the C library, PHP extension,etc.) read up on the following options -b/--cookie -c/--cookie-jar -j/--junk-session-cookies
{ "language": "en", "url": "https://stackoverflow.com/questions/170019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What factors that degrade the performance of a SQL Server 2000 Job? We are currently running a SQL Job that archives data daily at every 10PM. However, the end users complains that from 10PM to 12, the page shows a time out error. Here's the pseudocode of the job while @jobArchive = 1 and @countProcecessedItem < @maxItem exec ArchiveItems @countProcecessedItem out if error occured set @jobArchive = 0 delay '00:10' The ArchiveItems stored procedure grabs the top 100 item that was created 30 days ago, process and archive them in another database and delete the item in the original table, including other tables that are related with it. finally sets the @countProcecessedItem with the number of item processed. The ArchiveItems also creates and deletes temporary tables it used to hold some records. Note: if the information I've provide is incomplete, reply and I'll gladly add more information if possible. A: Only thing not clear is it the ArchiveItems also delete or not data from database. Deleting rows in SQL Server is a very expensive operation that causes a lot of Locking condition on the database, with possibility to have table and database locks and this typically causes timeout. If you're deleting data what you can do is: * *Set a "logical" deletion flag on the relevant row and consider it in the query you do to read data *Perform deletes in batches. I've found that (in my application) deleting about 250 rows in each transaction gives the faster operation, taking a lot less time than issuing 250 delete command in a separate way Hope this helps, but archiving and deleting data from SQL Server is a very tough job. A: While the ArchiveItems process is deleting the 100 records, it is locking the table. Make sure you have indexes in place to make the delete run quickly; run a Profiler session during that timeframe and see how long it takes. You may need to add an index on the date field if it is doing a Table Scan or Index Scan to find the records. On the end user's side, you may be able to add a READUNCOMMITTED or NOLOCK hint on the queries; this allows the query to run while the deletes are taking place, but with the possibility of returning records that are about to be deleted. Also consider a different timeframe for the job; find the time that has the least user activity, or only do the archiving once a month during a maintenance window. A: As another poster mentioned, slow DELETEs are often caused by not having a suitable index, or a suitable index needs rebuilding. During DELETEs it is not uncommon for locks to be escalated ROW -> PAGE -> TABLE. You reduce locking by * *Adding a ROWLOCK hint (but be aware it will likely consume more memory) *Randomising the Rows that are deleted (makes lock escalation less likely) *Easiest: Adding a short WAITFOR in ArchiveItems WHILE someCondition BEGIN DELETE some rows -- Give other processes a chance... WAITFOR DELAY '000:00:00.250' END I wouldn't use the NOLOCK hint if the deletes are happening during periods with other activity taking place, and you want to maintain integrity of your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/170021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How would you simplify Entering and Exiting a ReaderWriterLock? This seems very noisy to me. Five lines of overhead is just too much. m_Lock.EnterReadLock() Try Return m_List.Count Finally m_Lock.ExitReadLock() End Try So how would you simply this? A: All the solutions posted so far are at risk of deadlock. A using block like this: ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); using (sync.Read()) { // Do stuff } gets converted into something like this: ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); IDisposable d = sync.Read(); try { // Do stuff } finally { d.Dispose(); } This means that a ThreadAbortException (or similar) could happen between sync.Read() and the try block. When this happens the finally block never gets called, and the lock is never released! For more information, and a better implementation see: Deadlock with ReaderWriterLockSlim and other lock objects. In short, the better implementation comes down to moving the lock into the try block like so: ReaderWriterLockSlim myLock = new ReaderWriterLockSlim(); try { myLock.EnterReadLock(); // Do stuff } finally { // Release the lock myLock.ExitReadLock(); } A wrapper class like the one in the accepted answer would be: /// <summary> /// Manager for a lock object that acquires and releases the lock in a manner /// that avoids the common problem of deadlock within the using block /// initialisation. /// </summary> /// <remarks> /// This manager object is, by design, not itself thread-safe. /// </remarks> public sealed class ReaderWriterLockMgr : IDisposable { /// <summary> /// Local reference to the lock object managed /// </summary> private ReaderWriterLockSlim _readerWriterLock = null; private enum LockTypes { None, Read, Write, Upgradeable } /// <summary> /// The type of lock acquired by this manager /// </summary> private LockTypes _enteredLockType = LockTypes.None; /// <summary> /// Manager object construction that does not acquire any lock /// </summary> /// <param name="ReaderWriterLock">The lock object to manage</param> public ReaderWriterLockMgr(ReaderWriterLockSlim ReaderWriterLock) { if (ReaderWriterLock == null) throw new ArgumentNullException("ReaderWriterLock"); _readerWriterLock = ReaderWriterLock; } /// <summary> /// Call EnterReadLock on the managed lock /// </summary> public void EnterReadLock() { if (_readerWriterLock == null) throw new ObjectDisposedException(GetType().FullName); if (_enteredLockType != LockTypes.None) throw new InvalidOperationException("Create a new ReaderWriterLockMgr for each state you wish to enter"); // Allow exceptions by the Enter* call to propogate // and prevent updating of _enteredLockType _readerWriterLock.EnterReadLock(); _enteredLockType = LockTypes.Read; } /// <summary> /// Call EnterWriteLock on the managed lock /// </summary> public void EnterWriteLock() { if (_readerWriterLock == null) throw new ObjectDisposedException(GetType().FullName); if (_enteredLockType != LockTypes.None) throw new InvalidOperationException("Create a new ReaderWriterLockMgr for each state you wish to enter"); // Allow exceptions by the Enter* call to propogate // and prevent updating of _enteredLockType _readerWriterLock.EnterWriteLock(); _enteredLockType = LockTypes.Write; } /// <summary> /// Call EnterUpgradeableReadLock on the managed lock /// </summary> public void EnterUpgradeableReadLock() { if (_readerWriterLock == null) throw new ObjectDisposedException(GetType().FullName); if (_enteredLockType != LockTypes.None) throw new InvalidOperationException("Create a new ReaderWriterLockMgr for each state you wish to enter"); // Allow exceptions by the Enter* call to propogate // and prevent updating of _enteredLockType _readerWriterLock.EnterUpgradeableReadLock(); _enteredLockType = LockTypes.Upgradeable; } /// <summary> /// Exit the lock, allowing re-entry later on whilst this manager is in scope /// </summary> /// <returns>Whether the lock was previously held</returns> public bool ExitLock() { switch (_enteredLockType) { case LockTypes.Read: _readerWriterLock.ExitReadLock(); _enteredLockType = LockTypes.None; return true; case LockTypes.Write: _readerWriterLock.ExitWriteLock(); _enteredLockType = LockTypes.None; return true; case LockTypes.Upgradeable: _readerWriterLock.ExitUpgradeableReadLock(); _enteredLockType = LockTypes.None; return true; } return false; } /// <summary> /// Dispose of the lock manager, releasing any lock held /// </summary> public void Dispose() { if (_readerWriterLock != null) { ExitLock(); // Tidy up managed resources // Release reference to the lock so that it gets garbage collected // when there are no more references to it _readerWriterLock = null; // Call GC.SupressFinalize to take this object off the finalization // queue and prevent finalization code for this object from // executing a second time. GC.SuppressFinalize(this); } } protected ~ReaderWriterLockMgr() { if (_readerWriterLock != null) ExitLock(); // Leave references to managed resources so that the garbage collector can follow them } } Making usage as follows: ReaderWriterLockSlim myLock = new ReaderWriterLockSlim(); using (ReaderWriterLockMgr lockMgr = new ReaderWriterLockMgr(myLock)) { lockMgr.EnterReadLock(); // Do stuff } Also, from Joe Duffy's Blog Next, the lock is not robust to asynchronous exceptions such as thread aborts and out of memory conditions. If one of these occurs while in the middle of one of the lock’s methods, the lock state can be corrupt, causing subsequent deadlocks, unhandled exceptions, and (sadly) due to the use of spin locks internally, a pegged 100% CPU. So if you’re going to be running your code in an environment that regularly uses thread aborts or attempts to survive hard OOMs, you’re not going to be happy with this lock. A: I was thinking the same, but in C# ;-p using System; using System.Threading; class Program { static void Main() { ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); using (sync.Read()) { // etc } } } public static class ReaderWriterExt { sealed class ReadLockToken : IDisposable { private ReaderWriterLockSlim sync; public ReadLockToken(ReaderWriterLockSlim sync) { this.sync = sync; sync.EnterReadLock(); } public void Dispose() { if (sync != null) { sync.ExitReadLock(); sync = null; } } } public static IDisposable Read(this ReaderWriterLockSlim obj) { return new ReadLockToken(obj); } } A: This is not my invention but it certainly has made by hair a little less gray. internal static class ReaderWriteLockExtensions { private struct Disposable : IDisposable { private readonly Action m_action; private Sentinel m_sentinel; public Disposable(Action action) { m_action = action; m_sentinel = new Sentinel(); } public void Dispose() { m_action(); GC.SuppressFinalize(m_sentinel); } } private class Sentinel { ~Sentinel() { throw new InvalidOperationException("Lock not properly disposed."); } } public static IDisposable AcquireReadLock(this ReaderWriterLockSlim lock) { lock.EnterReadLock(); return new Disposable(lock.ExitReadLock); } public static IDisposable AcquireUpgradableReadLock(this ReaderWriterLockSlim lock) { lock.EnterUpgradeableReadLock(); return new Disposable(lock.ExitUpgradeableReadLock); } public static IDisposable AcquireWriteLock(this ReaderWriterLockSlim lock) { lock.EnterWriteLock(); return new Disposable(lock.ExitWriteLock); } } How to use: using (m_lock.AcquireReadLock()) { // Do stuff } A: I ended up doing this, but I'm still open to better ways or flaws in my design. Using m_Lock.ReadSection Return m_List.Count End Using This uses this extension method/class: <Extension()> Public Function ReadSection(ByVal lock As ReaderWriterLockSlim) As ReadWrapper Return New ReadWrapper(lock) End Function Public NotInheritable Class ReadWrapper Implements IDisposable Private m_Lock As ReaderWriterLockSlim Public Sub New(ByVal lock As ReaderWriterLockSlim) m_Lock = lock m_Lock.EnterReadLock() End Sub Public Sub Dispose() Implements IDisposable.Dispose m_Lock.ExitReadLock() End Sub End Class A: Since the point of a lock is to protect some piece of memory, I think it would be useful to wrap that memory in a "Locked" object, and only make it accessble through the various lock tokens (as mentioned by Mark): // Stores a private List<T>, only accessible through lock tokens // returned by Read, Write, and UpgradableRead. var lockedList = new LockedList<T>( ); using( var r = lockedList.Read( ) ) { foreach( T item in r.Reader ) ... } using( var w = lockedList.Write( ) ) { w.Writer.Add( new T( ) ); } T t = ...; using( var u = lockedList.UpgradableRead( ) ) { if( !u.Reader.Contains( t ) ) using( var w = u.Upgrade( ) ) w.Writer.Add( t ); } Now the only way to access the internal list is by calling the appropriate accessor. This works particularly well for List<T>, since it already has the ReadOnlyCollection<T> wrapper. For other types, you could always create a Locked<T,T>, but then you lose out on the nice readable/writable type distinction. One improvement might be to define the R and W types as disposable wrappers themselves, which would protected against (inadvertant) errors like: List<T> list; using( var w = lockedList.Write( ) ) list = w.Writable; //BAD: "locked" object leaked outside of lock scope list.MakeChangesWithoutHoldingLock( ); However, this would make Locked more complicated to use, and the current version does gives you the same protection you have when manually locking a shared member. sealed class LockedList<T> : Locked<List<T>, ReadOnlyCollection<T>> { public LockedList( ) : base( new List<T>( ), list => list.AsReadOnly( ) ) { } } public class Locked<W, R> where W : class where R : class { private readonly LockerState state_; public Locked( W writer, R reader ) { this.state_ = new LockerState( reader, writer ); } public Locked( W writer, Func<W, R> getReader ) : this( writer, getReader( writer ) ) { } public IReadable Read( ) { return new Readable( this.state_ ); } public IWritable Write( ) { return new Writable( this.state_ ); } public IUpgradable UpgradableRead( ) { return new Upgradable( this.state_ ); } public interface IReadable : IDisposable { R Reader { get; } } public interface IWritable : IDisposable { W Writer { get; } } public interface IUpgradable : IReadable { IWritable Upgrade( );} #region Private Implementation Details sealed class LockerState { public readonly R Reader; public readonly W Writer; public readonly ReaderWriterLockSlim Sync; public LockerState( R reader, W writer ) { Debug.Assert( reader != null && writer != null ); this.Reader = reader; this.Writer = writer; this.Sync = new ReaderWriterLockSlim( ); } } abstract class Accessor : IDisposable { private LockerState state_; protected LockerState State { get { return this.state_; } } protected Accessor( LockerState state ) { Debug.Assert( state != null ); this.Acquire( state.Sync ); this.state_ = state; } protected abstract void Acquire( ReaderWriterLockSlim sync ); protected abstract void Release( ReaderWriterLockSlim sync ); public void Dispose( ) { if( this.state_ != null ) { var sync = this.state_.Sync; this.state_ = null; this.Release( sync ); } } } class Readable : Accessor, IReadable { public Readable( LockerState state ) : base( state ) { } public R Reader { get { return this.State.Reader; } } protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterReadLock( ); } protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitReadLock( ); } } sealed class Writable : Accessor, IWritable { public Writable( LockerState state ) : base( state ) { } public W Writer { get { return this.State.Writer; } } protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterWriteLock( ); } protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitWriteLock( ); } } sealed class Upgradable : Readable, IUpgradable { public Upgradable( LockerState state ) : base( state ) { } public IWritable Upgrade( ) { return new Writable( this.State ); } protected override void Acquire( ReaderWriterLockSlim sync ) { sync.EnterUpgradeableReadLock( ); } protected override void Release( ReaderWriterLockSlim sync ) { sync.ExitUpgradeableReadLock( ); } } #endregion }
{ "language": "en", "url": "https://stackoverflow.com/questions/170028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Decent profiler for Windows? Does windows have any decent sampling (eg. non-instrumenting) profilers available? Preferably something akin to Shark on MacOS, although i am willing to accept that i am going to have to pay for such a profiler on windows. I've tried the profiler in VS Team Suite and was not overly impressed, and was wondering if there were any other good ones. [Edit: Erk, i forgot to say this is for C/C++, rather than .NET -- sorry for any confusion] A: AMD's CodeAnalyst is FREE here A: We use both VTune and AQTime, and I can vouch for both. Which works best for you depends on your needs. Both have free trial versions - I suggest you give them a go. A: The Windows Driver Kit includes a non-instrumenting user/kernel sampling profiler called "kernrate". It seems useful for profiling multi-process applications, applications that spend most of their time in the kernel, and device drivers (of course). It's also available in the KrView (Kernrate Viewer) and Windows Server 2003 Resource Kit Tools packages. Kernrate works on Windows 2000 and later (unlike Xperf, which requires Vista / Server 2008). It's command-line based and the documentation has a somewhat intimidating list of options. I'm not sure if it can record call stacks or just the program counter. If you use a symbol server, make sure to put an up-to-date dbghelp.dll and symsrv.dll in the same directory as kernrate.exe to prevent it from using the ancient version of dbghelp.dll that is installed in %SystemRoot%\system32. A: I have tried Intel's vtune with a rather large project about two years ago. It was an instrumenting profiler then and it took so long to instrument the DLL that I was attempting to profile that I eventually lost patience after an hour. The one tool that I have had quite good success and which i would highly recommend is that of AQTime. It not only provides excellent performance profiling resources but it also doe really good memory profiling which has been of significant help to me in tracking down memory leaks. A: For Windows, check out the free Xperf that ships with the Windows SDK. It uses sampled profile, has some useful UI, & does not require instrumentation. Quite useful for tracking down performance problems. You can answer questions like: Who is using the most CPU? Drill down to function name using call stacks. Who is allocating the most memory? Outstanding memory allocations (leaks) Who is doing the most registry queries? Disk writes? etc. A: I know I'm adding my answer months after this question was asked, but I thought I'd point out a decent, open-source profiler: Very Sleepy. It doesn't have the feature count that some of the other profilers mentioned before do, but it's a pretty respectable sampling profiler that will work very well in most situations. A: Intel VTune is good and is non-instrumenting. We evaluated a whole bunch of profilers for Windows, and this was the best for working with driver code (though it does unmanaged user level code as well). A particular strength is that it reads all the Intel processor performance counters, so you can get a good understanding of why your code is running slowly, and it was useful for putting prefetch instructions into our code and sorting out data layout to work well with the cache lines, and the way cache lines get invalidated in multi core systems. It is commercial, and I have to say it isn't the easiest UI in the world. A: Luke Stackwalker seems promising -- it's not as polished as I'd like, but it is open source and it does do something that seems very close to what @Mike Dunlavey keeps saying we ought to do. (Of course, it then tries to smoosh it all down into the typically-unhelpful call graphs that Mike is so weary of, but it shouldn't be too hard to fix that with the source as our ally.) It even seems to count time spent waiting in the kernel, as far as I can tell... A: I'm not sure what a non-instrumenting profiler is, but I can say for .NET I love RedGate's ANTS Profiler. Version 3 beats the MS version for ease of use and Version 4, which allows arbitrary time slices, makes MS look like a joke.
{ "language": "en", "url": "https://stackoverflow.com/questions/170036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: ActiveX events between apartments Environment: VS2008 (ATL), Borland Developer Studio 2006. Hello all. I'm having some troubles with ActiveX control events. Here is a brief description of my app architecture: There is an inproc COM server which contains STA ActiveX control (aka control) and MTA COM object (aka object). Here is the IDL definition of the control and object interfaces: [ object, uuid(2338CCAF-BBAF-4E29-929B-A67285B1E772), dual, nonextensible, pointer_default(unique) ] interface IObject : IDispatch{ [id(1)] HRESULT DoWork(void); }; [ object, uuid(1A0A1DA2-E33B-4DF4-99A9-9EAEF2281E7D), dual, nonextensible, pointer_default(unique) ] interface IControl : IDispatch{ }; [ uuid(BC27FABD-2794-4F9C-B3BD-C0C0628741FA), version(1.0), helpstring("AVRep 1.0 Type Library") ] library ActiveXLib { importlib("stdole2.tlb"); [ uuid(4B5575A7-E0FF-49B5-AE10-0D980CF49EB3) ] dispinterface _IControlEvents { properties: methods: [id(1)] HRESULT SomeEvent([in] IObject* obj); }; [ uuid(7C44F19E-6B71-434B-96F6-E29A3C66C794), control ] coclass Control { [default] interface IControl; [default, source] dispinterface _IControlEvents; }; [ uuid(17BDFAC0-DF21-4474-BCFF-846FE0075D68) ] coclass Object { [default] interface IObject; }; }; Client is a Delphi application with ActiveX control on the form which creates MTA object and calls its DoWork method var mta : IObject; begin mta := CreateOleObject('ActiveXLib.Object.1') as IObject; mta.DoWork(); end; This method directly calls Fire_SomeEvent method of ActiveX control coclass and passes 'this' as a parameter (pointer to IObject interface). Delphi code successfully receives event but when it tries to access any IObject method or property (not shown in idl for simplicity) then access violation occured in oleaut32.dll. One important note - I use ATLCPImplMT class to implement event firing from different threads (see http://support.microsoft.com/kb/280512 for details). This implementation allows to switch apartments when event fires (from MTA apartment of the object to STA Delphi forms apartment). I suggest that this problem is related to incorrect event parameter marshaling because when standard ATLCPImpl class is used all works fine. Are there any restrictions for cross-apartment events? Maybe some special Delphi environment setup is required to work with activex objects correctly... A: Are you accessing objects that were created in the same thread as the event handler or were the COM object created in the main thread? If you are not in the same thread context in the eventhandler as the thread that created the object, you may get access violations when you try accessing the COM object. A quick fix workaround can be to post a message to the main thread from the event handler, and have the main thread access the COM object in the main thread context, instead of directly in the COM event handler. Threads and COM is not less complicated that threads without COM.
{ "language": "en", "url": "https://stackoverflow.com/questions/170038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How would you simply Monitor.TryEnter I'm trying to make things simpler. Here is my code: If Threading.Monitor.TryEnter(syncRoot) Then Try 'do something Finally Threading.Monitor.Exit(syncRoot) End Try Else 'do something else End If This is even worse than the ReaderWriterLock in terms of noise. I can use C# or VB, so answers applying to either will be welcome. A: Use a delegate? E.g. public bool TryEnter(object lockObject, Action work) { if (Monitor.TryEnter(lockObject)) { try { work(); } finally { Monitor.Exit(lockObject); } return true; } return false; } A: This is very similar to your last post, and I would expect a similar answer. The only significant difference is that you might return "null" from your method if the timeout fails - then the "Dispose()" is not called, and you can easily check the value: using(var token = GetLock(syncLock, timeout)) { if(token != null) { ... } } The only real glitch is that you don't necessarily want to add an extension method to "object" (or even "T where T : class")... Jon Skeet has looked at this in the past - worth a look.
{ "language": "en", "url": "https://stackoverflow.com/questions/170051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to group RadioButtons generated from the ItemTemplate of an ItemsControl <DataTemplate x:Key="Genre_DataTemplate"> <RadioButton GroupName="One" Content="{Binding... </DataTemplate> Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree. Any solution or workaround to group them together?. GroupName property also doesn't have any effect here. [Update] I am trying this in Silverlight A: The problem is that the RadioButton.GroupName behavior depends on the logical tree to find a common ancestor and effectively scope it's use to that part of the tree, but silverlight's ItemsControl doesn't maintain the logical tree. This means, in your example, the RadioButton's Parent property is always null I built a simple attached behavior to fix this. It is available here: http://www.dragonshed.org/blog/2009/03/08/radiobuttons-in-a-datatemplate-in-silverlight/ A: I think the problem is somewhere else in the control tree. Can you post more details? Here is a sample xaml code that works as expected: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <Grid.Resources> <XmlDataProvider x:Key="flickrdata" Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&amp;lang=en-us&amp;format=rss_200"> <XmlDataProvider.XmlNamespaceManager> <XmlNamespaceMappingCollection> <XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/"/> </XmlNamespaceMappingCollection> </XmlDataProvider.XmlNamespaceManager> </XmlDataProvider> <DataTemplate x:Key="itemTemplate"> <RadioButton GroupName="One"> <Image Width="75" Height="75" Source="{Binding Mode=OneWay, XPath=media:thumbnail/@url}"/> </RadioButton> </DataTemplate> <ControlTemplate x:Key="controlTemplate" TargetType="{x:Type ItemsControl}"> <WrapPanel IsItemsHost="True" Orientation="Horizontal"/> </ControlTemplate> </Grid.Resources> <ItemsControl Width="375" ItemsSource="{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}" ItemTemplate="{StaticResource itemTemplate}" Template="{StaticResource controlTemplate}"> </ItemsControl> </Grid> </Page> P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)
{ "language": "en", "url": "https://stackoverflow.com/questions/170061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What utilities can provide database hits/duration per page? SQL Server profiler is great for profiling SQL Server performance for web apps. However, when I'm testing my webapp I'd like a summary of database hits/duration per page. Does anybody know of any utilities for giving you this kind of information? A: If you want duration per page, I'd recommand Google Analytics. If you want a summary of database hits (ie, you run three procedures during one page load so you want to show a count of three) then I would recommend adding auditing code to your sprocs. Alternately (though more expensively in terms of processing) you could turn on either SQL Profiler or SQL Trace and then track the database hits that way to perform statistical analysis on them. A: I would recommend setting a data access routine that will be used for all the site. This routine/class/or whatever you like could log in the database or in a log all the "hits", their duration, error (is any), timeout, etc. If you program it properly, you will be able to know how many DB hit / page load, avg(DBHit) + you will get as a free bonus the "longest SProc, shortest, more often called". The positive side of this is that you don't need to modify any stored proc and you can have a nice little "wrapper" around your access to the DB. For the "Duration per page", if you go with google analysis you will not be able to merge the information back with what you got on the database server. So I would recommend logging each access to a page in the DB. Then you can infer that Page1.StartTime = getdate(), Page1.EndTime = (page2.Starttime-1 or session.log_off_time) for example. [This is a little basic but according to your environment you can improve it].
{ "language": "en", "url": "https://stackoverflow.com/questions/170064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the differences between using the New keyword and calling CreateObject in Excel VBA? What criteria should I use to decide whether I write VBA code like this: Set xmlDocument = New MSXML2.DOMDocument or like this: Set xmlDocument = CreateObject("MSXML2.DOMDocument") ? A: You should always use Set xmlDocument = CreateObject("MSXML2.DOMDocument") This is irrelevant to the binding issue. Only the declaration determines the binding. Using CreateObject exclusively will make it easier to switch between early and late binding, since you only have to change the declaration line. In other words, if you write this: Dim xmlDocument As MSXML2.DOMDocument Set xmlDocument = CreateObject("MSXML2.DOMDocument") Then, to switch to late binding, you only have to change the first line (to As Object). If you write it like this: Dim xmlDocument As MSXML2.DOMDocument Set xmlDocument = New MSXML2.DOMDocument then when you switch to late binding, you have to change both lines. A: For the former you need to have a reference to the type library in your application. It will typically use early binding (assuming you declare your variable as MSXML2.DOMDocument rather than as Object, which you probably will), so will generally be faster and will give you intellisense support. The latter can be used to create an instance of an object using its ProgId without needing the type library. Typically you will be using late binding. Normally it's better to use "As New" if you have a type library, and benefit from early binding. A: As long as the variable is not typed as object Dim xmlDocument as MSXML2.DOMDocument Set xmlDocument = CreateObject("MSXML2.DOMDocument") is the same as Dim xmlDocument as MSXML2.DOMDocument Set xmlDocument = New MSXML2.DOMDocument both use early binding. Whereas Dim xmlDocument as Object Set xmlDocument = CreateObject("MSXML2.DOMDocument") uses late binding. See MSDN here. When you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function. New requires that a type library is referenced. Whereas CreateObject uses the registry. CreateObject can be used to create an object on a remote machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/170070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: SQL Server 2005 Setting a variable to the result of a select query How do I set a variable to the result of select query without using a stored procedure? I want to do something like: OOdate DATETIME SET OOdate = Select OO.Date FROM OLAP.OutageHours as OO WHERE OO.OutageID = 1 Then I want to use OOdate in this query: SELECT COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO INNER join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE CONVERT(VARCHAR(10),OO.Date,126) = CONVERT(VARCHAR(10),FF.FaultDate,126)) AND OFIO.OutageID = 1 A: You can use something like SET @cnt = (SELECT COUNT(*) FROM User) or SELECT @cnt = (COUNT(*) FROM User) For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis. Edit: Have you tried something like this? DECLARE @OOdate DATETIME SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1 Select COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO inner join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE @OODate = FF.FaultDate AND OFIO.OutageID = 1 A: You could use: declare @foo as nvarchar(25) select @foo = 'bar' select @foo A: You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this. Incidentally, since you are using a predicate like this: CONVERT(...) = CONVERT(...) that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function. Here is one way to make the original query somewhat better: DECLARE @ooDate datetime SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1 SELECT COUNT(FF.HALID) FROM Outages.FaultsInOutages AS OFIO INNER JOIN Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE FF.FaultDate >= @ooDate AND FF.FaultDate < DATEADD(day, 1, @ooDate) AND OFIO.OutageID = 1 This version could leverage in index that involved FaultDate, and achieves the same goal. Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT. SELECT COUNT(FF.HALID) FROM Outages.FaultsInOutages AS OFIO INNER JOIN Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND OFIO.OutageID = 1 Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration. Regards. A: This will work for original question asked: DECLARE @Result INT; SELECT @Result = COUNT(*) FROM TableName WHERE Condition A: -- Sql Server 2005 Management studio use Master go DECLARE @MyVar bigint SET @myvar = (SELECT count(*) FROM spt_values); SELECT @myvar Result: 2346 (in my db) -- Note: @myvar = @Myvar A: What do you mean exactly? Do you want to reuse the result of your query for an other query? In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)
{ "language": "en", "url": "https://stackoverflow.com/questions/170078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }