Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've recently come across this piece of JavaScript code: ``` if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1) ``` I was intrigued, because to write this test I would have done: ``` if (/(>=|<=|<>)/.test(sCompOp)) ``` Is this just a stylistic difference, or does the author of the other code know something about ...
I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... *except* when `sCompOp` could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long `sCompOp` gets, whil...
I doubt it is a question of performance or optimization. I would suspect the author of that code was simply not comfortable or familiar with regular expressions. Also notice how the comma-separated string isn't split apart in order to leverage object properties - possibly also a case of lack of familiarity with the lan...
JavaScript style/optimization: String.indexOf() v. Regex.test()
[ "", "javascript", "regex", "optimization", "coding-style", "" ]
One of the things that always bugs me about using Readers and Streams in Java is that the `close()` method can throw an exception. Since it's a good idea to put the close method in a finally block, that necessitates a bit of an awkward situation. I usually use this construction: ``` FileReader fr = new FileReader("Som...
I would always go for the first example. If close were to throw an exception (in practice that will never happen for a FileReader), wouldn't the standard way of handling that be to throw an exception appropriate to the caller? The close exception almost certainly trumps any problem you had using the resource. The seco...
I'm afraid there's a big problem with the first example, which is that if an exception happens on or after the read, the `finally` block executes. So far so good. But what if the `fr.close()` then causes another exception to be thrown? This will "trump" the first exception (a bit like putting `return` in a `finally` bl...
Is there a preference for nested try/catch blocks?
[ "", "java", "try-catch", "" ]
When developing distributed applications, all written in Java by the same company, would you choose Web Services or RMI? What are the pros and cons in terms of performance, loose coupling, ease of use, ...? Would anyone choose WS? Can you build a service-oriented architecture with RMI?
I'd try to think about it this way: Are you going for independent services running beneath each other, and those services may be accessed by non-java applications some time in the future? Then go for web services. Do you just want to spread parts of an application (mind the singular) over several servers? Then go for...
I would choose WS. * It is unlikely that WS/RMI will be your bottleneck. * Why to close the door for other possible technologies in the future? * RMI might have problem if version of classes on client/server get out of sync. And... I would most likely choose REST services.
What are the pros and cons of Web Services and RMI in a Java-only environment?
[ "", "java", "web-services", "remoting", "rmi", "" ]
Many times, a Java app needs to connect to the Internet. The most common example happens when it is reading an XML file and needs to download its schema. I am behind a proxy server. How can I set my JVM to use the proxy ?
From the Java documentation (*not* the javadoc API): <http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html> Set the JVM flags `http.proxyHost` and `http.proxyPort` when starting your JVM on the command line. This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the ex...
To use the system proxy setup: ``` java -Djava.net.useSystemProxies=true ... ``` Or programatically: ``` System.setProperty("java.net.useSystemProxies", "true"); ``` Source: <http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html>
How do I set the proxy to be used by the JVM
[ "", "java", "proxy", "jvm", "" ]
I am going through John Resig's excellent [Advanced javascript tutorial](http://ejohn.org/apps/learn/#47) and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice in...
Not quite. Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2): ``` >>> String.substring.call("foo", 1) "1" >>> String().substring.call("foo", 1) "oo" ``` Array.slice is *neither* properly referencing the slice function attached to the Array prototype nor the slice...
Array is just a function, albeit a special one (used to initialize arrays). Array.slice is a reference to the slice() function in the Array prototype. It can only be called on an array object and not on the Constructor (i.e. Array) itself. Array seems to behave specially though, as Array() returns an empty array. This ...
Difference between Array.slice and Array().slice
[ "", "javascript", "arrays", "" ]
So, I have a nice domain model built. Repositories handle the data access and what not. A new requirements has popped up that indicates that reasons need to be logged with deletes. Up until now, deletes have been fairly simple => Entity.Children.Remove(child). No internal change tracking was happening as my ORM tool wa...
Ok, this sounds crazy and I'm going to take another shot at this -- even though I might be spanked for bad nHibernate usage. Before you delete, why don't you select the children that are going to be deleted (you already have their ids correct?) and do a transformation into whatever entity your going to be using to log ...
If deletes are relatively rare for that particular entity type, I would add a flag to the entity to mark it as logically "deleted" rather than actually deleting the row. The application would then have to handle the hiding of these entities under normal circumstances. If this would cause an unacceptable number of "sta...
Domain Driven Design - Logical Deletes
[ "", "c#", ".net", "nhibernate", "domain-driven-design", "ddd-repositories", "" ]
Suppose I have a LimitedValue class which holds a value, and is parameterized on int types 'min' and 'max'. You'd use it as a container for holding values which can only be in a certain range. You could use it such: ``` LimitedValue< float, 0, 360 > someAngle( 45.0 ); someTrigFunction( someAngle ); ``` so that 'someT...
You can do this using templates -- try something like this: ``` template< typename T, int min, int max >class LimitedValue { template< int min2, int max2 >LimitedValue( const LimitedValue< T, min2, max2 > &other ) { static_assert( min <= min2, "Parameter minimum must be >= this minimum" ); static_assert( m...
OK, this is C++11 with no Boost dependencies. Everything guaranteed by the type system is checked at compile time, and anything else throws an exception. I've added `unsafe_bounded_cast` for conversions that *may* throw, and `safe_bounded_cast` for explicit conversions that are statically correct (this is redundant s...
Limiting range of value types in C++
[ "", "c++", "templates", "" ]
I have little knowledge of Flash but for a little Flash game I have to store score and successful tries of users in a database using PHP. Now the Flash runs locally on the users computer and connects to a remote server. How can I secure against manipulation of game scores. Is there any best practice for this use case?
You might want to check these other questions: * Q46415 [Passing untampered data from Flash app to server?](https://stackoverflow.com/questions/46415/) * Q73947 [What is the best way to stop people hacking the PHP-based highscore table of a Flash game.](https://stackoverflow.com/questions/73947/) * Q25999 [Secure Onli...
What you are asking is inherently impossible. The game runs on the client and is therefore completely at the user's mercy. Only way to be sure is running a real time simulation of the game on the server based on user's input (mouse movement, keypresses), which is absolutely ridiculous.
Secure communication between Flash and PHP script
[ "", "php", "flash", "security", "" ]
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present. **So something like:** *dr.ToString.Substring(1, dr.ToString.Length);* But more conditionally in case the dollar si...
``` Convert.ToString(dr(columnName)).Replace("$", String.Empty) ``` -- If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will onl...
You could also use ``` string trimmed = (dr as string).Trim('$'); ``` or ``` string trimmed = (dr as string).TrimStart('$'); ```
Simple way to trim Dollar Sign if present in C#
[ "", "c#", "" ]
I have a class that defines the names of various session attributes, e.g. ``` class Constants { public static final String ATTR_CURRENT_USER = "current.user"; } ``` I would like to use these constants within a JSP to test for the presence of these attributes, something like: ``` <%@ taglib prefix="c" uri="http:/...
It's not working in your example because the `ATTR_CURRENT_USER` constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the [unstandard tag library](http://jakarta.apache.org/taglibs/sandbox/doc...
You can define Constants.ATTR\_CURRENT\_USER as a variable with c:set,just as below: ``` <c:set var="ATTR_CURRENT_USER" value="<%=Constants.ATTR_CURRENT_USER%>" /> <c:if test="${sessionScope[ATTR_CURRENT_USER] eq null}"> <%-- Do somthing --%> </c:if> ```
accessing constants in JSP (without scriptlet)
[ "", "java", "jsp", "session", "jstl", "" ]
I am trying to uncompress some data created in VB6 using the zlib API. I have read this is possible with the qUncompress function: <http://doc.trolltech.com/4.4/qbytearray.html#qUncompress> I have read the data in from QDataStream via readRawBytes into a char array, which I then converted to a QByteArray for decompre...
I haven't used VB6 in *ages*, so I hope this is approximately correct. I *think* that vb6 used () for array indexing. If I got anything wrong, please let me know. Looking at the qUncompress docs, you should have put your data in your QByteArray starting at byte 5 (I'm going to assume that you left the array index base...
This is how I can convert arbitary data from one format to another. ``` Private Type LongByte H1 As Byte H2 As Byte L1 As Byte L2 As Byte End Type Private Type LongType L As Long End Type Function SwapEndian(ByVal LongData as Long) as Long Dim TempL As LongType Dim TempLB As LongByte Dim Te...
How to convert a number to a bytearray in bit endian order
[ "", "c++", "qt", "vb6", "compression", "endianness", "" ]
I wrote some code with a lot of recursion, that takes quite a bit of time to complete. Whenever I "pause" the run to look at what's going on I get: > > Cannot evaluate expression because the code of the current method is optimized. I think I understand what that means. However, what puzzles me is that after I hit ste...
The Debugger uses FuncEval to allow you to "look at" variables. FuncEval requires threads to be stopped in managed code at a GarbageCollector safe point. Manually "pausing" the run in the IDE causes all threads to stop as soon as possible. Your highly recursive code will tend to stop at an unsafe point. Hence, the debu...
While the Debug.Break() line is on top of the callstack you can't eval expressions. That's because that line is optimized. Press F10 to move to the next line - a valid line of code - and the watch will work.
What does "Cannot evaluate expression because the code of the current method is optimized." mean?
[ "", "c#", ".net", "debugging", "optimization", "compiler-construction", "" ]
I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge. I want some help working out how to create an iterator for a class I have created. I have a class 'Shape' which has a container of Points. I have a class 'Piece' which...
You should use Boost.Iterators. It contains a number of templates and concepts to implement new iterators and adapters for existing iterators. I have written [an article about this very topic](http://accu.org/index.php/journals/1527); it's in the December 2008 ACCU magazine. It discusses an (IMO) elegant solution for e...
/EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I'm letting the code below stand because it can be useful in similar circumstances. --- Is an own iterator actually necessary here? Perhaps it's sufficient to forward all required definitions to the container holding the a...
Creating my own Iterators
[ "", "c++", "iterator", "" ]
What are [metaclasses](https://docs.python.org/3/reference/datamodel.html#metaclasses)? What are they used for?
A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass. While in Python you can use arbitrary callables for metaclasses (like [Jerub](https://stackoverflow.com/questions/100003/what-...
# Classes as objects Prior to delving into metaclasses, a solid grasp of Python classes is beneficial. Python holds a particularly distinctive concept of classes, a notion it adopts from the Smalltalk language. In most languages, classes are just pieces of code that describe how to produce an object. That is somewhat...
What are metaclasses in Python?
[ "", "python", "oop", "metaclass", "python-class", "python-datamodel", "" ]
Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App\_Data folder (an .mdf "database"). Seems easy, and it is once you know how.
So here's the answer from MSDN: > Choos[e] "Add New Data Source" from the > Data menu.[And follow the connection wizard] Very easy, except that I have no Data menu. If you don't have a Data menu, do the following: * Click on Tools >> Connect to Database... * Select "Microsoft SQL Server Database File", take the defa...
A great resource I always keep around is [connectionstrings.com](http://connectionstrings.com). It's really handy for finding these connection strings when you can't find an example. Particularly [this page](http://connectionstrings.com/?carrier=sqlserver2005) applied to your problem **Attach a database file on conne...
How do I connect to an .mdf (Microsoft SQL Server Database File) in a simple web project?
[ "", "c#", "asp.net", "database", "visual-studio-2008", "" ]
Which type of input is least vulnerable to Cross-Site Scripting (XSS) and SQL Injection attacks. PHP, HTML, BBCode, etc. I need to know for a forum I'm helping a friend set up.
We need to know more about your situation. Vulnerable how? Some things you should always do: * Escape strings before storing them in a database to guard against SQL injections * HTML encode strings when printing them back to the user from an unknown source, to prevent malicious html/javascript I would never execute p...
*(I just posted this in a comment, but it seems a few people are under the impression that select lists, radio buttons, etc don't need to be sanitized.)* Don't count on radio buttons being secure. You should still sanitize the data on the server. People could create an html page on their local machine, and make a text...
Which Type of Input is Least Vulnerable to Attack?
[ "", "php", "html", "forum", "bbcode", "security", "" ]
What are the C++ rules for calling the base class constructor from a derived class? For example, I know in Java, you must do it as the first line of the subclass constructor (and if you don't, an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).
Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by na...
In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this: ``` class Sub : public Base { Sub(int x, int y) : Base(x...
What are the rules for calling the base class constructor?
[ "", "c++", "inheritance", "constructor", "" ]
What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have `\/:*?"<>|` characters). I'd like to use it like the following: ``` // Return true if string is invalid. if (Regex.IsMatch(szFileName, "<your regex string>")) { // Tell user to reformat the...
As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions: ``` if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1) { MessageBox.Show("The filename is invalid"); return; } ```
This isn't as simple as just checking whether the file name contains any of [System.IO.Path.GetInvalidFileNameChars](http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx) (as mentioned in a couple of other answers already). For example what if somebody enters a name that contains no inva...
Regular expressions in C# for file name validation
[ "", "c#", "regex", "" ]
I have PHP configured so that magic quotes are on and register globals are off. I do my best to always call htmlentities() for anything I am outputing that is derived from user input. I also occasionally seach my database for common things used in xss attached such as... ``` <script ``` What else should I be doing ...
Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use `|escape:'htmlall'` modifier to convert all sensitive characters to HTML entities (I use own `|e` modifier which is alias to the above). My approach to input/output secur...
I'm of the opinion that one shouldn't escape anything during input, only on output. Since (most of the time) you can not assume that you know where that data is going. Example, if you have form that takes data that later on appears in an email that you send out, you need different escaping (otherwise a malicious user c...
What are the best practices for avoiding xss attacks in a PHP site
[ "", "php", "security", "xss", "" ]
We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS. The current target that checks the original JAR file into VSS discovers th...
I would suggest to work with [macros](http://ant.apache.org/manual/Tasks/macrodef.html) over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties). You simply refactor your Ant scr...
It is generally considered a bad idea to version control your binaries and I do not recommend doing so. But if you absolutely have to, you can use antcall combined with param to pass parameters and call a target. ``` <antcall target="reusable"> <param name="some.variable" value="var1"/> </antcall> <target name="r...
Is there a way to generalize an Apache ANT target?
[ "", "java", "build-process", "build-automation", "ant", "" ]
We are using [JetBrains](http://en.wikipedia.org/wiki/JetBrains)' [dotTrace](http://en.wikipedia.org/wiki/DotTrace). What other profiling tools can be recommended that are better for profiling C# [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) applications?
No. I have tried pretty much every .NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application. If and only ...
I have used the [EQATEC Profiler](http://eqatec.com/Profiler/Home.aspx). It is free and is a code profiler, not a memory profiler.
Best .NET memory and performance profiler?
[ "", "c#", ".net", "profiling", "profiler", "" ]
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 extensio...
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](http://www.springframework.org/osgi).
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 ...
Extending Java Web Applications with plugins
[ "", "java", "tomcat", "servlets", "modularity", "" ]
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 ...
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.
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 procedu...
Simple way to programmatically get all stored procedures
[ "", "c#", "sql-server", "sql-server-2005", "stored-procedures", "" ]
I want to use a timer in my simple [.NET](http://en.wikipedia.org/wiki/.NET_Framework) 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...
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...
I would recommend the [`Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) class in the [`System.Timers`](http://msdn.microsoft.com/en-us/library/system.timers.aspx) namespace. Also of interest, the [`Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) class in the [`Syst...
Is there a timer class in C# that isn't in the Windows.Forms namespace?
[ "", "c#", ".net", "scheduling", "timer", "" ]
I'm trying to get a case-insensitive search with two strings in JavaScript working. Normally it would be like this: ``` var string="Stackoverflow is the BEST"; var result= string.search(/best/i); alert(result); ``` The `/i` flag would be for case-insensitive. But I need to search for a second string; without the fl...
Yeah, use `.match`, rather than `.search`. The result from the `.match` call will return the actual string that was matched itself, but it can still be used as a boolean value. ``` var string = "Stackoverflow is the BEST"; var result = string.match(/best/i); // result == 'BEST'; if (result){ alert('Matched'); } `...
Replace ``` var result= string.search(/searchstring/i); ``` with ``` var result= string.search(new RegExp(searchstring, "i")); ```
Case-insensitive search
[ "", "javascript", "search", "string-comparison", "case-insensitive", "" ]
I am setting up a test version of my website against a new schema. I am trying to connect using the proxy connection and am getting the following error: > ORA-28150: proxy not authorized to connect as client my connect string has the following form: > Data Source=*Instance*; User Id=*user*; Proxy User Id=*prxy\_usr*...
According to [the docs](http://download.oracle.com/docs/cd/B28359_01/server.111/b28278/e24280.htm#ORA-28150): Grant the proxy user permission to perform actions on behalf of the client by using the ALTER USER ... GRANT CONNECT command.
EddieAwad's answer was correct but here is the specific code to run: > ALTER USER *username* GRANT CONNECT THROUGH *proxyUserName*; The THROUGH keyword is the part I couldn't find in the documentation.
.NET unable to connect to Oracle DB using Oracle proxy user
[ "", "c#", "oracle", "odp.net", "" ]
Consider a normal customer-orders application based on MVC pattern using WinForms. The view part has grown too much (over 4000 files) and it needs to be split into smaller ones. --- For this example we are going to use 3 projects for the view part: * **Main** - has dependencies to the other 2 projects. Instantiates ...
Change at least one of the types to an interface. For example have a ICustomer interface and a Customer type that implements this interface. Now add the ICustomer to the orders project and from the customers project set a reference to the Orders project so you can implement the interface. The Order type can now work a...
If they are that tightly coupled maybe they should not be split.
Cyclic Dependencies
[ "", "c#", "asp.net-mvc", "dependencies", "" ]
I have a WinForms app written in C# with .NET 3.5. It runs a lengthy batch process. I want the app to update status of what the batch process is doing. What is the best way to update the UI?
The BackgroundWorker sounds like the object you want.
The quick and dirty way is using `Application.DoEvents()` But this can cause problems with the order events are handled. So it's not recommended The problem is probably not that you have to yield to the ui thread but that you do the processing on the ui thread blocking it from handling messages. You can use the backgr...
How do I Yield to the UI thread to update the UI while doing batch processing in a WinForm app?
[ "", "c#", ".net", "winforms", "" ]
How can I *programmatically* determine if I have access to a server (TCP) with a given IP address and port using C#?
Assuming you mean through a TCP socket: ``` IPAddress IP; if(IPAddress.TryParse("127.0.0.1",out IP)){ Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try{ s.Connect(IPs[0], port); } catch(Exception ex){ // something went wrong } } ...
Declare string address and int port and you are ready to connect through the TcpClient class. ``` System.Net.Sockets.TcpClient client = new TcpClient(); try { client.Connect(address, port); Console.WriteLine("Connection open, host active"); } catch (SocketException ex) { Console.WriteLine("Connection could...
How can I test a TCP connection to a server with C# given the server's IP address and port?
[ "", "c#", "networking", "" ]
How do I programmatically force an onchange event on an input? I've tried something like this: ``` var code = ele.getAttribute('onchange'); eval(code); ``` But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.
Create an `Event` object and pass it to the `dispatchEvent` method of the element: ``` var element = document.getElementById('just_an_example'); var event = new Event('change'); element.dispatchEvent(event); ``` This will trigger event listeners regardless of whether they were registered by calling the `addEventListe...
In jQuery I mostly use: ``` $("#element").trigger("change"); ```
How do I programmatically force an onchange event on an input?
[ "", "javascript", "" ]
How can I convert a JavaScript string value to be in all lowercase letters? Example: `"Your Name"` to `"your name"`
``` const lowerCaseName = "Your Name".toLowerCase(); // your name ```
Use either [toLowerCase](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLowerCase) or [toLocaleLowerCase](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/toLocaleLowerCase) methods of the [String](http://developer.mozilla.org/en/Core_JavaScript_...
Convert JavaScript String to be all lowercase
[ "", "javascript", "string", "" ]
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another ...
Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily: ``` from uuid import getnode as get_mac mac = get_mac() ``` The return value is the mac address as 48 bit integer.
The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in [this activestate recipe](http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/) ``` #!/usr/bin/pyth...
Getting MAC Address
[ "", "python", "windows", "linux", "networking", "" ]
I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me. Example input: > Is this thing on??? or what??? Desired output: > Is this thing on? or what? I'm u...
``` preg_replace('{\?+}', '?', 'Is this thing on??? or what???'); ``` That is, you only have to escape the question mark, the plus in "\?+" means that we're replacing every instance with one or more characters, though I suspect "\?{2,}" might be even better and more efficient (replacing every instance with two or more...
`preg_replace( '{\\?+}', '?', $text );` should do it. You need to escape the question mark itself with a backslash, and then escape the backslash itself with another backslash. It's situations like this where C#'s [verbatim strings](http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx) are nice.
PHP regex to remove multiple ?-marks
[ "", "php", "regex", "escaping", "" ]
I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In `MySQL` I would use `SHOW TABLES LIKE "Datasheet%"`, but in `T-SQL` this throws an error (it tries to look for a `SHOW` stored procedure and fails). Is this possible, and if so, how?
This will give you a list of the tables in the current database: ``` Select Table_name as "Table name" From Information_schema.Tables Where Table_type = 'BASE TABLE' and Objectproperty (Object_id(Table_name), 'IsMsShipped') = 0 ``` Some other useful T-SQL bits can be found here: <http://www.devx.com/tips/Tip/28529>
I know you've already accepted an answer, but why not just use the much simpler [sp\_tables](https://msdn.microsoft.com/en-us/library/ms186250.aspx)? ``` sp_tables 'Database_Name' ```
How can I do the equivalent of "SHOW TABLES" in T-SQL?
[ "", "sql", "t-sql", "sql-server-2005", "" ]
I want my WPF application to be skinnable, by applying a certain XAML template, and the changes to be application wide, even for dynamic controls or controls that aren't even in the visual/logical tree. What can I use to accomplish this type of functionality? Are there any good resources or tutorials that show how thi...
The basic approach to take is using resources all through your application and dynamically replacing the resources at runtime. See <http://www.nablasoft.com/alkampfer/index.php/2008/05/22/simple-skinnable-and-theme-management-in-wpf-user-interface/> for the basic approach
The replacing of resource will work but I found "structural skinning" to be more powerfull! Read more about it on CodeProject... <http://www.codeproject.com/KB/WPF/podder1.aspx>
What is the recommended way to skin an entire application in WPF?
[ "", "c#", ".net", "wpf", "templates", "skinning", "" ]
I see on Stack Overflow and [PEP 8](http://www.python.org/dev/peps/pep-0008/) that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought ...
The answer was given right there in the PEP [ed: this passage has been edited out in [2013](https://hg.python.org/peps/rev/fb24c80e9afb#l1.75)]. I quote: > The **most popular** way of indenting Python is with spaces only. What other underlying reason do you need? To put it less bluntly: Consider also the scope of th...
Well well, seems like everybody is strongly biased towards spaces. I use tabs exclusively. I know very well why. Tabs are actually a cool invention, that came **after** spaces. It allows you to indent without pushing space millions of times or using a fake tab (that produces spaces). I really don't get why everybody ...
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
[ "", "python", "indentation", "pep8", "" ]
When displaying the value of a decimal currently with `.ToString()`, it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places. Do I use a variation of `.ToString()` for this?
``` decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m ``` or ``` decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m ``` or ``` decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m ```
I know this is an old question, but I was surprised to see that no one seemed to post an answer that; 1. Didn't use bankers rounding 2. Keeps the value as a decimal. This is what I would use: ``` decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero); ``` <http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx>
How do I display a decimal value to 2 decimal places?
[ "", "c#", ".net", "format", "decimal", "" ]
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?
You can use the [zipfile](http://docs.python.org/dev/library/zipfile.html) module to compress the file using the zip standard, the [email](http://docs.python.org/dev/library/email.html) module to create the email with the attachment, and the [smtplib](http://docs.python.org/dev/library/smtplib.html) module to send it -...
Look at [zipfile](http://www.python.org/doc/2.5.2/lib/module-zipfile.html) for compressing a folder and it's subfolders. Look at [smtplib](http://www.python.org/doc/2.5.2/lib/module-smtplib.html) for an email client.
How can I compress a folder and email the compressed file in Python?
[ "", "python", "" ]
I have a .NET **2.0** WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide a...
This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff. This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function: ``` wi...
And for an easy way to inject that magic line of javascript, read [how to inject javascript into webbrowser control](https://stackoverflow.com/questions/153748/webbrowser-control-from-net-how-to-inject-javascript). Or just use this complete code: ``` private void InjectAlertBlocker() { HtmlElement head = webBrows...
Blocking dialogs in .NET WebBrowser control
[ "", "c#", ".net", "winforms", "activex", "mshtml", "" ]
What libraries and/or packages have you used to create blog posts with code blocks? Having a JavaScript library that would support line numbers and indentation is ideal.
The [GeSHi text highlighter](http://qbnz.com/highlighter/) is pretty awesome. If you're using WordPress, [there's a plugin](http://wordpress.org/extend/plugins/wp-syntax/) for you already
A simple Google query reveals <http://code.google.com/p/syntaxhighlighter/> From initial looks it seems pretty good. Entirly JS based so can be implemented independent of the server side language used.
Displaying code in blog posts
[ "", "javascript", "syntax-highlighting", "" ]
In the [Google C++ Style Guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml), the [section on Operator Overloading](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading) recommends against overloading *any* operators ("except in rare, special circumstances"). Specifical...
Except for the more fundamental types, the less-than operation isn't always trivial, and even equality may vary from situation to situation. Imagine the situation of an airline that wants to assign all passengers a boarding number. This number reflects the boarding order (of course). Now, what determines who comes bef...
Generally, defining `operator<` is better and simpler. The case where you would want to use functors is when you need multiple ways of comparing a particular type. For example: ``` class Person; struct CompareByHeight { bool operator()(const Person &a, const Person &b); }; struct CompareByWeight { bool oper...
Comparison Functor Types vs. operator<
[ "", "c++", "stl", "coding-style", "" ]
I see lots of job ads for C#/.NET programmers, so I thought it could be a good idea to have had a look at it. After looking at a few tutorials I found nothing really new to me. Just a language with a syntax somewhere between Java and C++ (arguably nicer than both though). So, what features in particular should I look...
Compared with Java: * The "using" statement (try/finally is rarely explicit in C#) (C# 1) * Delegates as a first class concept (C# 1) * Properties and events as first class concepts (C# 1) * User-defined value types (C# 1) * Operator overloading (use with care!) (C# 1) * Iterator blocks (C# 2) * Generics without type ...
The .Net Framework library is more important than the language.
C#/.NET, what to look at?
[ "", "c#", "" ]
Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work ``` DECLARE @MyBoolean bit; SET @MyBoolean = 0; SET @MyBoolean = NOT @MyBoolean; SELECT @MyBoolean; ``` Instead, I am getting more successful with ``` DECLARE @MyBoolean bit; SET @MyBoolean =...
Use the ~ operator: ``` DECLARE @MyBoolean bit SET @MyBoolean = 0 SET @MyBoolean = ~@MyBoolean SELECT @MyBoolean ```
Your solution is a good one... you can also use this syntax to toggle a bit in SQL... ``` DECLARE @MyBoolean bit; SET @MyBoolean = 0; SET @MyBoolean = @MyBoolean ^ 1; SELECT @MyBoolean; ```
Boolean 'NOT' in T-SQL not working on 'bit' datatype?
[ "", "sql", "sql-server", "t-sql", "boolean-operations", "" ]
I have a list string tag. I am trying to initialize a dictionary with the key as the tag string and values as the array index. ``` for i, ithTag in enumerate(tag): tagDict.update(ithTag=i) ``` The above returns me {'ithTag': 608} *608 is the 608th index* My problem is that while the i is being interpreted as a ...
You actually want to do this: ``` for i, tag in enumerate(tag): tagDict[tag] = i ``` The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.
If you want to be clever: ``` tagDict.update(map(reversed, enumerate(tag))) ``` Thanks to Brian for the update. This is apparently ~5% faster than the iterative version. (EDIT: Thanks saverio for pointing out my answer was incorrect (now fixed). Probably the most efficient/Pythonic way would be Torsten Marek's answe...
python dictionary update method
[ "", "python", "dictionary", "variables", "" ]
I'm trying to define a task that emits (using echo) a message when a target completes execution, regardless of whether that target was successful or not. Specifically, the target executes a task to run some unit tests, and I want to emit a message indicating where the results are available: ``` <target name="mytarget"...
The solution to your problem is to use the `failureProperty` in conjunction with the `haltOnFailure` property of the testng task like this: ``` <target name="mytarget"> <testng outputDir="${results}" failureProperty="tests.failed" haltOnFailure="false" ...> ... </testng> <echo>Tests complete. Results availa...
According to the [Ant docs](http://ant.apache.org/manual/Tasks/exec.html), there are two properties that control whether the build process is stopped or not if the testng task fails: > **haltonfailure** - Stop the build process > if a failure has occurred during the > test run. Defaults to false. > > **haltonskipped**...
Unconditionally execute a task in ant?
[ "", "java", "unit-testing", "ant", "" ]
It seems like most examples of JPA/Hibernate entity bean classes I've seen do no explicit synchronization. Yet, it is possible to call getters/setters on those objects in the context of building up a transaction. And it's possible for those methods to be called across multiple threads (although maybe that's unusual and...
The object probably is not the same for the 2 threads. Supposing your threads use a session factory to access the db, the objects you get from the session should be viewed as 'independent' (I believe hibernate creates 'fresh' objects for each get(), unless they are in the session). As for your stars question, it's the...
In my opinion you should NEVER share domains objects across threads. In fact I typically share very little between threads as such data must be protected. I have built some large/high performance systems and have never had to break this rule. If you need to parallelize work then do so but NOT by sharing instances of do...
What is the best practice for JPA/Hibernate entity classes and synchronization?
[ "", "java", "multithreading", "hibernate", "jpa", "" ]
Is there a way to get more useful information on validation error? XmlSchemaException provides the line number and position of the error which makes little sense to me. Xml document after all is not about its transient textual representation. I'd like to get an enumerated error (or an error code) specifying what when w...
You can accomplish this, sort of, by setting up an XmlReader whose XmlReaderSettings contain the schema and then using it to read through the input stream node by node. You can keep track of the last node read and have a pretty good idea of where you are in the document when a validation error happens. I think that if...
In my experience, you are lucky to get a line number and parse position.
Validating and reparing xml
[ "", "c#", "xml", "xsd", "" ]
I'm trying to create a ImageIcon from a animated gif stored in a jar file. ``` ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif"))); ``` The image loads, but only the first frame of the animated gif. The animation does not play. If I load the animated ...
This reads gif animation from inputStream ``` InputStream in = ...; Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in)); ```
You have to use getClass().getResource(imgName); to get a URL to the image file. Check out [this tutorial](http://www.rgagnon.com/javadetails/java-0240.html) from Real's HowTo. EDIT: Once the image is loaded you have to [set the ImageObserver property](http://java.sun.com/javase/6/docs/api/javax/swing/ImageIcon.html#s...
Loading animated gif from JAR file into ImageIcon
[ "", "java", "swing", "animated-gif", "javax.imageio", "" ]
I'm looking for a few talking points I could use to convince coworkers that it's NOT OK to run a 24/7 production application by simply opening Visual Studio and running the app in debug mode. What's different about running a compiled console application vs. running that same app in debug mode? Are there ever times wh...
You will suffer from reduced performance when running under the debugger (not to mention the complexity concerns [mentioned by Bruce](https://stackoverflow.com/questions/136674/reasons-to-not-run-a-business-critical-c-console-application-via-the-debugger#136699)), and there is nothing to keep you from getting the same ...
Just in itself there's no issue in running it in debugging if the performance is good enough. What strikes me as odd is that you are running business critical 24/7 applications as users, perhaps even on a workstation. If you want to ensure robustness and avaliability you should consider running this on dedicated hardwa...
Reasons to NOT run a business-critical C# console application via the debugger?
[ "", "c#", "debugging", "" ]
Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container? I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.
You can use poor-man's dependency injection: ``` public ProductController() : this( new Foo() ) { //the framework calls this } public ProductController(IFoo foo) { _foo = foo; } ```
One way is to create a ControllerFactory: ``` public class MyControllerFactory : DefaultControllerFactory { public override IController CreateController( RequestContext requestContext, string controllerName) { return [construct your controller here] ; } } ``` Then, in Global.asax.cs: ``` ...
Constructor parameters for controllers without a DI container for ASP.NET MVC
[ "", "c#", ".net", "asp.net-mvc", "" ]
I have a Hashtable<Integer, Sport> called sportMap and a list of sportIds (List<Integer> sportIds) from my backing bean. The Sport object has a List<String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport? ``` <h:dataTable value="#{bean.sportIds}" var="_sportId" >...
@[keith30xi.myopenid.com](https://stackoverflow.com/questions/136696/can-i-use-a-hashtable-in-a-unified-el-expression-on-a-cforeach-tag-using-jsf-12#137188) **Not TRUE in JSF 1.2**. According to the [java.net wiki faq](http://wiki.java.net/bin/view/Projects/JavaServerFacesSpecFaq#12coreTags) they should work together ...
I had the same problem once, and I couldn't find a solution using dataTable. The problem is that the var **\_sportId** can be read only by the dataTable component. If you need to do a loop inside a loop, you can use a dataTable inside a dataTable: ``` <h:dataTable value="#{bean.sportIds}" var="_sportId" > <h:dataT...
Can I use a Hashtable in a unified EL expression on a c:forEach tag using JSF 1.2 with JSP 2.1?
[ "", "java", "jsp", "jsf", "jstl", "" ]
I have a web part that I've developed, and if I manually install the web part it is fine. However when I have packaged the web part following the instructions on this web site as a guide: <http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html> I get this error in the log files: ``` 09/23/2008...
Figured it out. The error message is the one from the .webpart file: ``` <?xml version="1.0" encoding="utf-8"?> <webParts> <webPart xmlns="http://schemas.microsoft.com/WebPart/v3"> <metaData> <!-- The following Guid is used as a reference to the web part class, and it will be automatically re...
We had this same problem and found that the constructor of our web part was being called by the WebPartImporter and within the constructor we were doing SPSecurity.RunWithElevatedPrivileges. For some reason the WebPartImporter cannot handle this. So, we simply moved our code out of the constructor to OnInit (where it ...
SharePoint error: "Cannot import Web Part"
[ "", "c#", "sharepoint", "moss", "web-parts", "project-server", "" ]
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python: ``` if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do somethin...
Starting `Python 3.8`, and the introduction of [assignment expressions (PEP 572)](https://www.python.org/dev/peps/pep-0572/) (`:=` operator), we can now capture the condition value `re.search(pattern, text)` in a variable `match` in order to both check if it's not `None` and then re-use it within the body of the condit...
Using named groups and a dispatch table: ``` r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)') def do_foo(data): ... def do_bar(data): ... def do_baz(data): ... dispatch = { 'foo': do_foo, 'bar': do_bar, 'baz': do_baz, } m = r.match(var) if m: dispatch[m.group('cmd')](m.group('data'...
How do you translate this regular-expression idiom from Perl into Python?
[ "", "python", "regex", "perl", "" ]
I have a Java application that monitors a folder for incoming XML files. When a new file is detected I need to test the file that it is not currently being updated and is closed. My thought is to use [File.canWrite()](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#canWrite()) to test this. Is there any issue...
No, canWrite is not suitable for this purpose. In general the file will be writable even if another process is writing. You need a higher level protocol to coordinate the locking. If you plan to use this code on a single platform, you may be able to use [NIO's FileLock facility](http://java.sun.com/j2se/1.5.0/docs/api...
Additionally, if you do a check followed by a write, then you have a race condition. The state could change between the check and the write. Sometimes its best to try and do the thing you want and handle errors gracefully. perhaps an n-attempt retry mechanism with a increased fallback delay time. Or redefine your test...
Can the Java File method "canWrite()" support locking?
[ "", "java", "xml", "file-io", "" ]
I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++. Equivalent of this if you know Cocoa: ``` NSString *string = [NSString stringWithContentsOfFile:file]; ```
We can do it but it's a long line : ``` #include<fstream> #include<iostream> #include<iterator> #include<string> using namespace std; int main() { // The one-liner string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>()); // Check result cout << fileConte...
Its almost possible with an istream\_iterator (3 lines!) ``` #include <iostream> #include <fstream> #include <iterator> #include <string> #include <sstream> using namespace std; int main() { ifstream file("filename.txt"); string fileContents; copy(istreambuf_iterator<char>(file), istreambu...
Is there a one-liner to read in a file to a string in C++?
[ "", "c++", "file", "filesystems", "" ]
Does anyone know if there is a good equivalent to Java's `Set` collection in C#? I know that you can somewhat mimic a set using a `Dictionary` or a `HashTable` by populating but ignoring the values, but that's not a very elegant way.
Try [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx): > The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order... > > The capacity of a HashSet(Of T) object is the number of elements that...
If you're using .NET 3.5, you can use [`HashSet<T>`](http://msdn.microsoft.com/en-us/library/bb359438.aspx). It's true that .NET doesn't cater for sets as well as Java does though. The [Wintellect PowerCollections](https://github.com/timdetering/Wintellect.PowerCollections) may help too.
C# Set collection?
[ "", "c#", ".net", "collections", "set", "" ]
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available. The problem is that I have no idea about what have to be done on the server side. I can imagine that my application (developped in C++ using Qt) has to se...
I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail. I'd make a HTTP GET request to a certain page on your site containing the version of the local application. like ``` http://www.example.com/update?version=1.2.4 ``` Then you can return what ever you want,...
Pilif answer was good, and I have lots of experience with this too, but I'd like to add something more: Remember that if you start yourapp.exe, then the "updater" will try to overwrite yourapp.exe with the newest version. Depending upon your operating system and programming environment (you've mentioned C++/QT, I have...
Automatically checking for a new version of my application
[ "", "c++", "qt", "" ]
I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills. Here's what I've got, but it seems like there should be an easier way. ``` public static TEntity InsertIfNotExists<TEntity> ( DataContext db, Table<TEntity> tab...
``` public static void InsertIfNotExists<TEntity> (this Table<TEntity> table, TEntity entity, Expression<Func<TEntity,bool>> predicate) where TEntity : class { if (!table.Any(predicate)) { table.InsertOnSubmit(record); table.Con...
As others have pointed out, the `if (!Any()) { InsertOnSubmit(); }` solutions all have a race condition. If you go that route, when you call `SubmitChanges`, you have to take into account that either a) a `SqlException` could be raised for a duplicate insert, or b) you could have duplicate records in the table. Fortun...
LINQ to SQL insert-if-non-existent
[ "", "c#", "linq-to-sql", "" ]
Something like ``` var life= { users : { guys : function(){ this.SOMETHING.mameAndDestroy(this.girls); }, girls : function(){ this.SOMETHING.kiss(this.boys); }, }, mameAndDestroy : function(group){ }, kiss : function(group){ } }; ``` this.SOMETHING is what I i...
JavaScript does not offer this functionality natively. And I doubt you could even create this type of functionality. For example: ``` var Bobby = {name: "Bobby"}; var Dad = {name: "Dad", children: [ Bobby ]}; var Mom = {name: "Mom", children: [ Bobby ]}; ``` Who does Bobby belong to?
I simply added in first function ``` parentThis = this; ``` and use parentThis in subfunction. Why? Because in JavaScript, objects are soft. A new member can be added to a soft object by simple assignment (not like ie. Java where classical objects are hard. The only way to add a new member to a hard object is to crea...
Access parent's parent from javascript object
[ "", "javascript", "oop", "" ]
I want to resize the font of a SPAN element's style until it the SPAN's text is 7.5 inches wide when printed out on paper, but JavaScript only reports the SPAN's clientWidth property in pixels. ``` <span id="test">123456</span> ``` And then: ``` #test { font-size:1.2in; /* adjust this for yourself until printout m...
I think this does what you want. But I agree with the other posters, HTML isn't really suited for this sort of thing. Anyway, hope you find this useful. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtm...
To summarize: This is not a problem you can solve using HTML. Apart from the [CSS2 print properties](http://www.w3schools.com/css/css_ref_print.asp), there is no defined or expected way for browsers to print things. Firstly, [A pixel (in CSS) is not neccessarily the same size as a pixel (on your screen)](http://webki...
How do you convert pixels to printed inches in JavaScript?
[ "", "javascript", "css", "printing", "" ]
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?
**Static methods versus Instance methods** [Static and instance members](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#static-and-instance-members) of the C# Language Specification explains the difference. Generally, static methods can provide a very small performa...
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 y...
Method can be made static, but should it?
[ "", "c#", ".net", "refactoring", "resharper", "static-methods", "" ]
I search an implementation of a network (or distributed) file system like NFS in Java. The goal is to extend it and do some research stuff with it. On the web I found some implementation e.g. [DJ NFS](http://users.csc.calpoly.edu/~jbergami/projects/djnfs/), but the open question is how mature and fast they are. Can an...
Have a look at [dcache.org](http://www.dcache.org). They implement a NFSv4.1 server in Java. * [whitepaper](https://www.dcache.org/manuals/dcache-whitepaper-light.pdf) * [github](https://github.com/dCache/nfs4j) * [manual](https://www.dcache.org/manuals/book.shtml)
You may want to take a look at [Alfresco JLAN](http://www.alfresco.com/products/aifs/): > Alfresco JLAN uses a virtual file system interface that allows you to plug in your own file system implementation with the core server handling all of the network protocol exchange between the client and server. JLAN is also the ...
NFS Server in Java
[ "", "java", "filesystems", "" ]
Is it possible to make it appear to a system that a key was pressed, for example I need to make `A` key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python. A better way to put it, I need to ...
Install the [pywin32](https://github.com/mhammond/pywin32) extensions. Then you can do the following: ``` import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.AppActivate("Notepad") # select another application wsh.SendKeys("a") # send the keys you want ``` Search for documentation of the WScrip...
You could also use PyAutoGui to send a virtual key presses. Here's the documentation: <https://pyautogui.readthedocs.org/en/latest/> ``` import pyautogui pyautogui.press('Any key combination') ``` You can also send keys like the shift key or enter key with: ``` import pyautogui pyautogui.press('shift') ``` Pyau...
Key Presses in Python
[ "", "python", "keypress", "" ]
I'm starting with Python coming from java. I was wondering if there exists something similar to JavaDoc API where I can find the class, its methods and and example of how to use it. I've found very helpul to use *help( thing )* from the Python ( command line ) I have found this also: <http://docs.python.org/2/> <h...
[pydoc](http://docs.python.org/library/pydoc.html)? I'm not sure if you're looking for something more sophisticated, but it does the trick.
The standard python library is fairly well documented. Try jumping into python and importing a module say "os" and running: ``` import os help(os) ``` This reads the doc strings on each of the items in the module and displays it. This is exactly what pydoc will do too. EDIT: [epydoc](http://epydoc.sourceforge.net...
Python language API
[ "", "python", "reference", "documentation", "python-2.x", "" ]
In java, which regular expression can be used to replace these, for example: before: aaabbb after: ab before: 14442345 after: 142345 thanks!
In perl ``` s/(.)\1+/$1/g; ``` Does the trick, I assume if java has perl compatible regexps it should work too. Edit: Here is what it means ``` s { (.) # match any charater ( and capture it ) \1 # if it is followed by itself + # One or more times }{$1}gx; # And replace the whole things by the fi...
``` String a = "aaabbb"; String b = a.replaceAll("(.)\\1+", "$1"); System.out.println("'" + a + "' -> '" + b + "'"); ```
regular expression to replace two (or more) consecutive characters by only one?
[ "", "java", "regex", "" ]
I have a `SqlCommand` that I want to call `Prepare()` on whose `CommandType = Text` (it **cannot** be a stored procedure). In order to do this, I need to set the `Size` attribute on the parameters to be non-zero otherwise an exception is thrown. Are there any negative effects from setting the `Size` on all parameters ...
I think the only potential negative side effect of doing something like that would be the cost of memory allocation for the parameters. Since you're calling 'Prepare()' I'm guessing you're planning to use the SqlCommand multiple times against the same SqlConnection which suggests a discrete section of code where it's ...
This is the way the framework does it if you use the SqlParameter constructor that just takes a parameter name and a value. There might be a slight inefficiency on the client side, but I have never noticed a difference in query performance.
SqlParameter Size - negative effects of setting to max size?
[ "", "c#", "sql-server", "ado.net", "" ]
Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it? Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at wo...
I highly recommend to use [Costura.Fody](https://github.com/Fody/Costura) - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package. ``` Install-Package Costura.Fody ``` After adding it to the project, it will automatically embed all references that are copied to the outpu...
Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File… And include the code below to your App.xaml.cs or equivalent. ``` public App() { AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve); } System.R...
Embedding DLLs in a compiled executable
[ "", "c#", ".net", "dll", "merge", "linker", "" ]
I know how to use JSON to create objects, but there doesn't seem to be away to use JSON to create an object that is of a specific object type. Here's an example of an Object and creating an instance of it: ``` Person = function() { }; Person.prototype = { FirstName: null, GetFirstName: function() { re...
I don't imagine so. I'd create a function on the Person class to initialise from a JSON object if I were you. ``` function Person() { this.loadFromJSON = function(json) { this.FirstName = json.FirstName; }; } ``` If you didn't know what class the JSON object was representing beforehand, perhaps add an...
You could allow new Person() to accept an object to populate attributes with as a parameter. ``` var you = new Person({ firstName: 'Mike' }); ```
How to use JSON to create object that Inherits from Object Type?
[ "", "javascript", "json", "inheritance", "" ]
In order to help my team write testable code, I came up with this simple list of best practices for making our C# code base more testable. (Some of the points refer to limitations of Rhino Mocks, a mocking framework for C#, but the rules may apply more generally as well.) Does anyone have any best practices that they f...
Definitely a good list. Here are a few thoughts on it: > **Write the test first, then the code.** I agree, at a high level. But, I'd be more specific: "Write a test first, then write *just enough* code to pass the test, and repeat." Otherwise, I'd be afraid that my unit tests would look more like integration or accep...
If you are working with .Net 3.5, you may want to look into the [Moq](https://github.com/Moq/moq4) mocking library - it uses expression trees and lambdas to remove non-intuitive record-reply idiom of most other mocking libraries. Check out this [quickstart](https://github.com/Moq/moq4/wiki/Quickstart) to see how much ...
Best Practices of Test Driven Development Using C# and RhinoMocks
[ "", "c#", "unit-testing", "tdd", "rhino-mocks", "" ]
For a new Java web project I thought about using: * Eclipse as IDE * Mercurial for version control * Some kind of bug tracking software I have heard of bug tracking software where you can tie a change to an unresolved bug when you check it in. I haven't used any such solution myself, but it sounds good. Are there any...
In my experience the MercurialEclipse plug-in works quite well - as far as I understood, nobody commenting here has actually used it, so don't base your decisions solely on those opinions. You'd probably be better off to test it yourself. As I said before - it works for me. Disclaimer: I've participated in developing ...
Vectrace offers [Mercurial Eclipse](http://www.vectrace.com/mercurialeclipse/). But, it doesn't sound finished. For bug tracking, you may try [Trac](http://trac.edgewall.org/) with [TracMercurial](http://trac.edgewall.org/wiki/TracMercurial).
Eclipse as IDE + Mercurial for version control + ? Bug tracking = Good idea?
[ "", "java", "eclipse", "mercurial", "hudson", "bug-tracking", "" ]
I've created a language pack for a site before, but I'm not sure if what I'm doing is the best method. Basically, all I have is a file with variables defining string constants. Usually a set of arrays where an array usually refers to a particular elements of the site. Then the site code just includes the appropriate ...
I suggest using [Zend\_Translate](http://framework.zend.com/manual/en/zend.translate.html). It is somewhat a combination of the other suggestions people left here, only more maintainable and better designed. You can switch adapters depending on your preference (supports gettext, csv and a multitude of others), you don...
The best option you could have, with PHP, is [GetText](http://be.php.net/manual/en/book.gettext.php), but not all the server have it built-in, so it may be a show stopper if you're managing your server.
Best practices for creating various language-packs on a site? PHP
[ "", "php", "language-agnostic", "language-packs", "" ]
I have a C# interface with certain method parameters declared as `object` types. However, the actual type passed around can differ depending on the class implementing the interface: ``` public interface IMyInterface { void MyMethod(object arg); } public class MyClass1 : IMyInterface { public void MyMethod(obj...
I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no ne...
You will get the same benefits in Mono that you do in .NET. We strongly recommend that you use Mono 1.9 or Mono 2.0 RCx in general, as generics support only matured with 1.9.
Do generic interfaces in C# prevent boxing? (.NET vs Mono performance)
[ "", "c#", "performance", "generics", "mono", "boxing", "" ]
Is there any way (in Java Servlet) to determine whether a HTTP POST or GET request is a result from a submission from a HTML form or otherwise?
You could possibly do it with a hidden form field + a cookie. What you could do is set up a [nonce](http://en.wikipedia.org/wiki/Cryptographic_nonce), and have that as the hidden field of the form. You would then apply that to a cookie that is sent along with the form. The cookie should be linked to the hidden field, ...
I think it is impossible unless the client itself is co-operating (means the client set some header)
How to differentiate a HTTP Request submitted from a HTML form and a HTTP Request submitted from a client?
[ "", "java", "http", "" ]
I'm writing a website that will sell items from one of my classes. It will be linked to a SQL Server db where I will pull pricing, item name, quantity and description. If I wanted to display the items from the database in a thinkgeek fashion, what would be the best control to use so I can custimize the display to actua...
You'll get the best flexibility with an asp:Repeater. This means you'll have to program more, but it will give you more flexibility.
Not sure if you have any technology requirements, but the ASP.Net has a new type of ASP.NET project called the [Dynamic Data project](http://msdn.microsoft.com/en-us/library/cc488546.aspx). Using that project you can point to your SQL Server and generate pages to display and edit the data. Pretty easy to get up and run...
What is the best control to use to display items from a database?
[ "", "c#", "asp.net", "" ]
I have used the XML Parser before, and even though it worked OK, I wasn't happy with it in general, it felt like I was using workarounds for things that should be basic functionality. I recently saw SimpleXML but I haven't tried it yet. Is it any simpler? What advantages and disadvantages do both have? Any other parse...
I would have to say [SimpleXML](http://php.net/manual/simplexml.examples.php) takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like `$root->myElement`.
Have a look at PHP's [available XML extensions](http://php.net/manual/en/book.xml.php). The main difference between XML Parser and SimpleXML is that the latter is not a pull parser. SimpleXML is built on top of the DOM extensions and will load the entire XML file into memory. XML Parser like XMLReader will only load t...
Best XML Parser for PHP
[ "", "php", "xml", "parsing", "xml-parsing", "" ]
I frequently encounter some definitions for Win32API structures (but not limited to it) that have a `cbSize` member as in the following example. ``` typedef struct _TEST { int cbSize; // other members follow } TEST, *PTEST; ``` And then we use it like this: ``` TEST t = { sizeof(TEST) }; ... ``` or ``` TES...
> My initial guess is that this could > potentially be used for versioning. That's one reason. I think it's the more usual one. Another is for structures that have variable length data. I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that ...
It is used for versioning. A good example is the [GetVersionEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) call. You can pass in either an [OSVERSIONINFO](http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx) or [OSVERSIONINFOEX](http://msdn.microsoft.com/en-us/library/ms724833(VS.85).aspx). ...
What is the purpose of the cbSize member in Win32API structs
[ "", "c++", "winapi", "api", "" ]
I'm familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especially on a live site or web app. Is it something that can be overused and if so, what does overuse look like? Are there cases where it shouldn't be us...
One thing to add to what was said already is that it's paramount that you record any errors in your web application into a log. This way, as Jeff "Coding Horror" Atwood suggests, you'll know when your users are experiencing trouble with your app (instead of "asking them what's wrong"). To do this, I recommend the foll...
Roughly speaking, errors are a legacy in PHP, while exceptions are the modern way to treat errors. The simplest thing then, is to set up an error-handler, that throws an exception. That way all errors are converted to exceptions, and then you can simply deal with one error-handling scheme. The following code will conve...
Error handling in PHP
[ "", "php", "error-handling", "" ]
I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db. I've managed to get it working by using the [MySQL Connector/.NET](http://www.mysql.com/products/co...
The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services. What ...
While the "official" answer is to use WCF to push a service to Silverlight, I kind of figure that anyone using MySQL would probably not be using a complete ASP.NET solution. My solution was to build a PHP webservice (like Rob suggested) to interact with the MySQL database and have the Silverlight access it in a RESTful...
How to have silverlight get its data from MySQL
[ "", "c#", ".net", "mysql", "silverlight", "data-binding", "" ]
I'm investigating the following `java.lang.VerifyError`: ``` java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/...
`java.lang.VerifyError` can be the result when you have compiled against a different library than you are using at runtime. For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in `org.apache.*` namespace) were ...
`java.lang.VerifyError` are the worst. You would get this error if the bytecode size of your method exceeds the 64kb limit; but you would probably have noticed that. Are you 100% sure this class isn't present in the classpath elsewhere in your application, maybe in another jar? Also, from your stacktrace, is the cha...
Causes of getting a java.lang.VerifyError
[ "", "java", "exception", "deployment", "runtime-error", "verifyerror", "" ]
In a [related question](https://stackoverflow.com/questions/168408/c-alternatives-to-void-pointers-that-isnt-templates) 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 o...
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 ha...
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]; templat...
C++ template destructors for both primitive and complex data types
[ "", "c++", "templates", "" ]
I'm developing an application for an internal customer. One of the requirements is that it be developed in such a way that it could potentially be sold to other organizations. The application is a tracking application for a fund-raising organization that will manage their donations, donors, participants, and events. I ...
I want to caution you against trying to make the "do everything" framework. This is a common mistake that a lot of developers make when trying to build their first few mass-market software apps. You have a customer already, and they are likely bankrolling the initial version of the application. You need to deliver as ...
The most important thing is to design it in such a way that it is completely generic i.e. there is no client specific information hard coded or embedded. Anything client specific must be configurable through meta-data. How you do this is completely up to you, but the main ways are through XML, Database or properties f...
What are some common things to consider when developing a web-based application to be sold
[ "", "c#", "asp.net", "architecture", "web-applications", "product", "" ]
Given the following code (that doesn't work): ``` while True: # Snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok.lower() == "y": break 2 # This doesn't work :( if ok.lower() == "n": break # Do more processing with menus and stuff ``` Is there a w...
My first instinct would be to refactor the nested loop into a function and use `return` to break out.
Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want. ``` for a in xrange(10): for b in xrange(20): if something(a, b): # Break the inner loop... break else: # Continue if the inner lo...
How can I break out of multiple loops?
[ "", "python", "nested-loops", "break", "control-flow", "" ]
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having... ``` using namespace xyzzy ``` ...statements in them, which impact on my code when I least want or expect it. Is there a way I can somehow cancel/override a previous "using" statement to a...
Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this... ``` namespace codegear { #include "codegear_header.h" } // namespace codegear ``` ...then the effects of any using directives within that header are neutralized. That might be problematic in some...
No you can't *unuse* a namespace. The only thing you can do is putting the `using namespace`-statement a block to limit it's scope. Example: ``` { using namespace xyzzy; } // stop using namespace xyzzy here ``` Maybe you can change the template which is used of your auto-generated headers.
How can I "unuse" a namespace?
[ "", "c++", "namespaces", "c++builder", "" ]
i am looking for opinions if the following problem maybe has a better/different/common solution: --- I have a database for products which contains the names of the products in english (the default language of this application) and i need translations of the names if available. Currently i have this setup: A product...
Looks good to me. The one thing I might change is the way you handle languages: that should probably be a separate table. Thus, you would have: ``` CREATE TABLE products_l10n ( product_id serial NOT NULL, language_id int NOT NULL, "name" character varying(255) NOT NULL, CONSTRAINT products_l10n_pkey PRIMARY KE...
Looks good - similar to my preferred localization technique - what about wide characters (Japanese)? We always used nvarchar to handle that. What we actually found, however in our international purchasing operation, was that there was no consistency across international boundaries on products, since the suppliers in e...
Database localization
[ "", "sql", "database", "localization", "" ]
One of our unit tests is to populate properties within our business objects with random data. These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of: ``` public static T GetData<T>() ``` How would...
It depends on what data you want to randomize, because the *way* or the *algorithm* you want to use is totally different depending on the type. For example: ``` // Random int Random r = new Random(); return r.Next(); // Random Guid return Guid.NewGuid(); ... ``` So this obviously makes the use of generics a nice s...
You could keep the "easy to use" GetData interface you've got there, but internally have a Dictionary<Type, object> where each value is a Func<T> for the relevant type. GetData would then have an implementation such as: ``` public static T GetData<T>() { object factory; if (!factories.TryGet(typeof(T), out fac...
Get random data using Generics
[ "", "c#", "unit-testing", "generics", "" ]
I have a VB6 COM component which I need to call from my .Net method. I use reflection to create an instance of the COM object and activate it in the following manner: ``` f_oType = Type.GetTypeFromProgID(MyProgId); f_oInstance = Activator.CreateInstance(f_oType); ``` I need to use GetTypeFromProgID rather than using ...
I looked at your code a little closer and with reflection you handle TargetInvocationException and work with the inner exception that is a COMException... Code example below (I ran and tested this as well): ``` private void button1_Click(object sender, EventArgs e) { try { var f_oTy...
You will handle COMException and use the ErrorCode property of that exception object. Normally in visual basic DLLs if you are throwing custom errors you would raise the error with: Err.Raise vbObjectError + 88, "Project1.Class1.Test3()", "Forced error test" If this is the case you will need to subtract vbobjecterror ...
Retrieving the original error number from a COM method called via reflection
[ "", "c#", ".net", "com", "interop", "" ]
Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object? I know that I can: ``` f = open('c:\file.doc', "w") f.write(text) f.close() ``` but Word will read it as an HTML file not a native .doc file.
I'd look into [IronPython](http://ironpython.net/) which intrinsically has access to windows/office APIs because it runs on .NET runtime.
See [python-docx](https://github.com/python-openxml/python-docx), its official documentation is available [here](https://python-docx.readthedocs.org/en/latest/). This has worked very well for me. Note that this does not work for .doc files, only .docx files.
Reading/Writing MS Word files in Python
[ "", "python", "ms-word", "read-write", "" ]
In a C++ project, compilation dependencies can make a software project difficult to maintain. What are some of the best practices for limiting dependencies, both within a module and across modules?
* [Forward Declarations](http://en.wikipedia.org/wiki/Forward_declaration) * [Abstract Interfaces](http://en.wikipedia.org/wiki/Abstract_interface) * [The Pimpl Idiom](http://en.wikipedia.org/wiki/Opaque_pointer)
Herb Sutter has a great treatment of this exact topic in Items 26, 27 and 28, "Minimizing Compile-time Dependencies, Parts 1, 2 and 3", in his excellent book *Exceptional C++*, ISBN: 0201615622. IMHO, this is one of the best C++ programming books available.
What are some techniques for limiting compilation dependencies in C++ projects?
[ "", "c++", "dependencies", "" ]
What is the difference between `UNION` and `UNION ALL`?
`UNION` removes duplicate rows (where all columns in the results are the same), `UNION ALL` does not. There is a performance hit when using `UNION` instead of `UNION ALL`, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when develop...
Both UNION and UNION ALL concatenate the result of two different SQLs. They differ in the way they handle duplicates. * UNION performs a DISTINCT on the result set, eliminating any duplicate rows. * UNION ALL does not remove duplicates, and it therefore faster than UNION. > **Note:** While using this commands all sel...
What is the difference between UNION and UNION ALL?
[ "", "sql", "union", "union-all", "" ]
Is there an open-source alternative to MATLAB's [`fmincon`](https://www.mathworks.com/help/optim/index.html;jsessionid=95cd06964ab253598de29e7d0a80) function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / [NumPy](https://numpy.org/) / [SciPy](https://scipy.org/) and this is the only...
Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently) * Linear Program (...
Python optimization software: * **OpenOpt** <http://openopt.org> **(this one is numpy-based as you wish, with automatic differentiation by FuncDesigner)** * **Pyomo** <https://software.sandia.gov/trac/coopr/wiki/Package/pyomo> * **CVXOPT** <http://abel.ee.ucla.edu/cvxopt/> * **NLPy** <http://nlpy.sourceforge.net/>
Open source alternative to MATLAB's fmincon function?
[ "", "python", "numpy", "matlab", "numeric", "scientific-computing", "" ]
I'm trying: ``` import commands print commands.getoutput("ps -u 0") ``` But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND nothing more
This works on Mac OS X 10.5.5. Note the capital **-U** option. Perhaps that's been your problem. ``` import subprocess ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE) print ps.stdout.read() ps.stdout.close() ps.wait() ``` Here's the Python version ``` Python 2.5.2 (r252:60911, Feb 22 2008, 07:57...
If the OS support the /proc fs you can do: ``` >>> import os >>> pids = [int(x) for x in os.listdir('/proc') if x.isdigit()] >>> pids [1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444] >>> ``` A cross-platform solution (linux, freebsd, osx, windows) is by using [psutil](http://code.google.com/p/psutil/): ...
Which is the best way to get a list of running processes in unix with python?
[ "", "python", "" ]
Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object? I know that I can: ``` $file = fopen('c:\file.doc', 'w+'); fwrite($file, $text); fclose(); ``` but Word will read it as an HTML file not a native .doc file.
Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution. You could use the [Microsoft Office XML formats](http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Word_XML_Format_example) for read...
this works with vs < office 2007 and its pure PHP, no COM crap, still trying to figure 2007 ``` <?php /***************************************************************** This approach uses detection of NUL (chr(00)) and end line (chr(13)) to decide where the text is: - divide the file contents up by chr(13) - reject...
Reading/Writing a MS Word file in PHP
[ "", "php", "ms-word", "read-write", "" ]
Suppose I have one list: ``` IList<int> originalList = new List<int>(); originalList.add(1); originalList.add(5); originalList.add(10); ``` And another list... ``` IList<int> newList = new List<int>(); newList.add(1); newList.add(5); newList.add(7); newList.add(11); ``` How can I update originalList so that: 1. ...
Sorry, wrote my first response before I saw your last paragraph. ``` for(int i = originalList.length-1; i >=0; --i) { if (!newList.Contains(originalList[i]) originalList.RemoveAt(i); } foreach(int n in newList) { if (!originaList.Contains(n)) originalList.Add(n); } ```
``` originalList = newList; ``` Or if you prefer them being distinct lists: ``` originalList = new List<int>(newList); ``` But, either way does what you want. By your rules, after updating, originalList will be identical to newList. UPDATE: I thank you all for the support of this answer, but after a closer reading ...
What is the least amount of code needed to update one list with another list?
[ "", "c#", "generics", "merge", "generic-list", "" ]
I am trying to use `WebClient` to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore. I checked the `WebResponse.ContentType`, but its value is always `null`. Anyone have any idea what could be the cause?
Given your update, you can do this by changing the .Method in GetWebRequest: ``` using System; using System.Net; static class Program { static void Main() { using (MyClient client = new MyClient()) { client.HeadOnly = true; string uri = "http://www.google.com"; ...
I'm not sure the cause, but perhaps you hadn't downloaded anything yet. This is the lazy way to get the content type of a remote file/page (I haven't checked if this is efficient on the wire. For all I know, it may download huge chunks of content) ``` Stream connection = new MemoryStream(""); // Just a placeho...
How to check if System.Net.WebClient.DownloadData is downloading a binary file?
[ "", "c#", "file", "download", "webclient", "" ]
im creating a Factory class that will contruct and return an object. I normally would do all of the data stuff at the Data Access Layer, but i dont think i could reach my objective and still do so. What i want to do is use a SQLDataReader to quickly read the data information and populate the object to be returned from ...
In most cases this is a good idea as this way provides two major benefits: 1. This way you can seperate the data access and business logic, which means if you change database design the upper layer algorithms do not need to be changed. 2. From OO stand point, you are converting some pure data into objects and may also...
If you're sure you're going to be using all of the data you load from the SQLDataReader, then yes, you could do it at construction time in the factory. However if the data set has many fields, which only a minority of will be used, then demand-loading the data at the time the accessors are called would be a better use ...
Factory Class - Should i populate my object with data here?
[ "", "c#", ".net", "factory", "" ]
I would like to be able to trap `Ctrl`+`C` in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?
See MSDN: [Console.CancelKeyPress Event](https://learn.microsoft.com/en-us/dotnet/api/system.console.cancelkeypress?view=net-6.0) Article with code samples: [Ctrl-C and the .NET console application](https://web.archive.org/web/20200810221940/http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx)
The [Console.CancelKeyPress](https://learn.microsoft.com/en-us/dotnet/api/system.console.cancelkeypress) event is used for this. This is how it's used: ``` public static void Main(string[] args) { Console.CancelKeyPress += delegate { // call methods to clean up }; while (true) {} } ``` When the u...
How do I trap Ctrl+C (SIGINT) in a C# console app?
[ "", "c#", ".net", "console", "" ]
I am using the next class (simplified for the sake of understandability) to download images in a struts web application. It is working fine in every browser but firefox, which cuts names containing spaces. That it is to say: **file with spaces.pdf** gets downloaded in firefox as: **file** while in chrome, IE7 IE6 is do...
The filename should be a **quoted** string. (According to [Section 19.5.1 of RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1)) ``` response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\""); ```
URLEncode the filename? Or at least substitute %20 for the space character. (I don't know if this will work, but give it a try) have you tried just putting quotes around the filename as well?
Firefox cuts files, whose name contains spaces, in a Struts application
[ "", "java", "firefox", "struts", "" ]
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles providing an explanation would be appreciated. ``` //The constructor public Page_Index() { //create a local value string currentValue = "This is the...
currentValue is no longer a local variable: it is a *captured* variable. This compiles to something like: ``` class Foo { public string currentValue; // yes, it is a field public void SomeMethod(object sender, EventArgs e) { Response.Write(currentValue); } } ... public Page_Index() { Foo foo = new Foo(); ...
> I suppose more the question I am asking is that how is it working with a local variable > [MG edit: "Ack - ignore this..." was added afterwards] That is the point; it really *isn't* a local variable any more - at least, not in terms of how we normally think of them (on the stack etc). It looks like one, but it isn't...
Local variables with Delegates
[ "", "c#", "delegates", "closures", "heap-memory", "" ]
How can I drop sql server agent jobs, if (and only if) it exists? This is a well functioning script for *stored procedures*. How can I do the same to sql server agent jobs? ``` if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop proc...
Try something like this: ``` DECLARE @jobId binary(16) SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job') IF (@jobId IS NOT NULL) BEGIN EXEC msdb.dbo.sp_delete_job @jobId END DECLARE @ReturnCode int EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job' ``` Best to re...
``` IF EXISTS (SELECT job_id FROM msdb.dbo.sysjobs_view WHERE name = N'Your Job Name') EXEC msdb.dbo.sp_delete_job @job_name=N'Your Job Name' , @delete_unused_schedule=1 ```
SQL Server Agent Job - Exists then Drop?
[ "", "sql", "sql-server", "sql-server-agent", "sql-job", "" ]
According to select name from system\_privilege\_map System has been granted: ``` SELECT ANY TABLE ``` ...and lots of other \* ANY TABLES. Plainly running ``` select * from the_table; select * from the_table; ``` ...nets the given response: > ERROR at line 1: > ORA-00942: table or view does not exist I can log i...
If the\_table is owned by user "some\_user" then: ``` select * from some_user.the_table; ```
As the previous responses have said, you can prefix the object name with the schema name: ``` SELECT * FROM schema_name.the_table; ``` Or you can use a synonym (private or public): ``` CREATE (PUBLIC) SYNONYM the_table FOR schema_name.the_table; ``` Or you can issue an alter session command to set the default schem...
As System in Sqlplus, how do I query another user's table?
[ "", "sql", "oracle", "sqlplus", "ora-00942", "" ]