Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable? ``` public class TokenTree { public TokenTree() { /* I must admit to not fully understanding this, * I got it from msdn. As far as I can tell, IDictionary is an * interface, and Dictionary is the default implementation of * that interface, right? */ SubPairs = new Dictionary<string, string>(); } public string Key; public string Value; public IDictionary<string, string> SubPairs; } ``` It's only really a simple shunt for passing around data.
There is an actual Data Type called KeyValuePair, use like this ``` KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue"); ```
One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications: ``` public class TokenTree : Dictionary<string, string> { public IDictionary<string, string> SubPairs; } ``` This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc). And yup you got the concept of the constructor right :)
Best implementation for Key Value Pair Data Structure?
[ "", "c#", "data-structures", "collections", "" ]
It seems like anything you can do with bytecode you can do just as easily and much faster in native code. In theory, you could even retain platform and language independence by distributing programs and libraries in bytecode then compiling to native code at installation, rather than JITing it. So in general, when would you want to execute bytecode instead of native?
Hank Shiffman from SGI said (a long time ago, but it's till true): > There are three advantages of Java > using byte code instead of going to > the native code of the system: > > 1. **Portability**: Each kind of computer has its unique instruction > set. While some processors include the > instructions for their predecessors, > it's generally true that a program > that runs on one kind of computer > won't run on any other. Add in the > services provided by the operating > system, which each system describes in > its own unique way, and you have a > compatibility problem. In general, you > can't write and compile a program for > one kind of system and run it on any > other without a lot of work. Java gets > around this limitation by inserting > its virtual machine between the > application and the real environment > (computer + operating system). If an > application is compiled to Java byte > code and that byte code is interpreted > the same way in every environment then > you can write a single program which > will work on all the different > platforms where Java is supported. > (That's the theory, anyway. In > practice there are always small > incompatibilities lying in wait for > the programmer.) > 2. **Security**: One of Java's virtues is its integration into the Web. Load > a web page that uses Java into your > browser and the Java code is > automatically downloaded and executed. > But what if the code destroys files, > whether through malice or sloppiness > on the programmer's part? Java > prevents downloaded applets from doing > anything destructive by disallowing > potentially dangerous operations. > Before it allows the code to run it > examines it for attempts to bypass > security. It verifies that data is > used consistently: code that > manipulates a data item as an integer > at one stage and then tries to use it > as a pointer later will be caught and > prevented from executing. (The Java > language doesn't allow pointer > arithmetic, so you can't write Java > code to do what we just described. > However, there is nothing to prevent > someone from writing destructive byte > code themselves using a hexadecimal > editor or even building a Java byte > code assembler.) It generally isn't > possible to analyze a program's > machine code before execution and > determine whether it does anything > bad. Tricks like writing > self-modifying code mean that the evil > operations may not even exist until > later. But Java byte code was designed > for this kind of validation: it > doesn't have the instructions a > malicious programmer would use to hide > their assault. > 3. **Size**: In the microprocessor world RISC is generally preferable > over CISC. It's better to have a small > instruction set and use many fast > instructions to do a job than to have > many complex operations implemented as > single instructions. RISC designs > require fewer gates on the chip to > implement their instructions, allowing > for more room for pipelines and other > techniques to make each instruction > faster. In an interpreter, however, > none of this matters. If you want to > implement a single instruction for the > switch statement with a variable > length depending on the number of case > clauses, there's no reason not to do > so. In fact, a complex instruction set > is an advantage for a web-based > language: it means that the same > program will be smaller (fewer > instructions of greater complexity), > which means less time to transfer > across our speed-limited network. So when considering byte code vs native, consider which trade-offs you want to make between portability, security, size, and execution speed. If speed is the only important factor, go native. If any of the others are more important, go with bytecode. I'll also add that maintaining a series of OS and architecture-targeted compilations of the same code base for every release can become very tedious. It's a huge win to use the same Java bytecode on multiple platforms and have it "just work."
The performance of essentially any program will improve if it is compiled, executed with profiling, and the results fed back into the compiler for a second pass. The code paths which are actually used will be more aggressively optimized, loops unrolled to exactly the right degree, and the hot instruction paths arranged to maximize I$ hits. All good stuff, yet it is almost never done because it is annoying to go through so many steps to build a binary. This is the advantage of running the bytecode for a while before compiling it to native code: profiling information is automatically available. The result after Just-In-Time compilation is highly optimized native code for the specific data the program is processing. Being able to run the bytecode also enables more aggressive native optimization than a static compiler could safely use. For example if one of the arguments to a function is noted to always be NULL, all handling for that argument can simply be omitted from the native code. There will be a brief validity check of the arguments in the function prologue, if that argument is not NULL the VM aborts back to the bytecode and starts profiling again.
What are advantages of bytecode over native code?
[ "", "java", ".net", "bytecode", "" ]
I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation? > Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?
In C# `#define` macros, like some of Bernard's examples, are not allowed. The only common use of `#define`/`#if`s in C# is for adding optional debug only code. For example: ``` static void Main(string[] args) { #if DEBUG //this only compiles if in DEBUG Console.WriteLine("DEBUG") #endif #if !DEBUG //this only compiles if not in DEBUG Console.WriteLine("RELEASE") #endif //This always compiles Console.ReadLine() } ```
#define is used to define compile-time constants that you can use with #if to include or exclude bits of code. ``` #define USEFOREACH #if USEFOREACH foreach(var item in items) { #else for(int i=0; i < items.Length; ++i) { var item = items[i]; //take item #endif doSomethingWithItem(item); } ```
How do you use #define?
[ "", "c#", "" ]
I'm setting up a web application with a FreeBSD PostgreSQL back-end. I'm looking for some database performance optimization tool/technique.
[pgfouine](http://pgfouine.projects.postgresql.org/) works fairly well for me. And it looks like there's a [FreeBSD port](http://portsmon.freebsd.org/portoverview.py?category=databases&portname=pgfouine) for it.
Database optimization is usually a combination of two things 1. Reduce the number of queries to the database 2. Reduce the amount of data that needs to be looked at to answer queries Reducing the amount of queries is usually done by caching non-volatile/less important data (e.g. "Which users are online" or "What are the latest posts by this user?") inside the application (if possible) or in an external - more efficient - datastore (memcached, redis, etc.). If you've got information which is very write-heavy (e.g. hit-counters) and doesn't need [ACID](http://en.wikipedia.org/wiki/ACID)-semantics you can also think about moving it out of the Postgres database to more efficient data stores. Optimizing the query runtime is more tricky - this can amount to creating [special indexes](http://www.postgresql.org/docs/current/static/indexes-partial.html) (or [indexes in the first place](http://www.postgresql.org/docs/current/static/indexes.html)), changing (possibly denormalizing) the data model or changing the fundamental approach the application takes when it comes to working with the database. See for example the [Pagination done the Postgres way](https://wiki.postgresql.org/images/3/35/Pagination_Done_the_PostgreSQL_Way.pdf) talk by [Markus Winand](http://use-the-index-luke.com/) on how to rethink the concept of pagination to make it more database efficient ## Measuring queries the slow way But to understand which queries should be looked at first you need to know how often they are executed and how long they run on average. One approach to this is logging all (or "slow") queries including their runtime and then parsing the query log. A good tool for this is [`pgfouine`](http://pgfouine.projects.pgfoundry.org/) which has already been mentioned earlier in this discussion, it has since been replaced by [`pgbadger`](http://dalibo.github.io/pgbadger/) which is written in a more friendly language, is much faster and more actively maintained. Both `pgfouine` and `pgbadger` suffer from the fact that they need query-logging enabled, which can cause a noticeable performance hit on the database or bring you into disk space troubles on top of the fact that parsing the log with the tool can take quite some time and won't give you up-to-date insights on what is going in the database. ## Speeding it up with extensions To address these shortcomings there are now two extensions which track query performance directly in the database - [`pg_stat_statements`](http://www.postgresql.org/docs/current/static/pgstatstatements.html) (which is only helpful in version 9.2 or newer) and [`pg_stat_plans`](https://github.com/2ndQuadrant/pg_stat_plans). Both extensions offer the same basic functionality - tracking how often a given "normalized query" (Query string minus all expression literals) has been run and how long it took in total. Due to the fact that this is done while the query is actually run this is done in a very efficient manner, the measurable overhead was less than 5% in synthetic benchmarks. ## Making sense of the data The list of queries itself is very "dry" from an information perspective. There's been work on a third extension trying to address this fact and offer nicer representation of the data called [`pg_statsinfo`](http://pgstatsinfo.projects.pgfoundry.org/) (along with `pg_stats_reporter`), but it's a bit of an undertaking to get it up and running. To offer a more convenient solution to this problem I started working on a commercial project which is focussed around `pg_stat_statements` and `pg_stat_plans` and augments the information collected by lots of other data pulled out of the database. It's called `pganalyze` and you can find it at <https://pganalyze.com/>. To offer a concise overview of interesting tools and projects in the Postgres Monitoring area i also started compiling a list at the [Postgres Wiki](http://wiki.postgresql.org/wiki/Monitoring) which is updated regularly.
PostgreSQL performance monitoring tool
[ "", "sql", "database", "optimization", "postgresql", "freebsd", "" ]
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: ``` class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) ``` But now I'm wondering if there's a situation where nesting would be better. Something like: ``` class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) ```
You might want to do this when the "inner" class is a one-off, which will never be used outside the *definition* of the outer class. For example to use a metaclass, it's sometimes handy to do ``` class Foo(object): class __metaclass__(type): .... ``` instead of defining a metaclass separately, if you're only using it once. The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together: ``` class Group(object): class cls1(object): ... class cls2(object): ... ``` Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.
I don't know Python, but your question seems very general. Ignore me if it's specific to Python. Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class. It is a common pattern make helper classes as private, nested classes.
Is there a benefit to defining a class inside another class in Python?
[ "", "python", "oop", "" ]
Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results. What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user? Does LINQ simplify the solution?
On MS SQL Server 2005 and above, [ROW\_NUMBER()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) seems to work: [T-SQL: Paging with ROW\_NUMBER()](http://blogs.x2line.com/al/archive/2005/11/18/1323.aspx) ``` DECLARE @PageNum AS INT; DECLARE @PageSize AS INT; SET @PageNum = 2; SET @PageSize = 10; WITH OrdersRN AS ( SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum ,OrderID ,OrderDate ,CustomerID ,EmployeeID FROM dbo.Orders ) SELECT * FROM OrdersRN WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize ORDER BY OrderDate ,OrderID; ```
I'd recommend either using LINQ, or try to copy what it does. I've got an app where I use the LINQ Take and Skip methods to retrieve paged data. The code looks something like this: ``` MyDataContext db = new MyDataContext(); var results = db.Products .Skip((pageNumber - 1) * pageSize) .Take(pageSize); ``` Running SQL Server Profiler reveals that LINQ is converting this query into SQL similar to: ``` SELECT [ProductId], [Name], [Cost], and so on... FROM ( SELECT [ProductId], [Name], [Cost], [ROW_NUMBER] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [Name]) AS [ROW_NUMBER], [ProductId], [Name], [Cost] FROM [Products] ) WHERE [ROW_NUMBER] BETWEEN 10 AND 20 ) ORDER BY [ROW_NUMBER] ``` In plain English: 1. Filter your rows and use the ROW\_NUMBER function to add row numbers in the order you want. 2. Filter (1) to return only the row numbers you want on your page. 3. Sort (2) by the row number, which is the same as the order you wanted (in this case, by Name).
How to return a page of results from SQL?
[ "", ".net", "sql", "linq", "pagination", "" ]
I've created a model for executing worker tasks in a server application using a thread pool associated with an IO completion port such as shown in the posts below: <http://weblogs.asp.net/kennykerr/archive/2008/01/03/parallel-programming-with-c-part-4-i-o-completion-ports.aspx> <http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx> Are there any classes in boost that can help with this programming model?
Not really, at least, not last time I looked. I mean, boost::thread\_group might make things marginally tidier in places, but not so as would make much of a difference, I don't think. Boost's thread support seems marginally useful when writing something that's cross-platform, but given that what you're writing is going to be Win32-specific anyway (due to the use of IOCPs) there doesn't really seem to be much benefit from that.
I haven't seen anything in boost that helps with the structure that you tend to end up with when using IO Completion Ports, but then I haven't looked that recently... However, slightly off-topic, you might like to take a look at the IOCP based thread pool that is part of my free IOCP server framework. It might give you some ideas if nothing else. You can find the code [here](http://www.serverframework.com/products---the-free-framework.html). The thread pool supports expansion and contraction based on demand and has been in use in production systems for over 6 years.
Task oriented thread pooling
[ "", "c++", "multithreading", "boost", "" ]
When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.
To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array. ``` void SomethingHappened(object sender, EventArgs ea) { if (InvokeRequired) { Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea); return; } textBox1.Text = "Something happened"; } ```
Here are the salient points: 1. You can't make UI control calls from a different thread than the one they were created on (the form's thread). 2. Delegate invocations (ie, event hooks) are triggered on the same thread as the object that is firing the event. So, if you have a separate "engine" thread doing some work and have some UI watching for state changes which can be reflected in the UI (such as a progress bar or whatever), you have a problem. The engine fire's an object changed event which has been hooked by the Form. But the callback delegate that the Form registered with the engine gets called on the engine's thread… not on the Form's thread. And so you can't update any controls from that callback. Doh! **BeginInvoke** comes to the rescue. Just use this simple coding model in all your callback methods and you can be sure that things are going to be okay: ``` private delegate void EventArgsDelegate(object sender, EventArgs ea); void SomethingHappened(object sender, EventArgs ea) { // // Make sure this callback is on the correct thread // if (this.InvokeRequired) { this.Invoke(new EventArgsDelegate(SomethingHappened), new object[] { sender, ea }); return; } // // Do something with the event such as update a control // textBox1.Text = "Something happened"; } ``` It's quite simple really. 1. Use **InvokeRequired** to find out if this callback happened on the correct thread. 2. If not, then reinvoke the callback on the correct thread with the same parameters. You can reinvoke a method by using the **Invoke** (blocking) or **BeginInvoke** (non-blocking) methods. 3. The next time the function is called, **InvokeRequired** returns false because we are now on the correct thread and everybody is happy. This is a very compact way of addressing this problem and making your Forms safe from multi-threaded event callbacks.
How do I make event callbacks into my win forms thread safe?
[ "", "c#", ".net", "winforms", "multithreading", "events", "" ]
When I call `socket.getsockname()` on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?
This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.
The only way I can think of that's guaranteed to give it to you is to hit a service like <http://whatismyip.com/> to get it.
How do I get the external IP of a socket in Python?
[ "", "python", "sockets", "" ]
How can I go about storing a vb.net user defined object in a sql database. I am not trying to replicate the properties with columns. I mean something along the lines of converting or encoding my object to a byte array and then storing that in a field in the db. Like when you store an instance of an object in session, but I need the info to persist past the current session. --- @Orion Edwards > It's not a matter of stances. It's because one day, you will change your code. Then you will try de-serialize the old object, and YOUR PROGRAM WILL CRASH. My Program will not "CRASH", it will throw an exception. Lucky for me .net has a whole set of classes dedicated for such an occasion. At which time I will refresh my stale data and put it back in the db. That is the point of this one field (or stance, as the case may be).
You can use [serialization](http://msdn.microsoft.com/en-us/library/ms973893.aspx) - it allows you to store your object at least in 3 forms: binary (suitable for BLOBs), XML (take advantage of MSSQL's XML data type) or just plain text (store in varchar or text column)
Before you head down this road towards your own eventual insanity, you should take a look at this (or one day repeat it): <http://thedailywtf.com/Articles/The-Mythical-Business-Layer.aspx> Persisting objects in a database is not a good idea. It kills all the good things that a database is designed to do.
vb.net object persisted in database
[ "", "sql", "vb.net", "serialization", "" ]
If I remove all the ' characters from a SQL query, is there some other way to do a SQL injection attack on the database? How can it be done? Can anyone give me examples?
Yes, there is. An excerpt from [Wikipedia](http://en.wikipedia.org/wiki/SQL_injection) `"SELECT * FROM data WHERE id = " + a_variable + ";"` It is clear from this statement that the author intended a\_variable to be a number correlating to the "id" field. However, if it is in fact a string then the end user may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a\_variable to `1;DROP TABLE users` will drop (delete) the "users" table from the database, since the SQL would be rendered as follows: `SELECT * FROM DATA WHERE id=1;DROP TABLE users;` SQL injection is *not* a simple attack to fight. I would do very careful research if I were you.
Yes, depending on the statement you are using. You are better off protecting yourself either by using Stored Procedures, or at least parameterised queries. See [Wikipedia](http://en.wikipedia.org/wiki/SQL_injection#Preventing_SQL_Injection) for prevention samples.
Is there some way to inject SQL even if the ' character is deleted?
[ "", "sql", "database", "sql-injection", "" ]
Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
The [`dis`](https://docs.python.org/3/library/dis.html) module disassembles the byte code for a function and is useful to see the difference between tuples and lists. In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list. ``` >>> def a(): ... x=[1,2,3,4,5] ... y=x[2] ... >>> def b(): ... x=(1,2,3,4,5) ... y=x[2] ... >>> import dis >>> dis.dis(a) 2 0 LOAD_CONST 1 (1) 3 LOAD_CONST 2 (2) 6 LOAD_CONST 3 (3) 9 LOAD_CONST 4 (4) 12 LOAD_CONST 5 (5) 15 BUILD_LIST 5 18 STORE_FAST 0 (x) 3 21 LOAD_FAST 0 (x) 24 LOAD_CONST 2 (2) 27 BINARY_SUBSCR 28 STORE_FAST 1 (y) 31 LOAD_CONST 0 (None) 34 RETURN_VALUE >>> dis.dis(b) 2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5)) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 LOAD_CONST 2 (2) 12 BINARY_SUBSCR 13 STORE_FAST 1 (y) 16 LOAD_CONST 0 (None) 19 RETURN_VALUE ```
## Summary *Tuples tend to perform better than lists* in almost every category: 1. Tuples can be [constant folded](https://en.wikipedia.org/wiki/Constant_folding). 2. Tuples can be reused instead of copied. 3. Tuples are compact and don't over-allocate. 4. Tuples directly reference their elements. ## Tuples can be constant folded Tuples of constants can be precomputed by Python's peephole optimizer or AST-optimizer. Lists, on the other hand, get built-up from scratch: ``` >>> from dis import dis >>> dis(compile("(10, 'abc')", '', 'eval')) 1 0 LOAD_CONST 2 ((10, 'abc')) 3 RETURN_VALUE >>> dis(compile("[10, 'abc']", '', 'eval')) 1 0 LOAD_CONST 0 (10) 3 LOAD_CONST 1 ('abc') 6 BUILD_LIST 2 9 RETURN_VALUE ``` ## Tuples do not need to be copied Running `tuple(some_tuple)` returns immediately itself. Since tuples are immutable, they do not have to be copied: ``` >>> a = (10, 20, 30) >>> b = tuple(a) >>> a is b True ``` In contrast, `list(some_list)` requires all the data to be copied to a new list: ``` >>> a = [10, 20, 30] >>> b = list(a) >>> a is b False ``` ## Tuples do not over-allocate Since a tuple's size is fixed, it can be stored more compactly than lists which need to over-allocate to make `append()` operations efficient. This gives tuples a nice space advantage: ``` >>> import sys >>> sys.getsizeof(tuple(iter(range(10)))) 128 >>> sys.getsizeof(list(iter(range(10)))) 200 ``` Here is the comment from *Objects/listobject.c* that explains what lists are doing: ``` /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long * sequence of appends() in the presence of a poorly-performing * system realloc(). * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... * Note: new_allocated won't overflow because the largest possible value * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t. */ ``` ## Tuples refer directly to their elements References to objects are incorporated directly in a tuple object. In contrast, lists have an extra layer of indirection to an external array of pointers. This gives tuples a small speed advantage for indexed lookups and unpacking: ``` $ python3.6 -m timeit -s 'a = (10, 20, 30)' 'a[1]' 10000000 loops, best of 3: 0.0304 usec per loop $ python3.6 -m timeit -s 'a = [10, 20, 30]' 'a[1]' 10000000 loops, best of 3: 0.0309 usec per loop $ python3.6 -m timeit -s 'a = (10, 20, 30)' 'x, y, z = a' 10000000 loops, best of 3: 0.0249 usec per loop $ python3.6 -m timeit -s 'a = [10, 20, 30]' 'x, y, z = a' 10000000 loops, best of 3: 0.0251 usec per loop ``` [Here](https://github.com/python/cpython/blob/54ba556c6c7d8fd5504dc142c2e773890c55a774/Include/cpython/tupleobject.h#L9) is how the tuple `(10, 20)` is stored: ``` typedef struct { Py_ssize_t ob_refcnt; struct _typeobject *ob_type; Py_ssize_t ob_size; PyObject *ob_item[2]; /* store a pointer to 10 and a pointer to 20 */ } PyTupleObject; ``` [Here](https://github.com/python/cpython/blob/master/Include/listobject.h) is how the list `[10, 20]` is stored: ``` PyObject arr[2]; /* store a pointer to 10 and a pointer to 20 */ typedef struct { Py_ssize_t ob_refcnt; struct _typeobject *ob_type; Py_ssize_t ob_size; PyObject **ob_item = arr; /* store a pointer to the two-pointer array */ Py_ssize_t allocated; } PyListObject; ``` Note that the tuple object incorporates the two data pointers directly while the list object has an additional layer of indirection to an external array holding the two data pointers.
Are tuples more efficient than lists in Python?
[ "", "python", "performance", "list", "tuples", "python-internals", "" ]
I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer. Here is my regex: `"\w+ +\w+ *\(.*\) *\{"` For those who do not know what a java method looks like I'll provide a basic one: ``` int foo() { } ``` There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have. Update: My current Regex is `"\w+ +\w+ *\([^\)]*\) *\{"` so as to prevent the situation that Mike and adkom described.
Have you considered matching the actual possible keywords? such as: ``` (?:(?:public)|(?:private)|(?:static)|(?:protected)\s+)* ``` It might be a bit more likely to match correctly, though it might also make the regex harder to read...
``` (public|protected|private|static|\s) +[\w\<\>\[\]]+\s+(\w+) *\([^\)]*\) *(\{?|[^;]) ``` I think that the above regexp can match almost all possible combinations of Java method declarations, even those including generics and arrays are return arguments, which the regexp provided by the original author did not match.
Regex that Will Match a Java Method Declaration
[ "", "java", "regex", "methods", "" ]
Why is `Array.Length` an int, and not a `uint`. This bothers me (just a bit) because a length value can never be negative. This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly... So the ultimate question is: is there any use for an unsigned int (`uint`)? Even Microsoft seems not to use them.
Unsigned int isn't CLS compliant and would therefore restrict usage of the property to those languages that do implement a `UInt`. See here: Framework 1.1 > [Introduction to the .NET Framework Class Library](http://msdn.microsoft.com/en-us/library/hfa3fa08(VS.71).aspx) Framework 2.0 > [.NET Framework Class Library Overview](http://msdn.microsoft.com/en-us/library/hfa3fa08(VS.80).aspx)
Many reasons: * uint is not CLS compliant, thus making a built in type (array) dependent on it would have been problematic * The runtime as originally designed prohibits any object on the heap occupying more than 2GB of memory. Since the maximum sized array that would less than or equal to this limit would be new byte[int.MaxValue] it would be puzzling to people to be able to generate positive but illegal array lengths. + Note that this limitation has been [somewhat removed in the 4.5 release](http://msdn.microsoft.com/en-us/library/hh285054(v=vs.110).aspx), though the standard Length as int remains. * Historically C# inherits much of its syntax and convention from C and C++. In those arrays are simply pointer arithmetic so negative array indexing was possible (though normally illegal and dangerous). Since much existing code assumes that the array index is signed this would have been a factor * On a related note the use of signed integers for array indexes in C/C++ means that interop with these languages and unmanaged functions would require the use of ints in those circumstances anyway, which may confuse due to the inconsistency. * The BinarySearch implementation (a very useful component of many algorithms) relies on being able to use the negative range of the int to indicate that the value was not found **and** the location at which such a value should be inserted to maintain sorting. * When operating on an array it is likely that you would want to take a negative offset of an existing index. If you used an offset which would take you past the start of the array using unit then the wrap around behaviour would make your index possibly legal (in that it is positive). With an int the result would be illegal (but safe since the runtime would guard against reading invalid memory)
Why is Array.Length an int, and not an uint
[ "", "c#", ".net", "int", "uint", "" ]
Why are unsigned integers not CLS compliant? I am starting to think the type specification is just for performance and not for correctness.
Not all languages have the concept of unsigned ints. For example VB 6 had no concept of unsigned ints which I suspect drove the decision of the designers of VB7/7.1 not to implement as well (it's implemented now in VB8). To quote: > <http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx> > > The CLS was designed to be large enough to include the language > constructs that are commonly needed by developers, yet small enough > that most languages are able to support it. In addition, any language > construct that makes it impossible to rapidly verify the type safety > of code was excluded from the CLS so that all CLS-compliant languages > can produce verifiable code if they choose to do so. Update: I did wonder about this some years back, and whilst I can't see why a UInt wouldn't be type safety verifiable, I guess the CLS guys had to have a cut off point somewhere as to what would be the baseline minimum number of value types supported. Also when you think about the longer term where more and more languages are being ported to the CLR why force them to implement unsigned ints to gain CLS compliance if there is absolutely no concept, ever?
Part of the issue, I suspect, revolves around the fact that unsigned integer types in C are required to behave as members of an abstract algebraic ring rather than as numbers [meaning, for example, that if an unsigned 16-bit integer variable equals zero, decrementing it is *required* to yield 65,535, and if it's equal to 65,535 then incrementing it is required to yield zero.] There are times when such behavior is extremely useful, but numeric types exhibit such behavior may have gone against the spirit of some languages. I would conjecture that the decision to omit unsigned types probably predates the decision to support both checked and unchecked numeric contexts. Personally, I wish there had been separate integer types for unsigned numbers and algebraic rings; applying a unary minus operator to unsigned 32-bit number should yield a 64-bit signed result [negating anything other than zero would yield a negative number] but applying a unary minus to a ring type should yield the additive inverse within that ring. In any case, the reason unsigned integers are not CLS compliant is that Microsoft decided that languages didn't have to support unsigned integers in order to be considered "CLS compatible".
Why are unsigned int's not CLS compliant?
[ "", "c#", ".net", "unsigned-integer", "cls-compliant", "" ]
I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING\_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas? ``` CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; ``` *Edited to remove double primary key definition...* --- Yeah, unfortunately that didn't fix it though. Now I'm getting: > Can't create table > './*REMOVED MY DB NAME*/SHIPPING\_GRID.frm' > (errno: 150) Doing a phpinfo() tells me this for mysql: > Client API version 5.0.45 Yes, the VENDOR.no is type int(6).
You defined the primary key twice. Try: ``` CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; ``` The VENDOR primary key must be INT(6), and both tables must be of type InnoDB.
> Can you provide the definition of the > VENDOR table I figured it out. The VENDOR table was MyISAM... (edited your answer to tell me to make them both INNODB ;) ) (any reason *not* to just switch the VENDOR type over to INNODB?)
Multiple foreign keys?
[ "", "sql", "mysql", "foreign-keys", "" ]
As everyone knows, the [Visual C++](http://en.wikipedia.org/wiki/Visual_C%2B%2B) runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since `0xFEEEFEEE != 0`. Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to `0xFEEEFEEE` instead of `NULL`. When I insert a proper check for `NULL`, as all good programs that manage their own memory should, I come up with problems as `0xFEEEFEEE` passes a `NULL` check without problems. Is there any good way, other than manually setting all pointers to `NULL` when deleting them, to detect when memory has already been freed? I would prefer to not use [Boost](http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries) simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.
It is not the responsibility of `delete` to reset all the pointers to the object to `NULL`. Also you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like `boost::shared_ptr<>` for pointers any way. That said, if you really want to **shoot your self in the foot** you can. You can **change** the **default fill** for the windows **DEBUG runtime** by using an allocator hook like this. This will only work on HEAP allocated object! ``` int main(int argc,char** arv) { // Call first to register hook _CrtSetAllocHook(&zero_fill); // Do other stuff malloc(100); } int zero_fill(int nAllocType, void* pvData, size_t nSize, int nBlockUse, long lRequest, const unsigned char *szFileName, int nLine ) { /// Very Importaint !! /// infinite recursion if this is removed !! /// _CRT_BLOCK must not do any thing but return TRUE /// even calling printf in the _CRT_BLOCK will cause /// infinite recursion if ( nBlockUse == _CRT_BLOCK ) return( TRUE ); switch(nAllocType) { case _HOOK_ALLOC: case _HOOK_REALLOC: // zero initialize the allocated space. memset(pvData,0,nSize); break; case _HOOK_FREE: break; } return TRUE; } ```
When you create a pointer, explicity initialize it to `NULL`. Likewise after a `delete`. Depending on the value of uninitialized data (except in a few specific cases) is asking for trouble. You can save yourself a lot of headaches by using a smart pointer class (such as [`boost::shared_ptr`](http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/shared_ptr.htm)) which will automatically deal with whether a pointer is initialized or not.
Uninitialized memory blocks in VC++
[ "", "c++", "memory", "allocation", "" ]
I want to generate a thumbnail preview of videos in Java. I'm mostly JMF and video manipulation alienated. * Is there an easy way to do it? * What about codecs? Will I have to deal with it? * Any video type is suported? (including Quicktime)
There seems to be a few examples out there that are far better than [what I was going to send you.](http://code.google.com/p/vitalopensource/source/browse/trunk/src/com/vtls/opensource/image/VideoImageSource.java) See <http://krishnabhargav.blogspot.com/2008/02/processing-videos-in-java.html>. I'd agree with Stu, however. If you can find a way to get what you want using some command-line tools (and run them using [Commons-Exec](http://commons.apache.org/exec/)), you might have a better overall solution than depending on what is essentially the Sanskrit of Java extensions.
Well, since you're not stuck with JMF, have you considered [Xuggler](http://www.xuggle.com/xuggler)? Xuggler is a Java API that uses FFmpeg under the covers to do all video decoding and encoding. It's free and LGPL licensed. In fact, we have a tutorial that shows [How to Make Thumbnails of an Existing File](http://build.xuggle.com/view/Stable/job/xuggler_jdk5_stable/ws/workingcopy/src/com/xuggle/mediatool/demos/DecodeAndCaptureFrames.java)
Video Thumbnails in Java
[ "", "java", "video", "jmf", "" ]
I'm looking at parsing a delimited string, something on the order of a,b,c But this is a very simple example, and parsing delimited data can get complex; for instance 1,"Your simple algorithm, it fails",True would blow your naiive string.Split implementation to bits. Is there anything I can freely use/steal/copy and paste that offers a relatively bulletproof solution to parsing delimited text? .NET, plox. *Update:* I decided to go with the [TextFieldParser](http://msdn.microsoft.com/en-us/library/f68t4563.aspx), which is part of VB.NET's pile of goodies hidden away in Microsoft.VisualBasic.DLL.
I use this to read from a file ``` string filename = @textBox1.Text; string[] fields; string[] delimiter = new string[] {"|"}; using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(filename)) { parser.Delimiters = delimiter; parser.HasFieldsEnclosedInQuotes = false; while (!parser.EndOfData) { fields = parser.ReadFields(); //Do what you need } } ``` I am sure someone here can transform this to parser a string that is in memory.
I am not aware of any framework, but a simple state machine works: * State 1: Read every char until you hit a " or a , + In case of a ": Move to State 2 + In case of a ,: Move to State 3 + In case of the end of file: Move to state 4 * State 2: Read every char until you hit a " + In case of a ": Move to State 1 + In case of the end of the file: Either Move to State 4 or signal an error because of an unterminated string * State 3: Add the current buffer to the output array, move the cursor forward behind the , and back to State 1. * State 4: this is the final state, does nothing except returning the output array.
Delimited string parsing?
[ "", "c#", "text-parsing", "csv", "" ]
I've been looking for this information for my commercial desktop product, with no avail. Specifically, what I'm look for, is deployment statistics of the .NET framework for end-users (both granny "I'm just browsing the internet" XP, and high-end users, if possible), and in the commercial/business sector. Edit: Other than the data points below, here's an interesting blog post about .NET [deployment rates](http://www.nbdtech.com/blog/archive/2009/05/25/what-percentage-of-users-have-the-.net-framework-installed-and.aspx).
Some statistics from 2005 I found at [Scott Wiltamuth's blog](http://blogs.msdn.com/scottwil/archive/2005/03/09/391199.aspx) (you can be sure these numbers are much higher now): * More than 120M copies of the .NET Framework have been downloaded and installed using either Microsoft downloads or Windows Update * More than 85% of new consumer PCs sold in 2004 had the .NET Framework installed * More than 58% of business PCs have the .NET Framework preinstalled or preloaded * Every new HP consumer imaging device (printer/scanner/camera) will install the .NET Framework if it’s not already there – that’s 3M units per year * Every new Microsoft IntelliPoint mouse software CD ships with the .NET Framework It is also worth pointing out that Vista and Windows Server 2008 both ship with the .NET Framework. XP gets it via Windows Update.
I don't have any hard numbers, but these days, it is pretty safe to assume most Windows XP and Vista users have at least .NET 2.0. I believe this was actually dropped via Windows Update for XP, and Vista came with at least 2.0 (apparently with 3.0 as pointed out in the comments to this answer).
What is the deployment rate of the .NET framework?
[ "", "c#", ".net", "deployment", "statistics", "" ]
Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?
Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap. Structs can also contain class definitions as members (inner classes). Here's some really useless code that at least compiles and runs to show that it's possible: ``` using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyStr m = new MyStr(); m.Foo(); MyStr.MyStrInner mi = new MyStr.MyStrInner(); mi.Bar(); Console.ReadLine(); } } public class Myclass { public int a; } struct MyStr { Myclass mc; public void Foo() { mc = new Myclass(); mc.a = 1; } public class MyStrInner { string x = "abc"; public string Bar() { return x; } } } } ```
The class content gets stored on the heap. A reference to the class (which is almost the same as a pointer) gets stored with the struct content. Where the struct content is stored depends on whether it's a local variable, method parameter, or member of a class, and whether it's been boxed or captured by a closure.
Can you have a class in a struct?
[ "", "c#", "class", "struct", "value-type", "reference-type", "" ]
How do I create class (i.e. [static](https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods)) variables or methods in Python?
Variables declared inside the class definition, but not inside a method are class or static variables: ``` >>> class MyClass: ... i = 3 ... >>> MyClass.i 3 ``` As @[millerdev](https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067) points out, this creates a class-level `i` variable, but this is distinct from any instance-level `i` variable, so you could have ``` >>> m = MyClass() >>> m.i = 4 >>> MyClass.i, m.i >>> (3, 4) ``` This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance. See [what the Python tutorial has to say on the subject of classes and class objects](https://docs.python.org/3/tutorial/classes.html#class-objects). @Steve Johnson has already answered regarding [static methods](http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod), also documented under ["Built-in Functions" in the Python Library Reference](https://docs.python.org/3/library/functions.html#staticmethod). ``` class C: @staticmethod def f(arg1, arg2, ...): ... ``` @beidy recommends [classmethod](https://docs.python.org/3/library/functions.html#classmethod)s over staticmethod, as the method then receives the class type as the first argument.
@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables: ``` >>> class Test(object): ... i = 3 ... >>> Test.i 3 ``` There are a few gotcha's here. Carrying on from the example above: ``` >>> t = Test() >>> t.i # "static" variable accessed via instance 3 >>> t.i = 5 # but if we assign to the instance ... >>> Test.i # we have not changed the "static" variable 3 >>> t.i # we have overwritten Test.i on t by creating a new attribute t.i 5 >>> Test.i = 6 # to change the "static" variable we do it by assigning to the class >>> t.i 5 >>> Test.i 6 >>> u = Test() >>> u.i 6 # changes to t do not affect new instances of Test # Namespaces are one honking great idea -- let's do more of those! >>> Test.__dict__ {'i': 6, ...} >>> t.__dict__ {'i': 5} >>> u.__dict__ {} ``` Notice how the instance variable `t.i` got out of sync with the "static" class variable when the attribute `i` was set directly on `t`. This is because `i` was re-bound within the `t` namespace, which is distinct from the `Test` namespace. If you want to change the value of a "static" variable, you must change it within the scope (or object) where it was originally defined. I put "static" in quotes because Python does not really have static variables in the sense that C++ and Java do. Although it doesn't say anything specific about static variables or methods, the [Python tutorial](http://docs.python.org/tut/) has some relevant information on [classes and class objects](https://docs.python.org/2/tutorial/classes.html). @Steve Johnson also answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference. ``` class Test(object): @staticmethod def f(arg1, arg2, ...): ... ``` @beid also mentioned classmethod, which is similar to staticmethod. A classmethod's first argument is the class object. Example: ``` class Test(object): i = 3 # class (or static) variable @classmethod def g(cls, arg): # here we can use 'cls' instead of the class name (Test) if arg > cls.i: cls.i = arg # would be the same as Test.i = arg1 ``` [![Pictorial Representation Of Above Example](https://i.stack.imgur.com/xqnxe.jpg)](https://i.stack.imgur.com/xqnxe.jpg)
Class (static) variables and methods
[ "", "python", "class", "static", "class-variables", "" ]
If I pass request fields or cookies with a period/dot in their names, PHP auto-replaces them with underscores. For example, if I put this code at `https://example.com/test.php?x.y=a.b`: ``` <?php echo $_SERVER['REQUEST_URI']; echo $_GET['x.y']; echo $_GET['x_y']; ``` the output is: ``` /test.php?x.y=a.b a.b ``` Is there **any** way I can prevent this behaviour?
Here's PHP.net's explanation of why it does it: > ### Dots in incoming variable names > > Typically, PHP does not alter the > names of variables when they are > passed into a script. However, it > should be noted that the dot (period, > full stop) is not a valid character in > a PHP variable name. For the reason, > look at it: > > ``` > <?php > $varname.ext; /* invalid variable name */ > ?> > ``` > > Now, what > the parser sees is a variable named > $varname, followed by the string > concatenation operator, followed by > the barestring (i.e. unquoted string > which doesn't match any known key or > reserved words) 'ext'. Obviously, this > doesn't have the intended result. > > For this reason, it is important to > note that PHP will automatically > replace any dots in incoming variable > names with underscores. That's from <http://ca.php.net/variables.external>. Also, according to [this comment](http://ca.php.net/manual/en/language.variables.external.php#81080) these other characters are converted to underscores: > The full list of field-name characters that PHP converts to \_ (underscore) is the following (not just dot): > > * chr(32) ( ) (space) > * chr(46) (.) (dot) > * chr(91) ([) (open square bracket) > * chr(128) - chr(159) (various) So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using [dawnerd's suggestion](https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667) (I'd just use [str\_replace](http://php.net/str_replace) though.)
Long-since answered question, but there is actually a better answer (or work-around). PHP lets you at the [raw input stream](http://php.net/manual/en/wrappers.php.php), so you can do something like this: ``` $query_string = file_get_contents('php://input'); ``` which will give you the $\_POST array in query string format, periods as they should be. You can then parse it if you need (as per [POSTer's comment](http://www.php.net/manual/en/language.variables.external.php#94607)) ``` <?php // Function to fix up PHP's messing up input containing dots, etc. // `$source` can be either 'POST' or 'GET' function getRealInput($source) { $pairs = explode("&", $source == 'POST' ? file_get_contents("php://input") : $_SERVER['QUERY_STRING']); $vars = array(); foreach ($pairs as $pair) { $nv = explode("=", $pair); $name = urldecode($nv[0]); $value = urldecode($nv[1]); $vars[$name] = $value; } return $vars; } // Wrapper functions specifically for GET and POST: function getRealGET() { return getRealInput('GET'); } function getRealPOST() { return getRealInput('POST'); } ?> ``` Hugely useful for OpenID parameters, which contain both '.' and '\_', each with a certain meaning!
How to stop PHP replacing dot characters in GET, POST, or COOKIE names?
[ "", "php", "" ]
Can someone give an example of a good time to actually use "unsafe" and "fixed" in C# code? I've played with it before, but never actually found a good use for it. Consider this code... ``` fixed (byte* pSrc = src, pDst = dst) { //Code that copies the bytes in a loop } ``` compared to simply using... ``` Array.Copy(source, target, source.Length); ``` The second is the code found in the .NET Framework, the first a part of the code copied from the Microsoft website, <http://msdn.microsoft.com/en-us/library/28k1s2k6(VS.80).aspx>. The built in Array.Copy() is dramatically faster than using Unsafe code. This might just because the second is just better written and the first is just an example, but what kinds of situations would you really even need to use Unsafe/Fixed code for anything? Or is this poor web developer messing with something above his head?
It's useful for interop with unmanaged code. Any pointers passed to unmanaged functions need to be fixed (aka. pinned) to prevent the garbage collector from relocating the underlying memory. If you are using P/Invoke, then the default marshaller will pin objects for you. Sometimes it's necessary to perform custom marshalling, and sometimes it's necessary to pin an object for longer than the duration of a single P/Invoke call.
I've used unsafe-blocks to manipulate Bitmap-data. Raw pointer-access is significantly faster than SetPixel/GetPixel. ``` unsafe { BitmapData bmData = bm.LockBits(...) byte *bits = (byte*)pixels.ToPointer(); // Do stuff with bits } ``` "fixed" and "unsafe" is typically used when doing interop, or when extra performance is required. Ie. String.CopyTo() uses unsafe and fixed in its implementation.
C# Unsafe/Fixed Code
[ "", "c#", ".net", "unsafe", "fixed", "" ]
Is there a way to get the tests inside of a `TestCase` to run in a certain order? For example, I want to separate the life cycle of an object from creation to use to destruction but I need to make sure that the object is set up first before I run the other tests.
Maybe there is a design problem in your tests. Usually each test must not depend on any other tests, so they can run in any order. Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests. Can you be more specific about why you need the same object for N tests?
PHPUnit supports test dependencies via the [@depends](https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.test-dependencies) annotation. Here is an example from the documentation where tests will be run in an order that satisfies dependencies, with each dependent test passing an argument to the next: ``` class StackTest extends PHPUnit_Framework_TestCase { public function testEmpty() { $stack = array(); $this->assertEmpty($stack); return $stack; } /** * @depends testEmpty */ public function testPush(array $stack) { array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertNotEmpty($stack); return $stack; } /** * @depends testPush */ public function testPop(array $stack) { $this->assertEquals('foo', array_pop($stack)); $this->assertEmpty($stack); } } ``` However, it's important to note that tests with unresolved dependencies will *not* be executed (desirable, as this brings attention quickly to the failing test). So, it's important to pay close attention when using dependencies.
Run PHPUnit Tests in Certain Order
[ "", "php", "unit-testing", "phpunit", "" ]
I have recently written an application(vb.net) that stores and allows searching for old council plans. Now while the application works well, the other day I was having a look at the routine that I use to generate the SQL string to pass the database and frankly, it was bad. I was just posting a question here to see if anyone else has a better way of doing this. What I have is a form with a bunch of controls ranging from text boxes to radio buttons, each of these controls are like database filters and when the user hits search button, a SQL string(I would really like it to be a LINQ query because I have changed to LINQ to SQL) gets generated from the completed controls and run. The problem that I am having is matching each one of these controls to a field in the database and generating a LINQ query efficiently without doing a bunch of "if ...then...else." statements. In the past I have just used the tag property on the control to link to control to a field name in the database. I'm sorry if this is a bit confusing, its a bit hard to describe. Just throwing it out there to see if anyone has any ideas. Thanks Nathan
When programming complex ad-hoc query type things, attributes can be your best friend. Take a more declarative approach and decorate your classes, interfaces, and/or properties with some custom attributes, then write some generic "glue" code that binds your UI to your model. This will allow your model and presentation to be flexible, without having to change 1000s of lines of controller logic. In fact, this is precisely how Microsoft build the Visual Studio "Properties" page. You may even be able use Microsoft's "EnvDTE.dll" in your product depending on the requirements.
You could maybe wrap each control in a usercontrol that can take in IQueryable and tack on to the query if it is warranted. So your page code might go something like ``` var qry = from t in _db.TableName select t; ``` then pass qry to a method on each user control ``` IQueryable<t> addToQueryIfNeeded(IQueryable<t> qry) { if(should be added) return from t in qry where this == that select t; else return qry } ``` then after you go through each control your query would be complete and then you can .ToList() it. A cool thing about LINQ is nothing happens until you .ToList() or .First() it.
Generate LINQ query from multiple controls
[ "", "sql", "linq", "" ]
Simply, are there any Java Developer specific Linux distros?
A real Sun geek would chime in here about the virtues of using Solaris as a Java development platform, but I am much more ambivalent. Developing with Java is about the same on any linux distro; you are going to wind up having to install the JDK and tools of your choosing (Eclipse, Sun Studio, Tomcat, etc) so you may as well choose a distro on other criteria... perhaps how comfortable you are with it, how easy package management is, and if the look & feel suit your development habits are all big factors. So, to answer your question more directly, a Java developer would do well with any major linux distro that they are comfortable with using in general. If you want some Java goodness out of the box, Fedora 9 and Ubuntu 8.04 have OpenJDK (and NetBeans) according to [a recent announcement](http://www.vnunet.com/vnunet/news/2215568/open-source-java-added-linux).
Dont listen to any of these noobs suggesting one distro over another. Java is Java and just about all distros can install java as such: ``` [package manager command to install] jdk ``` If the question was about creating RPM's, then obviously RH/CentOS/Fedora would be desirable over deb distros, source distros, or whatever other format you love. However, due to the nature of Java, a specific distro to use is only relevant if the OP cant formulate their own opinion and must follow whatever other people are doing. To reiterate *There is no java distro* , use whatever will have you hit the ground running. ``` // begin hypocritical personal recomendation ``` ... that being said ... I *personally* use Archlinux. Archlinux works on rolling releases so it is more likely to have a more recent JDK version then the "sudo apt-get dist-upgrade && sleep 6 months" distros of the world. ``` // end hypocritical personal recomendation ``` Also, I am fully prepared to get downvoted, but please, leave me above 50 so i can comment still, thanks!
Linux distros for Java Development
[ "", "java", "linux", "distro", "" ]
What does the option “convert to web application” do if I select it in visual studio? If I do convert my site to a web application what are the advantages? Can I go back?
Well, it converts your web site to a web application project. As for the advantages, here is some further reading: MSDN comparison -- [Comparing Web Site Projects and Web Application Projects](http://msdn.microsoft.com/en-us/library/aa730880(VS.80).aspx#wapp_topic5) Webcast on ASP.NET -- [Web Application Projects vs. Web Site Projects in Visual Studio 2008](http://www.asp.net/LEARN/webcasts/webcast-236.aspx) *"In this webcast, by request, we examine the differences between web application projects and web site projects in Microsoft Visual Studio 2008. We focus specifically on the reasons you would choose one over the other and explain how to make informed decisions when creating a Web solution*" The primary difference (to me) between a web application project and a web site is how things gets compiled. In web sites each page has its code-behind compiled into a separate library, whereas in web applications all code-behind gets compiled into a single library. There are advantages and disadvantages to both, it really depends. It's also often a matter of [opinion](http://blog.madskristensen.dk/post/Web-Application-Projects-vs-Web-Site-Projects.aspx).
[Also Answered Here](https://stackoverflow.com/questions/43019/what-does-vs-2008s-convert-to-website-mean) so go vote that answer up, not this one. **Don't give me credit** > There are two types of web applications in ASP.NET: The Web Site and Web Application Project. The difference between the two are discussed here: > > [Difference between web site and web applications in Visual Studio 2005](http://www.dotnetspider.com/resources/1520-Difference-between-web-site-web-application.aspx) > > Convert to Website allows you to convert a Web Application Project to a Web Site. > > Visual Studio 2003 used the Web Application Project style, but initially VS2005 only supported web sites. VS2005 SP1 brought back Web Applications. > > If you don't want to convert your project to a web site, apply SP1 if you're using VS2005. VS2008 can support either.
What does the option "convert to web application" do if I select it in visual studio?
[ "", "c#", "asp.net", "visual-studio", "" ]
Is there an incantation of mysqldump or a similar tool that will produce a piece of SQL2003 code to create and fill the same databases in an arbitrary SQL2003 compliant RDBMS? (The one I'm trying right now is MonetDB)
DDL statements are inherently database-vendor specific. Although they have the same basic structure, each vendor has their own take on how to define types, indexes, constraints, etc. DML statements on the other hand are fairly portable. Therefore I suggest: * Dump the database without any data (mysqldump --no-data) to get the schema * Make necessary changes to get the schema loaded on the other DB - these need to be done by hand (but some search/replace may be possible) * Dump the data with extended inserts off and no create table (--extended-insert=0 --no-create-info) * Run the resulting script against the other DB. This should do what you want. However, when porting an application to a different database vendor, many other things will be required; moving the schema and data is the easy bit. Checking for bugs introduced, different behaviour and performance testing is the hard bit. At the very least test every single query in your application for validity on the new database. Ideally do a lot more.
This one is kind of tough. Unless you've got a very simple DB structure with vanilla types (varchar, integer, etc), you're probably going to get the best results writing a migration tool. In a language like Perl (via the DBI), this is pretty straight-forward. The program is basically an echo loop that reads from one database and inserts into the other. There are examples of this sort of code that Google knows about. Aside from the obvious problem of moving the data is the more subtle problem of how some datatypes are represented. For instance, MS SQL's datetime field is not in the same format as MySQL's. Other datatypes like BLOBs may have a different capacity in one RDBMs than in another. You should make sure that you understand the datatype definitions of the target DB system very well before porting. The last problem, of course, is getting application-level SQL statements to work against the new system. In my work, that's by far the hardest part. Date math seems especially DB-specific, while annoying things like quoting rules are a constant source of irritation. Good luck with your project.
Migrating from MySQL to arbitrary standards-compliant SQL2003 server
[ "", "sql", "mysql", "" ]
I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete. Any suggestions would be much appreciated.
Assuming this is running on a Linux machine, I've always handled it like this: ``` exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile)); ``` This launches the command `$cmd`, redirects the command output to `$outputfile`, and writes the process id to `$pidfile`. That lets you easily monitor what the process is doing and if it's still running. ``` function isRunning($pid){ try{ $result = shell_exec(sprintf("ps %d", $pid)); if( count(preg_split("/\n/", $result)) > 2){ return true; } }catch(Exception $e){} return false; } ```
Write the process as a server-side script in whatever language (php/bash/perl/etc) is handy and then call it from the process control functions in your php script. The function probably detects if standard io is used as the output stream and if it is then that will set the return value..if not then it ends ``` proc_close( proc_open( "./command --foo=1 &", array(), $foo ) ); ``` I tested this quickly from the command line using "sleep 25s" as the command and it worked like a charm. ([Answer found here](http://ca.php.net/manual/en/function.exec.php))
php execute a background process
[ "", "php", "" ]
I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debugging information. I'm currently planning to fork objdump, passing in a list of hex addresses and parsing the output to get function names and source line numbers. I have compiled an objdump with support for MIPS binaries, and it is working. I'd prefer to have a package allowing me to look things up natively from the Python code without forking another process. I can find no mention of libdwarf, libelf, or libbfd on python.org, nor any mention of python on dwarfstd.org. Is there a suitable module available somewhere?
Please check [pyelftools](https://github.com/eliben/pyelftools) - a new pure Python library meant to do this.
You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/): ``` >>> from bintools.dwarf import DWARF >>> dwarf = DWARF('test/test') >>> dwarf.get_loc_by_addr(0x8048475) ('/home/emilmont/Workspace/dbg/test/main.c', 36, 0) ```
Analizing MIPS binaries: is there a Python library for parsing binary data?
[ "", "python", "x86", "mips", "elf", "dwarf", "" ]
I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better? When I build the site (using [Web Deployment Projects](http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx)), can I automate part of the build so that it does not copy certain folders from the project into the Release folder? For instance, I have folders with local search indexes, images and other content part of the folder, but I never need or upload those when deploying the project. I'm also looking toward this type of solution to automatically increment build and version numbers.
Here's an example of a Web Deployment Project scripting this sort of task in the .wdproj file: ``` <Target Name="AfterBuild"> <!-- ============================ Script Compression============================ --> <MakeDir Directories="$(OutputPath)\compressed" /> <Exec Command="java -jar c:\yuicompressor-2.2.5\build\yuicompressor-2.2.5.jar --charset UTF-8 styles.css -o compressed/styles.css" WorkingDirectory="$(OutputPath)" /> <Exec Command="move /Y .\compressed\* .\" WorkingDirectory="$(OutputPath)" /> <RemoveDir Directories="$(OutputPath)\sql" /> <Exec Command="c:\7zip-4.4.2\7za.exe a $(ZipName).zip $(OutputPath)\*" /> </Target> ``` This would allow you to delete a folder. (I suspect that if you wanted to not have the folder copy over *at all*, the solution file would be the place to specify that, though I haven't had to use that.)
MaseBase, you can use [Web Deployment Projects](http://weblogs.asp.net/scottgu/archive/2005/11/06/429723.aspx) to build and package Web Sites. We do that all the time for projects with a web application aspect. After you assign a WDP to a Web Site, you can open up the **.wdproj** file as plain-text XML file. At the end is a commented section of MSBuild targets that represent the sequence of events that fire during a build process. ``` <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.WebDeployment.targets. <Target Name="BeforeBuild"> </Target> <Target Name="BeforeMerge"> </Target> <Target Name="AfterMerge"> </Target> <Target Name="AfterBuild"> </Target> --> ``` You can uncomment the targets you want (e.g. "AfterBuild") and insert the necessary tasks there to carry out your repeated post-build activities.
How do I automate repetitive tasks post-build?
[ "", "c#", "asp.net", "visual-studio-2005", "msbuild", "web-deployment-project", "" ]
I am calling a vendor's Java API, and on some servers it appears that the JVM goes into a low priority polling loop after logging into the API (CPU at 100% usage). The same app on other servers does not exhibit this behavior. This happens on WebSphere and Tomcat. The environment is tricky to set up so it is difficult to try to do something like profiling within Eclipse. Is there a way to profile (or some other method of inspecting) an existing Java app running in Tomcat to find out what methods are being executed while it's in this spinwait kind of state? The app is only executing one method when it gets in this state (vendor's method). Vendor can't replicate the behavior (of course). --- Update: Using JConsole I was able to determine who was running and what they were doing. It took me a few hours to then figure out why it was doing it. The problem ended up being that the vendor's API jar that was being used did not match exactly to the the database configuration that it was using. It was defaulting to having tracing and performance monitoring enabled on the servers that had the slight mis-match in configuration. I used a different jar and all is well. So thanks, Joshua, for your answer. JConsole was extremely easy to setup and use to monitor an existing application. @Cringe - I did some experimenting with some of the options you suggested. I had some problems with getting JProfiler set up, it looks good (but pricey). Going forward I went ahead and added the Eclipse Profiler plugin and I'll be looking over the different open source profilers to compare functionality.
If you are using Java 5 or later, you can connect to your application using [jconsole](http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html) to view all running threads. jstack also will do a stack dump. I think this should still work even inside a container like Tomcat. Both of these tools are included with JDK5 and later (I assume the process needs to be at least Java 5, though I could be wrong) Update: It's also worth noting that starting with JDK 1.6 update 7 there is now a bundled profiler called [VisualVM](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/) which can be launched with 'jvisualvm'. It looks like it is a [java.net project](http://visualvm.java.net/), so additional info may be available at that page. I haven't used this yet but it looks useful for more serious analysis. Hope that helps
Facing the same problem I used [YourKit profiler](http://www.yourkit.com/overview/index.jsp). It's loader doesn't activate unless you actually connect to it (though it does open a port to listen for connections). The profiler itself has a nice "get amount of time spent in each method" while working in it's less obtrusive mode. Another way is to detect CPU load (via JNI, so you'd need an external library for this) in a "watchdog" thread with highest priority and start logging all threads when the CPU is high enough for a long enough time. You might find [this article](http://www.javaworld.com/javaworld/javaqa/2002-11/01-qa-1108-cpu.html) enlightining.
If you have a Java application that is consuming CPU when it isn't doing anything, how do you determine what it is doing?
[ "", "java", "profiling", "" ]
How do I multiply 10 to an `Integer` object and get back the `Integer` object? I am looking for the neatest way of doing this. I would probably do it this way: Get int from `Integer` object, multiply it with the other int and create another Integer object with this int value. Code will be something like ... ``` integerObj = new Integer(integerObj.intValue() * 10); ``` But, I saw a code where the author is doing it this way: Get the `String` from the `Integer` object, concatenate "0" at the end and then get `Integer` object back by using `Integer.parseInt` The code is something like this: ``` String s = integerObj + "0"; integerObj = Integer.parseInt(s); ``` Is there any merit in doing it either way? And what would be the most efficient/neatest way in general and in this case?
With Java 5's [autoboxing](http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html), you can simply do: ``` Integer a = new Integer(2); // or even just Integer a = 2; a *= 10; System.out.println(a); ```
The string approach is amusing, but almost certainly a bad way to do it. Getting the int value of an Integer, and creating a new one will be very fast, where as parseInt would be fairly expensive to call. Overall, I'd agree with your original approach (which, as others have pointed out, can be done without so much clutter if you have autoboxing as introduced in Java 5).
How to multiply 10 to an "Integer" object in Java?
[ "", "java", "types", "casting", "" ]
Haven't fired up reflector to look at the difference but would one expect to see the exact same compiled code when comparing `Func<T, bool>` vs. `Predicate<T>` I would imagine there is no difference as both take a generic parameter and return bool?
They share the same signature, but they're still different types.
Robert S. is completely correct; for example:- ``` class A { static void Main() { Func<int, bool> func = i => i > 100; Predicate<int> pred = i => i > 100; Test<int>(pred, 150); Test<int>(func, 150); // Error } static void Test<T>(Predicate<T> pred, T val) { Console.WriteLine(pred(val) ? "true" : "false"); } } ```
Isn't Func<T, bool> and Predicate<T> the same thing after compilation?
[ "", "c#", ".net", "predicate", "func", "" ]
I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example?
I'm not quite sure what an "out-of-place" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets. In our projects we move the compiled dlls into lib folders and put the files into the proper locations after a build is complete. To do this we've created a custom build .target file that creates the `Target`'s, `Property`'s, and `ItemGroup`'s that we then use to populate our external output folder. Our custom targets file looks a bit like this: ``` <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <ProjectName>TheProject</ProjectName> <ProjectDepthPath>..\..\</ProjectDepthPath> <ProjectsLibFolder>..\..\lib\</ProjectsLibFolder> <LibFolder>$(ProjectsLibFolder)$(ProjectName)\$(Configuration)\</LibFolder> </PropertyGroup> <Target Name="DeleteLibFiles"> <Delete Files="@(LibFiles-> '$(ProjectDepthPath)$(LibFolder)%(filename)%(extension)')" TreatErrorsAsWarnings="true" /> </Target> <Target Name="CopyLibFiles"> <Copy SourceFiles="@(LibFiles)" DestinationFolder="$(ProjectDepthPath)$(LibFolder)" SkipUnchangedFiles="True" /> </Target> <ItemGroup> <LibFiles Include=" "> <Visible>false</Visible> </LibFiles> </ItemGroup> </Project> ``` The .csproj file in Visual Studio then integrates with this custom target file: ``` <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" ... > ... <Import Project="..\..\..\..\build\OurBuildTargets.targets" /> <ItemGroup> <LibFiles Include="$(OutputPath)$(AssemblyName).dll"> <Visible>false</Visible> </LibFiles> </ItemGroup> <Target Name="BeforeClean" DependsOnTargets="DeleteLibFiles" /> <Target Name="AfterBuild" DependsOnTargets="CopyLibFiles" /> </Project> ``` In a nutshell, this build script first tells MSBuild to load our custom build script, then adds the compiled file to the `LibFiles` ItemGroup, and lastly ties our custom build targets, `DeleteLibFiles` and `CopyLibFiles`, into the build process. We set this up for each project in our solution so only the files that are updated get deleted/copied and each project is responsible for it's own files (dlls, images, etc). I hope this helps. I apologize if I misunderstood what you mean by out-of-place build system and this is completely useless to you!
> Is there a way I can define a macro for a directory and use it in the output path Have you looked at the pre-build and post-build events of a project?
Out-of-place builds with C#
[ "", "c#", "msbuild", "build-process", "" ]
How do you set the Windows time zone on the local machine programmatically in C#? Using an interactive tool is not an option because the remote units have no user interface or users. The remote machine is running .NET 2.0 and Windows XP Embedded and a local app that communicates with a central server (via web service) for automated direction of its tasks. We can deliver a command to synch to a certain time/zone combination, but what code can be put in the local app to accomplish the change? The equipment is not imaged for specific locations before installation, so in order to use any equipment at any location, we have to be able to synch this information.
[SetTimeZoneInformation](http://msdn.microsoft.com/en-us/library/ms724944.aspx) should do what you need. You'll need to use [P/Invoke](http://pinvoke.net/default.aspx/kernel32/SetTimeZoneInformation.html) to get at it. Note also that you'll need to possess and enable the SE\_TIME\_ZONE\_NAME privilege.
This is not working in Windows 7. I have tried with the following environment windows 7 VSTS-2008 It is opening Change Time Zone Window as we do it manually
Setting time zone remotely in C#
[ "", "c#", ".net", "windows", "localization", "timezone", "" ]
Does anybody have experience working with PHP accelerators such as [MMCache](http://turck-mmcache.sourceforge.net/) or [Zend Accelerator](http://www.zend.com/en/)? I'd like to know if using either of these makes PHP comparable to *faster* web-technologies. Also, are there trade offs for using these?
Note that Zend Optimizer and MMCache (or similar applications) are totally different things. While Zend Optimizer tries to optimize the program opcode MMCache will cache the scripts in memory and reuse the precompiled code. I did some benchmarks some time ago and you can find the [results](http://blogs.interdose.com/dominik/2008/04/11/benchmarking-php-eaccelerator-und-andere-opcode-caches/) in my blog (in German though). The basic results: Zend Optimizer alone didn't help at all. Actually my scripts were slower than without optimizer. When it comes to caches: \* fastest: [eAccelerator](http://eaccelerator.net/) \* [XCache](http://xcache.lighttpd.net/) \* [APC](http://www.php.net/manual/en/book.apc.php) And: You DO want to install a opcode cache! For example: [alt text http://blogs.interdose.com/dominik/wp-content/uploads/2008/04/opcode\_wordpress.png](http://blogs.interdose.com/dominik/wp-content/uploads/2008/04/opcode_wordpress.png) This is the duration it took to call the wordpress homepage 10.000 times. *Edit:* BTW, eAccelerator contains an optimizer itself.
MMCache has been deprecated. I recommend either <http://pecl.php.net/package/APC> or <http://xcache.lighttpd.net/>, both of which also give you variable storage (like Memcache).
Is using PHP accelerators such as MMCache or Zend Accelerator making PHP faster?
[ "", "php", "caching", "zend-optimizer", "" ]
I'm working on a program that will be processing files that could potentially be 100GB or more in size. The files contain sets of variable length records. I've got a first implementation up and running and am now looking towards improving performance, particularly at doing I/O more efficiently since the input file gets scanned many times. Is there a rule of thumb for using `mmap()` versus reading in blocks via C++'s `fstream` library? What I'd like to do is read large blocks from disk into a buffer, process complete records from the buffer, and then read more. The `mmap()` code could potentially get very messy since `mmap`'d blocks need to lie on page sized boundaries (my understanding) and records could potentially lie across page boundaries. With `fstream`s, I can just seek to the start of a record and begin reading again, since we're not limited to reading blocks that lie on page sized boundaries. How can I decide between these two options without actually writing up a complete implementation first? Any rules of thumb (e.g., `mmap()` is 2x faster) or simple tests?
I was trying to find the final word on mmap / read performance on Linux and I came across a nice post ([link](http://marc.info/?l=linux-kernel&m=95496636207616&w=2)) on the Linux kernel mailing list. It's from 2000, so there have been many improvements to IO and virtual memory in the kernel since then, but it nicely explains the reason why `mmap` or `read` might be faster or slower. * A call to `mmap` has more overhead than `read` (just like `epoll` has more overhead than `poll`, which has more overhead than `read`). Changing virtual memory mappings is a quite expensive operation on some processors for the same reasons that switching between different processes is expensive. * The IO system can already use the disk cache, so if you read a file, you'll hit the cache or miss it no matter what method you use. However, * Memory maps are generally faster for random access, especially if your access patterns are sparse and unpredictable. * Memory maps allow you to *keep* using pages from the cache until you are done. This means that if you use a file heavily for a long period of time, then close it and reopen it, the pages will still be cached. With `read`, your file may have been flushed from the cache ages ago. This does not apply if you use a file and immediately discard it. (If you try to `mlock` pages just to keep them in cache, you are trying to outsmart the disk cache and this kind of foolery rarely helps system performance). * Reading a file directly is very simple and fast. The discussion of mmap/read reminds me of two other performance discussions: * Some Java programmers were shocked to discover that nonblocking I/O is often slower than blocking I/O, which made perfect sense if you know that nonblocking I/O requires making more syscalls. * Some other network programmers were shocked to learn that `epoll` is often slower than `poll`, which makes perfect sense if you know that managing `epoll` requires making more syscalls. **Conclusion:** Use memory maps if you access data randomly, keep it around for a long time, or if you know you can share it with other processes (`MAP_SHARED` isn't very interesting if there is no actual sharing). Read files normally if you access data sequentially or discard it after reading. And if either method makes your program less complex, do *that*. For many real world cases there's no sure way to show one is faster without testing your actual application and NOT a benchmark. (Sorry for necro'ing this question, but I was looking for an answer and this question kept coming up at the top of Google results.)
There are lots of good answers here already that cover many of the salient points, so I'll just add a couple of issues I didn't see addressed directly above. That is, this answer shouldn't be considered a comprehensive of the pros and cons, but rather an addendum to other answers here. ## mmap seems like magic Taking the case where the file is already fully cached1 as the baseline2, `mmap` might seem pretty much like *magic*: 1. `mmap` only requires 1 system call to (potentially) map the entire file, after which no more system calls are needed. 2. `mmap` doesn't require a copy of the file data from kernel to user-space. 3. `mmap` allows you to access the file "as memory", including processing it with whatever advanced tricks you can do against memory, such as compiler auto-vectorization, [SIMD](https://en.wikipedia.org/wiki/SIMD) intrinsics, prefetching, optimized in-memory parsing routines, OpenMP, etc. In the case that the file is already in the cache, it seems impossible to beat: you just directly access the kernel page cache as memory and it can't get faster than that. Well, it can. ## mmap is not actually magic because... ### mmap still does per-page work A primary hidden cost of `mmap` vs [`read(2)`](http://man7.org/linux/man-pages/man2/read.2.html) (which is really the comparable OS-level syscall for *reading blocks*) is that with `mmap` you'll need to do "some work" for every 4K page accessed in a new mapping, even though it might be hidden by the page-fault mechanism. For a example a typical implementation that just `mmap`s the entire file will need to fault-in so 100 GB / 4K = 25 million faults to read a 100 GB file. Now, these will be [*minor faults*](https://en.wikipedia.org/wiki/Page_fault#Minor), but 25 million page faults is still not going to be super fast. The cost of a minor fault is probably in the 100s of nanos in the best case. ### mmap relies heavily on TLB performance Now, you can pass `MAP_POPULATE` to `mmap` to tell it to set up all the page tables before returning, so there should be no page faults while accessing it. Now, this has the little problem that it also reads the entire file into RAM, which is going to blow up if you try to map a 100GB file - but let's ignore that for now3. The kernel needs to do *per-page work* to set up these page tables (shows up as kernel time). This ends up being a major cost in the `mmap` approach, and it's proportional to the file size (i.e., it doesn't get relatively less important as the file size grows)4. Finally, even in user-space accessing such a mapping isn't exactly free (compared to large memory buffers not originating from a file-based `mmap`) - even once the page tables are set up, each access to a new page is going to, conceptually, incur a TLB miss. Since `mmap`ing a file means using the page cache and its 4K pages, you again incur this cost 25 million times for a 100GB file. Now, the actual cost of these TLB misses depends heavily on at least the following aspects of your hardware: (a) how many 4K TLB enties you have and how the rest of the translation caching works performs (b) how well hardware prefetch deals with with the TLB - e.g., can prefetch trigger a page walk? (c) how fast and how parallel the page walking hardware is. On modern high-end x86 Intel processors, the page walking hardware is in general very strong: there are at least 2 parallel page walkers, a page walk can occur concurrently with continued execution, and hardware prefetching can trigger a page walk. So the TLB impact on a *streaming* read load is fairly low - and such a load will often perform similarly regardless of the page size. Other hardware is usually much worse, however! ## read() avoids these pitfalls The [`read()`](https://linux.die.net/man/2/read) syscall, which is what generally underlies the "block read" type calls offered e.g., in C, C++ and other languages has one primary disadvantage that everyone is well-aware of: * Every `read()` call of N bytes must copy N bytes from kernel to user space. On the other hand, it avoids most the costs above - you don't need to map in 25 million 4K pages into user space. You can usually `malloc` a single buffer small buffer in user space, and re-use that repeatedly for all your `read` calls. On the kernel side, there is almost no issue with 4K pages or TLB misses because all of RAM is usually linearly mapped using a few very large pages (e.g., 1 GB pages on x86), so the underlying pages in the page cache are covered very efficiently in kernel space. So basically you have the following comparison to determine which is faster for a single read of a large file: **Is the extra per-page work implied by the `mmap` approach more costly than the per-byte work of copying file contents from kernel to user space implied by using `read()`?** On many systems, they are actually approximately balanced. Note that each one scales with completely different attributes of the hardware and OS stack. In particular, the `mmap` approach becomes relatively faster when: * The OS has fast minor-fault handling and especially minor-fault bulking optimizations such as fault-around. * The OS has a good `MAP_POPULATE` implementation which can efficiently process large maps in cases where, for example, the underlying pages are contiguous in physical memory. * The hardware has strong page translation performance, such as large TLBs, fast second level TLBs, fast and parallel page-walkers, good prefetch interaction with translation and so on. ... while the `read()` approach becomes relatively faster when: * The `read()` syscall has good copy performance. E.g., good `copy_to_user` performance on the kernel side. * The kernel has an efficient (relative to userland) way to map memory, e.g., using only a few large pages with hardware support. * The kernel has fast syscalls and a way to keep kernel TLB entries around across syscalls. The hardware factors above vary *wildly* across different platforms, even within the same family (e.g., within x86 generations and especially market segments) and definitely across architectures (e.g., ARM vs x86 vs PPC). The OS factors keep changing as well, with various improvements on both sides causing a large jump in the relative speed for one approach or the other. A recent list includes: * Addition of fault-around, described above, which really helps the `mmap` case without `MAP_POPULATE`. * Addition of fast-path `copy_to_user` methods in `arch/x86/lib/copy_user_64.S`, e.g., using `REP MOVQ` when it is fast, which really help the `read()` case. ## Update after Spectre and Meltdown The mitigations for the Spectre and Meltdown vulnerabilities considerably increased the cost of a system call. On the systems I've measured, the cost of a "do nothing" system call (which is an estimate of the pure overhead of the system call, apart from any actual work done by the call) went from about 100 ns on a typical modern Linux system to about 700 ns. Furthermore, depending on your system, the [page-table isolation](https://en.wikipedia.org/wiki/Kernel_page-table_isolation) fix specifically for Meltdown can have additional downstream effects apart from the direct system call cost due to the need to reload TLB entries. All of this is a relative disadvantage for `read()` based methods as compared to `mmap` based methods, since `read()` methods must make one system call for each "buffer size" worth of data. You can't arbitrarily increase the buffer size to amortize this cost since using large buffers usually performs worse since you exceed the L1 size and hence are constantly suffering cache misses. On the other hand, with `mmap`, you can map in a large region of memory with `MAP_POPULATE` and the access it efficiently, at the cost of only a single system call. --- 1 This more-or-less also includes the case where the file wasn't fully cached to start with, but where the OS read-ahead is good enough to make it appear so (i.e., the page is usually cached by the time you want it). This is a subtle issue though because the way read-ahead works is often quite different between `mmap` and `read` calls, and can be further adjusted by "advise" calls as described in 2. 2 ... because if the file is *not* cached, your behavior is going to be completely dominated by IO concerns, including how sympathetic your access pattern is to the underlying hardware - and all your effort should be in ensuring such access is as sympathetic as possible, e.g. via use of [`madvise`](http://man7.org/linux/man-pages/man2/madvise.2.html) or [`fadvise`](https://linux.die.net/man/2/fadvise) calls (and whatever application level changes you can make to improve access patterns). 3 You could get around that, for example, by sequentially `mmap`ing in windows of a smaller size, say 100 MB. 4 In fact, it turns out the `MAP_POPULATE` approach is (at least one some hardware/OS combination) only slightly faster than not using it, probably because the kernel is using [faultaround](https://lwn.net/Articles/588802/) - so the actual number of minor faults is reduced by a factor of 16 or so.
mmap() vs. reading blocks
[ "", "c++", "file-io", "fstream", "mmap", "" ]
After cleaning a folder full of HTML files with TIDY, how can the tables content be extracted for further processing?
Depends on what sort of processing you want to do. You can tell Tidy to generate XHTML, which is a type of XML, which means you can use all the usual XML tools like XSLT and XQuery on the results. If you want to process them in Microsoft Excel, then you should be able to slice the table out of the HTML and put it in a file, then open that file in Excel: it will happily convert an HTML table in to a spreadsheet page. You could then save it as CSV or as an Excel workbook etc. (You can even use this on a web server -- return an HTML table but set the `Content-Type` header to `application/ms-vnd.excel`: Excel will open and import the table and turn it in to a spreadsheet.) If you want CSV to feed in to a database then you could go via Excel as before, or if you want to automate the process, you could write a program that uses the XML-navigating API of your choice to iterate of the table rows and save them as CSV. Python's Elementtree and CSV modules would make this pretty easy.
I've used BeautifulSoup for such things in the past with great success.
What's the best way to extract table content from a group of HTML files?
[ "", "java", "html", "excel", "csv", "extract", "" ]
When should I **not** use the ThreadPool in .Net? It looks like the best option is to use a ThreadPool, in which case, why is it not the only option? What are your experiences around this?
The only reason why I wouldn't use the `ThreadPool` for cheap multithreading is if I need to… 1. interract with the method running (e.g., to kill it) 2. run code on a [STA thread](http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx "Single-Threaded Apartment thread; see e.g. this MSDN reference page for STAThreadAttribute") (this happened to me) 3. keep the thread alive after my application has died (`ThreadPool` threads are background threads) 4. in case I need to change the priority of the Thread. We can not change priority of threads in ThreadPool which is by default Normal. > **P.S.:** The MSDN article [*"The Managed Thread Pool"*](http://msdn.microsoft.com/en-us/library/0ka9477y.aspx "The Managed Thread Pool (page on MSDN)") contains a section titled, *"When Not to Use Thread Pool Threads"*, with a very similar but slightly more complete list of possible reasons for not using the thread pool. There are lots of reasons why you would need to skip the `ThreadPool`, but if you don't know them then the `ThreadPool` should be good enough for you. Alternatively, look at the new [Parallel Extensions Framework](https://learn.microsoft.com/en-us/visualstudio/extensibility/debugger/parallel-extension-internals-for-the-dotnet-framework), which has some neat stuff in there that may suit your needs without having to use the `ThreadPool`.
@Eric, I'm going to have to agree with Dean. Threads are expensive. You can't assume that your program is the only one running. When everyone is greedy with resources, the problem multiplies. > I prefer to create my threads manually and control them myself. It keeps the code very easy to understand. That's fine when it's appropriate. If you need a bunch of worker threads, though, all you've done is make your code more complicated. Now you have to write code to manage them. If you just used a thread pool, you'd get all the thread management for free. And the thread pool provided by the language is very likely to be more robust, more efficient, and less buggy than whatever you roll for yourself. > ``` > Thread t = new Thread(new ThreadStart(DoSomething)); > t.Start(); > t.Join(); > ``` I hope that you would normally have some additional code in between `Start()` and `Join()`. Otherwise, the extra thread is useless, and you're wasting resources for no reason. > People are way too afraid of the resources used by threads. I've never seen creating and starting a thread to take more than a millisecond. There is no hard limit on the number of threads you can create. RAM usage is minimal. Once you have a few hundred threads, CPU becomes an issue because of context switches, so at that point you might want to get fancy with your design. A millisecond is a *long* time on modern hardware. That's 3 million cycles on a 3GHz machine. And again, you aren't the only one creating threads. Your threads compete for the CPU along with every other program's threads. If you use not-quite-too-many threads, and so does another program, then together you've used too many threads. > Seriously, don't make life more complex than it needs to be. Don't use the thread pool unless you need something very specific that it offers. Indeed. Don't make life more complex. If your program needs multiple worker threads, don't reinvent the wheel. Use the thread pool. That's why it's there. Would you roll your own string class?
When should I not use the ThreadPool in .Net?
[ "", "c#", ".net", "multithreading", "design-decisions", "" ]
In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using `System.Windows.Forms.FolderBrowserDialog` but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path). I'd like something more like the `System.Windows.Forms.OpenFileDialog`, but for folders instead of files. What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it.
Don't create it yourself! It's been done. You can use [FolderBrowserDialogEx](http://dotnetzip.codeplex.com/SourceControl/changeset/view/29832#432677) - a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better. Full Source code. Free. MS-Public license. ![FolderBrowserDialogEx](https://i.stack.imgur.com/V1caf.png) Code to use it: ``` var dlg1 = new Ionic.Utils.FolderBrowserDialogEx(); dlg1.Description = "Select a folder to extract to:"; dlg1.ShowNewFolderButton = true; dlg1.ShowEditBox = true; //dlg1.NewStyle = false; dlg1.SelectedPath = txtExtractDirectory.Text; dlg1.ShowFullPathInEditBox = true; dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer; // Show the FolderBrowserDialog. DialogResult result = dlg1.ShowDialog(); if (result == DialogResult.OK) { txtExtractDirectory.Text = dlg1.SelectedPath; } ```
Unfortunately there are no dialogs other than FolderBrowserDialog for folder selection. You need to create this dialog yourself or use PInvoke.
Choosing a folder with .NET 3.5
[ "", "c#", ".net", "wpf", "winforms", "" ]
I have a piece of server-ish software written in Java to run on Windows and OS X. (It is not running on a server, but just a normal user's PC - something like a torrent client.) I would like the software to signal to the OS to keep the machine awake (prevent it from going into sleep mode) while it is active. Of course I don't expect there to be a cross platform solution, but I would love to have some very minimal C programs/scripts that my app can spawn to inform the OS to stay awake. Any ideas?
I use this code to keep my workstation from locking. It's currently only set to move the mouse once every minute, you could easily adjust it though. It's a hack, not an elegant solution. ``` import java.awt.*; import java.util.*; public class Hal{ public static void main(String[] args) throws Exception{ Robot hal = new Robot(); Random random = new Random(); while(true){ hal.delay(1000 * 60); int x = random.nextInt() % 640; int y = random.nextInt() % 480; hal.mouseMove(x,y); } } } ```
On Windows, use the [SystemParametersInfo](http://msdn.microsoft.com/en-us/library/ms724947.aspx) function. It's a Swiss army-style function that lets you get/set all sorts of system settings. To disable the screen shutting off, for instance: ``` SystemParametersInfo( SPI_SETPOWEROFFACTIVE, 0, NULL, 0 ); ``` Just be sure to set it back when you're done...
How do you keep the machine awake?
[ "", "java", "windows", "macos", "cross-platform", "operating-system", "" ]
I'm looking around for a Java [code signing](http://en.wikipedia.org/wiki/Code_signing) certificate so my Java applets don't throw up such scary security warnings. However, all the places I've found offering them charge (in my opinion) way too much, like over USD200 per year. While doing research, a code signing certificate seems almost exactly the same as an [SSL](http://en.wikipedia.org/wiki/SSL) certificate. The main question I have: is it possible to buy an SSL certificate, but use it to sign Java applets?
Short answer: No, they're different. Long answer: It's the same sort of certificate and it uses the same crypto software, but the certificate has flags indicating what it is allowed to be used for. Code signing and web server are different uses.
When I import a new CA certificate in Firefox (etc.) I have the option of choosing which certificate uses I trust: * Sign servers * Sign code (like your applet) * Sign email certificates So to me the answer is: Yes, they're the same. Furthermore, why not generate your own with [OpenSSL](http://en.wikipedia.org/wiki/OpenSSL) (man openssl, man x509, man req, etc. on Unix)? Do you want to just quiet down the warnings *or* do you want *other* people whom you've never met to trust your code? If you don't need other users to chain trust to the anchor CA's bundled with their browser, OS, etc., then use OpenSSL to generate your own. And ask "How do I use OpenSSL to generate my own certificates?" if the latter is your choice.
Are Java code signing certificates the same as SSL certificates?
[ "", "java", "ssl", "certificate", "code-signing", "" ]
any idea how if the following is possible in PHP as a single line ?: ``` <?php $firstElement = functionThatReturnsAnArray()[0]; ``` ... It doesn't seem to 'take'. I need to do this as a 2-stepper: ``` <?php $allElements = functionThatReturnsAnArray(); $firstElement = $allElements[0]; ``` ... just curious - other languages I play with allow things like this, and I'm lazy enoug to miss this in PHP ... any insight appreciated ...
Try: ``` <?php $firstElement = reset(functionThatReturnsAnArray()); ``` If you're just looking for the first element of the array.
@Scott Reynen that's not true. This will work: ``` list(,,$thirdElement) = $myArray; ```
PHP: Can I reference a single member of an array that is returned by a function?
[ "", "php", "arrays", "function", "" ]
By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?
Sure there is. This is all you need to do: * Go to ``` File -> Settings -> Global Code Style -> General ``` * Disable the checkbox next to 'Use same settings for all file types' * The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.
In IntelliJ IDEA 10.0.3 it's File > Settings > Code Style > General
How do I change XML indentation in IntelliJ IDEA?
[ "", "java", "xml", "ide", "intellij-idea", "" ]
I'm a front-end developer and I was looking for opinions about the best all-round online documentation for javascript/css/html/xhtml/dom/browser quirks and support. I've tried Sitepoint, Quirksmode, W3Schools but all of these seem to be lacking in certain aspects and have been using them in combination.
I like gotapi.com (Update 2: Site is apparently offline -- Use another resource such as [MDN](https://developer.mozilla.org/en-US/)) **Update:** the original answer was from 2008 -- today I would say to check out [Mozilla Developer Network](https://developer.mozilla.org/en-US/) (as many others have also said).
I like Mozilla's references: <http://developer.mozilla.org/en/JavaScript> <http://developer.mozilla.org/en/DOM> These are not at all the one stop site you want, but they help me.
What is the best online javascript/css/html/xhtml/dom reference?
[ "", "javascript", "html", "css", "ajax", "xhtml", "" ]
Struts 1.3 application. Main website is NOT served by struts/Java. I need to forward the result of a struts action to a page in the website, that is outside of the struts context. Currently, I forward to a JSP in context and use a meta-refresh to forward to the real location. That seems kinda sucky. Is there a better way?
You can't "forward", in the strict sense. Just call `sendRedirect()` on the `HttpServletResponse` object in your `Action` class's `execute()` method and then, `return null`. Alternately, either call `setModule()` on the `ActionForward` object (that you are going to return) or set the path to an absolute URI.
I ended up doing response.sendRedirect().
Struts 1.3: forward outside the application context?
[ "", "java", "struts", "" ]
I have a few scripts on a site I recently started maintaining. I get those Object Not Found errors in IE6 (which Firefox fails to report in its Error Console?). What's the best way to debug these- any good cross-browser-compatible IDEs, or javascript debugging libraries of some sort?
There's no cross-browser JS debugger that I know of (because most browsers use different JS engines). For firefox, I'd definitely recommend firebug (<http://www.getfirebug.com>) For IE, the best I've found is Microsoft Script Debugger (<http://www.microsoft.com/downloads/details.aspx?familyid=2f465be0-94fd-4569-b3c4-dffdf19ccd99&displaylang=en>). If you have Office installed, you may also have Microsoft Script Editor installed. To use either of these, you need to turn on script debugging in IE. (uncheck Tools -> Internet Options -> Advanced -> Disable Script debugging).
You could also use [Firebug Lite](http://getfirebug.com/lite.html) - which will work in IE & Opera. It's an external lib that will help you track down problems. It's sometimes more convenient than dealing with the MS Script Debugger.
Cross-browser JavaScript debugging
[ "", "javascript", "" ]
I'm looking for a way to check within `pageLoad()` if this method is raised during load event because of a postback/async postback or because of being loaded and access the first time. This is similar to `Page.IsPostback` property within code behind page. TIA, Ricky
One way you could do that is to wire up an Application.Load handler in Application.Init, then have that handler unbind itself after running: ``` Sys.Application.add_init(AppInit); function AppInit() { Sys.Application.add_load(RunOnce); } function RunOnce() { // This will only happen once per GET request to the page. Sys.Application.remove_load(RunOnce); } ``` That will execute after Application.Init. It should be the last thing before pageLoad is called.
@Darren: Thanks for the answer. I had tried to create pageLoad with event argument [ApplicationLoadEventArgs](http://asp.net/AJAX/Documentation/Live/ClientReference/Sys/ApplicationLoadEventArgsClass/ApplicationLoadEventArgsIsPartialLoadProperty.aspx) as parameter (see below). However according to [this](http://msdn.microsoft.com/en-us/library/bb386417.aspx): *The load event is raised for all postbacks to the server, which includes asynchronous postbacks.* As you have indicated, the isPartialLoad property does not cover all postback scenarios. It'll be nice if the event argument also contain isPostback property. ``` function pageLoad(sender, arg) { if (!arg.get_isPartialLoad()) { //code to be executed only on the first load } } ``` @mmattax: I'm looking for property that can be called from client-side (javascript).
How to check if page is postback within reserved function pageLoad on ASP.NET AJAX
[ "", "javascript", "asp.net-ajax", "postback", "lifecycle", "" ]
I would like to intercept the event in a .NET Windows Forms TabControl when the user has changed tab by double-clicking the tab (instead of just single-clicking it). Do you have any idea of how I can do that?
The MouseDoubleClick event of the TabControl seems to respond just fine to double-clicking. The only additional step I would do is set a short timer after the TabIndexChanged event to track that a new tab has been selected and ignore any double-clicks that happen outside the timer. This will prevent double-clicking on the selected tab.
For some reason, MouseDoubleClick, as suggested by Jason Z is only firing when clicking on the tabs and clicking on the tab panel does not do anything, so that's exactly what I was looking for.
.NET : Double-click event in TabControl
[ "", "c#", ".net", "vb.net", "winforms", "tabcontrol", "" ]
First off, there's a bit of background to this issue available on my blog: * <http://www.codebork.com/coding/2008/06/25/message-passing-a-plug-framework.html> * <http://www.codebork.com/coding/2008/07/31/message-passing-2.html> I'm aware that the descriptions aren't hugely clear, so I'll try to summarise what I'm attempting as best I can here. The application is a personal finance program. Further background on the framework itself is available at the end of this post. There are a number of different types of plug-in that the framework can handle (e.g., accounts, export, reporting, etc.). However, I'm focussing on one particular class of plug-in, so-called data plug-ins, as it is this class that is causing me problems. I have one class of data plug-in for accounts, one for transactions, etc. I'm midway through a vast re-factoring that has left me with the following architecture for data plug-ins: * The data plug-in object (implementing intialisation, installation and plug-in metadata) [implements `IDataPlugin<FactoryType>`] * The data object (such as an account) [implements, e.g., `IAccount`] * A factory to create instances of the data object [implements, e.g., `IAccountFactory`] Previously the data object and the plug-in object were combined into one, but this meant that a new transaction plug-in had to be instantiated for each transaction recorded in the account which caused a number of problems. Unfortunately, that re-factoring has broken my message passing. The data object implements `INotifyPropertyChanged`, and so I've hit a new problem, and one that I'm not sure how to work around: the plug-in object is registering events with the message broker, but it's the data objects that actually fire the events. This means that **the subscribing plug-in currently has to subscribe to each created account, transaction, etc.!** This is clearly not scalable. As far as I can tell at the moment I have two possible solutions: 1. Make the data plug-in object a go-between for the data-objects and message broker, possibly batching change notifications. I don't like this because it adds another layer of complexity to the messaging system that I feel I should be able to do without. 2. Junk the current event-based implementation and use something else that's more easily manageable (in-memory WCF?!). So I guess I'm really asking: 1. How would you solve this problem? 2. What potential solutions do you think I've overlooked? 3. Is my approach even vaguely on-track/sensible?! :-) As you will be able to tell from the dates of the blog posts, some variant of this problem has been taxing me for quite a long time now! As such, any and all responses will be greatly appreciated. The background to the framework itself is as follows: > My plug-in framework consists of three main components: a plug-in broker, a preferences manager and a message broker. The plug-in broker does the bread-and-butter plug-in stuff: discovering and creating plug-ins. The preferences manager manages user preferences for the framework and individual plug-ins, such as which plug-ins are enabled, where data should be saved, etc. Communication is via publish/subscribe, with the message broker sitting in the middle, gathering all published message types and managing subscriptions. The publish/subscribe is currently implemented via the .NET `INotifyPropertyChanged` interface, which provides one event called `PropertyChanged`; the message broker builds a list of all plug-ins implementing `INotifyPropertyChanged` and subscribes other plug-ins this event. The purpose of the message passing is to allow the account and transaction plug-ins to notify the storage plug-ins that data has changed so that it may be saved.
This is my understanding of your question: You have a plugin object that may have to listen for events on x data objects - you don't want to subscribe to the event on each data object though. I'm assuming that several plugins may want to listen to events on the same data object. You could create a session type object. Each plugin listens for events on the session object. The data object no longer raises the event - it calls the session object to raise the event (one of the parameters would have to be the data object raising the event). That means that your plugins only have to subscribe to one event, but they get the event from all data objects. On the other hand, if only one plugin will ever listen to a data object at a time, why not just have the data object call the plugin directly?
Wow! Big question! :) Correct me if I'm wrong. Your basic solution now is kind of an Observer pattern, where the data object (Account, etc) notifies about changes in their states. You think that the problem is that the subscribing plugin has to register in every object to be able to handle notifications. That's not a problem per se, you can put the event control in the [Domain Model](http://martinfowler.com/eaaCatalog/domainModel.html), but I suggest you create a [Service Layer](http://martinfowler.com/eaaCatalog/serviceLayer.html) and do this event notifications in this layer. That way just one object would be responsible for publishing notifications. Martin Fowler have a series of Event Patterns in his blog. [Check it out](http://www.martinfowler.com/eaaDev/)! Very good reading.
Message passing in a plug-in framework
[ "", "c#", "plugins", "message-passing", "" ]
This should hopefully be a simple one. I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class. How should this extension method look? My first intuitive thought is something like this: ``` namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle(this ViewPage<Type> v) { return ""; } } } ``` **Solution** The general solution is [this answer](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772). The specific solution to extending the System.Web.Mvc.ViewPage class is [my answer](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802) below, which started from the [general solution](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772). The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.
I don't have VS installed on my current machine, but I think the syntax would be: ``` namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle<T>(this ViewPage<T> v) { return ""; } } } ```
Thanks leddt. Doing that yielded the error: > The type 'TModel' must be a reference > type in order to use it as parameter > 'TModel' in the generic type or method which pointed me to [this page](http://forums.asp.net/p/1311022/2581563.aspx), which yielded this solution: ``` namespace System.Web.Mvc { public static class ViewPageExtensions { public static string GetDefaultPageTitle<T>(this ViewPage<T> v) where T : class { return ""; } } } ```
How do you write a C# Extension Method for a Generically Typed Class
[ "", "c#", "asp.net-mvc", "generics", "extension-methods", "" ]
I've seen there are a few of them. [opencvdotnet](http://code.google.com/p/opencvdotnet/), [SharperCV](http://www.cs.ru.ac.za/research/groups/SharperCV/), [EmguCV](http://sourceforge.net/projects/emgucv), [One on Code Project](http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx#install). Does anyone have any experience with any of these? I played around with the one on Code Project for a bit, but as soon as I tried to do anything complicated I got some nasty uncatchable exceptions (i.e. Msgbox exceptions). Cross platform (supports Mono) would be best.
I started out with opencvdotnet but it's not really actively developed any more. Further, support for the feature I needed (facedetection) was patchy. I'm using [EmguCV](http://www.emgu.com/wiki/index.php/Main_Page) now: It wraps a much greater part of the API and the guy behind it is very responsive to suggestions and requests. The code is a joy to look at and is known to work on Mono. I've wrote up a quick [getting-started guide](http://friism.com/webcam-face-detection-in-c-using-emgu-cv) on my blog.
[NuGetMustHaves](https://nugetmusthaves.com/Tag/opencv) has a good summary of packages on NuGet with their build dates and OpenCV revs. As of 8/8/2023: * [EmguCV](http://www.emgu.com) is updated for OpenCV v4.7.0.5276 * [OpenCvSharp](https://github.com/shimat/opencvsharp) is updated for OpenCV v4.8.0.20230708 EmguCV and OpenCvSharp are the 2 packages with recent builds and appear to be the better choices going forward. Beware, EmguCV uses a dual GPL3/Commercial license [(source)](http://www.emgu.com/forum/viewtopic.php?t=5162) whereas OpenCVSharp uses the BSD 3-Clause License. In other words, OpenCVSharp is free for commercial use but EmguCV is not. EmguCV has superior documentation/examples/support and a bigger development team behind it, though, making the license worthwhile in many cases. It's worth considering what your future use cases are. If you're just looking to get running quickly using a managed language, the wrappers are fine. I started off that way. But as I got into more serious applications, I've found building a python/C++ application has better performance and more potential for reuse of code across platforms.
.Net (dotNet) wrappers for OpenCV?
[ "", "c#", ".net", "opencv", "mono", "cross-platform", "" ]
How do I avoid read locks in my database? Answers for multiple databases welcome!
In Oracle the default mode of operation is the *Read committed* isolation level where a select statement is not blocked by another transaction modifying the data it's reading. From [Data Concurrency and Consistency](http://download.oracle.com/docs/cd/B10501_01/server.920/a96524/c21cnsis.htm): > Each query executed by a transaction sees only data that was committed before the query (not the transaction) began. An Oracle query never reads dirty (uncommitted) data.
PostgreSQL also uses MVCC (Multi-Version Concurrency Control), so using the default transaction isolation level (read-committed), you should never block, unless somebody is doing maintainace on th DB (dropping / adding columns / tables / indexes / etc).
How do I avoid read locks in my database?
[ "", "sql", "database", "performance", "locking", "" ]
I have the following HTML `<select>` element: ``` <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option> </select> ``` Using a JavaScript function with the `leaveCode` number as a parameter, how do I select the appropriate option in the list?
You can use this function: ``` function selectElement(id, valueToSelect) { let element = document.getElementById(id); element.value = valueToSelect; } selectElement('leaveCode', '11'); ``` ``` <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option> </select> ``` Optionally if you want to trigger onchange event also, you can use : ``` element.dispatchEvent(new Event('change')) ```
If you are using jQuery you can also do this: ``` $('#leaveCode').val('14'); ``` This will select the `<option>` with the value of 14. --- With plain Javascript, this can also be achieved with two [`Document` methods](https://developer.mozilla.org/en-US/docs/Web/API/Document#Methods): * With [`document.querySelector`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector), you can select an element based on a CSS selector: ``` document.querySelector('#leaveCode').value = '14' ``` * Using the more established approach with [`document.getElementById()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById), that will, as the name of the function implies, let you select an element based on its `id`: ``` document.getElementById('leaveCode').value = '14' ``` You can run the below code snipped to see these methods and the jQuery function in action: ``` const jQueryFunction = () => { $('#leaveCode').val('14'); } const querySelectorFunction = () => { document.querySelector('#leaveCode').value = '14' } const getElementByIdFunction = () => { document.getElementById('leaveCode').value='14' } ``` ``` input { display:block; margin: 10px; padding: 10px } ``` ``` <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option> </select> <input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" /> <input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" /> <input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ```
How do I programmatically set the value of a select box element using JavaScript?
[ "", "javascript", "html", "dom", "" ]
(I'm using Visual C++ 2008) I've always heard that main() is *required* to return an integer, but here I didn't put in `return 0;` and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a `return;` also causes the error to appear. But leaving it out completely, it compiles just fine. ``` #include <iostream> using namespace std; int main() { cout << "Hey look I'm supposed to return an int but I'm not gonna!\n"; } ``` Could this be a bug in VC++?
> # 3.6.1 Main function > > .... > > 2 An implementation shall not predefine the `main` function. This function shall not be overloaded. It shall have a return type of type `int`, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main: > > ``` > int main() { /* ... */ } > ``` > > and > > ``` > int main(int argc, char* argv[]) { > /* ... */ > } > ``` > > .... and it continues to add ... > > 5 A `return` statement in `main` has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling `exit` with the return value as the argument. **If control reaches the end of `main` without encountering a return statement, the effect is that of executing return 0**; attempting to find an online copy of the C++ standard so I could quote this passage [I found a blog post that quotes all the right bits better than I could.](http://zamanbakshifirst.blogspot.com/2006/11/c-c-main-should-return-void.html)
This is part of the C++ language standard. An implicit return 0 is generated for you if there's no explicit return statement in main.
Why does int main() {} compile?
[ "", "c++", "return-value", "program-entry-point", "" ]
I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?
You need [ARP](http://en.wikipedia.org/wiki/Address_Resolution_Protocol). Python's standard library doesn't include any code for that, so you either need to call an external program (your OS may have an 'arp' utility) or you need to build the packets yourself (possibly with a tool like [Scapy](http://www.secdev.org/projects/scapy/).
I don't think there is a built in way to get it from Python itself. My question is, how are you getting the IP information from your network? To get it from your local machine you could parse ifconfig (unix) or ipconfig (windows) with little difficulty.
Search for host with MAC-address using Python
[ "", "python", "network-programming", "" ]
I have a line of C# in my ASP.NET code behind that looks like this: ``` DropDownList ddlStates = (DropDownList)fvAccountSummary.FindControl("ddlStates"); ``` The DropDownList control is explicitly declared in the markup on the page, not dynamically created. It is inside of a FormView control. When my code hits this line, I am getting an ArithmeticException with the message "Value was either too large or too small for an Int32." This code has worked previously, and is in production right now. I fired up VS2008 to make some changes to the site, but before I changed anything, I got this exception from the page. Anyone seen this one before?
If that's the stacktrace, its comingn from databinding, not from the line you posted. Is it possible that you have some really large data set? I've seen a 6000-page GridView overflow an Int16, although it seems pretty unlikely you'd actually overflow an Int32... Check to make sure you're passing in sane data into, say, the startpageIndex or pageSize of your datasource, for example.
Are you 100% sure that's the line of code that's throwing the exception? I'm pretty certain that the FindControl method is not capable of throwing an ArithmeticException. Of course, I've been known to be wrong before... :)
FindControl() method throws ArithmeticException?
[ "", "c#", "asp.net", "" ]
How do I get today's date in C# in mm/dd/yyyy format? I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time. BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11. *Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.* [kronoz's answer](https://stackoverflow.com/questions/32747/how-do-i-get-todays-date-in-c-in-8282008-format#32819 "kronoz's answer")
``` DateTime.Now.ToString("M/d/yyyy"); ``` <http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx>
Not to be horribly pedantic, but if you are internationalising the code it might be more useful to have the facility to get the short date for a given culture, e.g.:- ``` using System.Globalization; using System.Threading; ... var currentCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-us"); string shortDateString = DateTime.Now.ToShortDateString(); // Do something with shortDateString... } finally { Thread.CurrentThread.CurrentCulture = currentCulture; } ``` Though clearly the "m/dd/yyyy" approach is considerably neater!!
How do I get today's date in C# in mm/dd/yyyy format?
[ "", "c#", "date", "" ]
I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: * [Lightweight IDE for linux](https://stackoverflow.com/questions/2756/lightweight-ide-for-linux) and * [What tools do you use to develop C++ applications on Linux?](https://stackoverflow.com/questions/17228/what-tools-do-you-use-to-develop-c-applications-on-linux) I'm not looking for a *lightweight* IDE. If an IDE is worth the money, then I will pay for it, so it need not be free. My question, then: > *What good, C++ programming IDE is available for Linux?* The minimums are fairly standard: syntax highlighting, code completion (like [intellisense](http://en.wikipedia.org/wiki/IntelliSense) or its Eclipse counterpart) and integrated debugging (e.g., basic breakpoints). I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that [Eclipse supports C++](http://www.eclipse.org/cdt/), and I really like that IDE for Java, but is it any good for C++ and is there something better? The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages? Maybe my question should therefore be: > *What IDE do you propose (given your experiences), and why?*
## Initially: confusion When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed. ## Epiphany: UNIX is an IDE. *All of it.*1 And then I realised that the IDE in Linux is the command line with its tools: * First you set up your shell + Bash, in my case, but many people prefer + [fish](https://fishshell.com/) or + [(Oh My) Zsh](https://github.com/robbyrussell/oh-my-zsh); * and your editor; pick your poison — both are state of the art: + [Neovim](https://neovim.io/)2 or + [Emacs](https://www.gnu.org/software/emacs/). Depending on your needs, you will then have to install and configure several plugins to make the editor work nicely (that’s the one annoying part). For example, most programmers on Vim will benefit from the [YouCompleteMe](https://valloric.github.io/YouCompleteMe/) plugin for smart autocompletion. Once that’s done, the shell is your command interface to interact with the various tools — Debuggers (gdb), Profilers (gprof, valgrind), etc. You set up your project/build environment using [Make](https://www.gnu.org/software/make/), [CMake](https://bitbucket.org/snakemake/snakemake/wiki/Home), [SnakeMake](https://bitbucket.org/snakemake/snakemake/wiki/Home) or any of the various alternatives. And you manage your code with a version control system (most people use [Git](https://git-scm.com/)). You also use [tmux](https://tmux.github.io/) (previously also screen) to multiplex (= think multiple windows/tabs/panels) and persist your terminal session. The point is that, thanks to the shell and a few tool writing conventions, these all *integrate with each other*. And that way **the Linux shell is a truly integrated development environment**, completely on par with other modern IDEs. (This doesn’t mean that individual IDEs don’t have features that the command line may be lacking, but the inverse is also true.) ## To each their own I cannot overstate how well the above workflow functions once you’ve gotten into the habit. But some people simply prefer graphical editors, and in the years since this answer was originally written, Linux has gained a suite of excellent graphical IDEs for several different programming languages (but not, as far as I’m aware, for C++). Do give them a try even if — like me — you end up not using them. Here’s just a small and biased selection: * For Python development, there’s [PyCharm](https://www.jetbrains.com/pycharm/) * For R, there’s [RStudio](https://www.rstudio.com/) * For JavaScript and TypeScript, there’s [Visual Studio Code](https://code.visualstudio.com/) (which is also a good all-round editor) * And finally, many people love the [Sublime Text editor](https://www.sublimetext.com/) for general code editing. Keep in mind that this list is far from complete. --- 1 I stole that title from dsm’s comment. 2 I used to refer to Vim here. And while plain Vim is still more than capable, Neovim is a promising restart, and it’s modernised a few old warts.
My personal favorite is the **CodeLite 2.x** IDE. see: [http://www.codelite.org](http://www.codelite.org/ "codelite website") The decision to use CodeLite was based on a research regarding the following C++ IDE for Linux: * Eclipse Galileo with CDT Plugin * NetBeans 6.7 (which is also the base for the SunStudio IDE) * KDevelop4 * CodeBlocks 8.02 * CodeLite 2.x After all I have decided to use *CodeLite 2.x*. Below I have listed some Pros and Cons regarding the mentioned C++ IDEs. Please note, that this reflects my personal opinion only! **EDIT**: what a pity that SOF doesn't support tables, so I have to write in paragraphs ... **Eclipse Galileo with CDT Plugin** Pros: * reasonable fast * also supports Java, Perl(with E.P.I.C plugin) * commonly used and well maintained * also available for other OS flavours (Windows, MacOS, Solaris, AIX(?)) Cons: * GUI is very confusing and somewhat inconsistent - not very intuitive at all * heavy weight * Only supports CVS (AFAIK) **NetBeans 6.7** (note this is also the base for the SunStudio IDE) Pros: * one of the most intuitive GUI I have ever seen * also supports Java, Python, Ruby * integrates CVS, SVN, Mercurial * commonly used and well maintained * also available for other OS flavours (Windows, MacOS, Solaris) Cons: * extremly slow * heavy weight * uses Spaces for indentation, which is not the policy at my work. I'm sure this is configurable, but I couldn't find out how to to that **KDevelop4** (note: I did not much testing on it) Pros: * commonly used on Linux * integrates CVS, SVN, Mercurial Cons: * the GUI looks somewhat old fashioned * heavy weight * very specific to the KDE environment **CodeBlocks 8.02** (note: I did not much testing on it) Pros: * reasonable fast Cons: * the GUI looks somewhat old fashioned (although it has a nice startup screen) * the fonts in the editor are very small * some icons (e.g. the debugger related icons starting/stepping) are very small * no source control integration **CodeLite 2.x** (note: this is my personal favorite) Pros: * the best, modern looking and intuitive GUI I have seen on Linux * lightweight * reasonable fast * integrates SVN * also available on other OS flavours(Windows, MacOS, Solaris(?)) Cons: * no CVS integration (that's important for me because I have to use it at work) * no support for Java, Perl, Python (would be nice to have)
C++ IDE for Linux?
[ "", "c++", "linux", "ide", "" ]
I want to allow users to upload avatar-type images in a variety of formats (**GIF, JPEG, and PNG at least**), but to save them all as **PNG database BLOBs**. If the images are oversized, pixelwise, I want to resize them before DB-insertion. **What is the best way to use GD to do the resizing and PNG conversion?** Edit: Sadly, only [GD](http://php.net/manual/en/book.image.php) is available on the server I need to use, no [ImageMagick](http://www.imagemagick.org/script/index.php).
``` <?php /* Resizes an image and converts it to PNG returning the PNG data as a string */ function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; $width = $maxSize; $height = $maxSize; // resize to height (orig is portrait) if ($ratio_orig < 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output to a temp file $destFile = tempnam(); imagepng($newImage, $destFile); // Free memory imagedestroy($newImage); if ( is_file($destFile) ) { $f = fopen($destFile, 'rb'); $data = fread($f); fclose($f); // Remove the tempfile unlink($destFile); return $data; } throw new Exception('Image conversion failed.'); } ```
Your process steps should look like this: 1. [Verify](http://www.php.net/manual/en/function.exif-imagetype.php) the [filetype](http://www.php.net/manual/en/function.imagetypes.php) 2. Load the image if it is a supported filetype into GD using [imagecreatefrom\*](http://www.php.net/manual/en/function.imagecreatefromjpeg.php) 3. Resizing using [imagecopyresize](http://www.php.net/manual/en/function.imagecopyresized.php) or [imagecopyresampled](http://www.php.net/manual/en/function.imagecopyresampled.php) 4. Save the image using [imagepng($handle, 'filename.png', $quality, $filters)](http://www.php.net/manual/en/function.imagepng.php) > ImageMagick is faster, generates better images, is more configurable, and finally is (IMO) much easier to code for. @ceejayoz Just wait for the new GD - it's OOP like MySQLi and it's actually not bad :)
How do I resize and convert an uploaded image to a PNG using GD?
[ "", "php", "database", "image", "png", "gd", "" ]
How do I open the default mail program with a Subject and Body in a cross-platform way? Unfortunately, this is for a a client app written in Java, not a website. I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever. In OS X, I have tried executing the command: ``` open mailto:?subject=MySubject&body=TheBody ``` URL escaping is needed to replace spaces with `%20`. **Updated** On Windows, you have to play all sorts of games to get `start` to run correctly. Here is the proper Java incantation: ``` class Win32 extends OS { public void email(String subject, String body) throws Exception { String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\""; Runtime.getRuntime().exec(cmd); } } ```
In Java 1.6 you have a stardard way to open the default mailer of the platform: [the Desktop.mail(URI) method](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html).The URI can be used to set all the fields of the mail (sender, recipients, body, subject). You can check a full example of desktop integration in Java 1.6 on [Using the Desktop API in Java SE 6](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/)
Never use `Runtime.exec(String)` on Mac OS X or any other operating system. If you do that, you'll have to figure out how to properly quote all argument strings and so on; it's a pain and very error-prone. Instead, use `Runtime.exec(String[])` which takes an array of already-separated arguments. This is much more appropriate for virtually all uses.
How do I open the default mail program with a Subject and Body in a cross-platform way?
[ "", "java", "windows", "macos", "email", "" ]
I have a PHP script that runs as a CGI program and the HTTP `Authenticate` header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored. I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials. So how would you implement this? Cookies? I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.
A few ways you could do this. 1. [htaccess](http://fragments.turtlemeat.com/htaccess.php) -- have your webserver handle securing the pages in question (not exactly cgi form based though). 2. Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash. Make sure to [salt](http://www.codinghorror.com/blog/archives/000949.html) your hashes for extra security vs rainbow tables. (This method is a bit naive... be *very* careful with security if you go this route) 3. use something like a [sqlite](http://www.sqlite.org/) database just to handle authentication. Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend. Theoretically, you could also store session data in a flat file, even if you can't have a database.
If you're currently using Authenticate, then you may already have an *htpasswd* file. If you would like to continue using that file, but switch to using FORM based authentication rather than via the Authenticate header, you can use a PHP script to use the same htpasswd file and use sessions to maintain the authentication status. A quick Google search for php htpasswd reveals [this page](https://web.archive.org/web/20120510143809/http://koivi.com/php-http-auth/) with a PHP function to check credentials against an htpasswd. You could integrate it (assuming you have sessions set to autostart) with some code like this: ``` // At the top of your 'private' page(s): if($_SESSION['authenticated'] !== TRUE) { header('Location: /login.php'); die(); } // the target of the POST form from login.php if(http_authenticate($_POST['username'], $_POST['password'])) $_SESSION['authenticated'] = TRUE; ```
How would you implement FORM based authentication without a backing database?
[ "", "php", "http", "authentication", "cookies", "cgi", "" ]
Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?
Believe it or not, you can actually use [`java.awt.Robot`](http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)) to "create an image containing pixels read from the screen." You can then write that image to a file on disk. I just tried it, and the whole thing ends up like: ``` Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage capture = new Robot().createScreenCapture(screenRect); ImageIO.write(capture, "bmp", new File(args[0])); ``` NOTE: This will only capture the primary monitor. See [GraphicsConfiguration](http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html) for multi-monitor support.
I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects: ``` public static final void makeScreenshot(JFrame argFrame) { Rectangle rec = argFrame.getBounds(); BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB); argFrame.paint(bufferedImage.getGraphics()); try { // Create temp file File temp = File.createTempFile("screenshot", ".png"); // Use the ImageIO API to write the bufferedImage to a temporary file ImageIO.write(bufferedImage, "png", temp); // Delete temp file when program exits temp.deleteOnExit(); } catch (IOException ioe) { ioe.printStackTrace(); } } ```
Is there a way to take a screenshot using Java and save it to some sort of image?
[ "", "java", "image", "screenshot", "" ]
I was testing on a customer's box this afternoon which has Windows Vista (He had home, but I am testing on a Business Edition with same results). We make use of a .DLL that gets the Hardware ID of the computer. It's usage is very simple and the sample program I have created works. The Dll is [This from AzSdk](http://www.azsdk.com/hardwareid.html). In fact, this works perfectly under Windows XP. However, for some strange reason, inside our project (way bigger), we get this exception: ``` Exception Type: System.DllNotFoundException Exception Message: Unable to load DLL 'HardwareID.dll': Invalid access to memory location. (Exception from HRESULT: 0x800703E6) Exception Target Site: GetHardwareID ``` I don't know what can be causing the problem, since I have full control over the folder. The project is a c#.net Windows Forms application and everything works fine, except the call for the external library. I am declaring it like this: (note: it's *not* a COM library and it doesn't need to be registered). ``` [DllImport("HardwareID.dll")] public static extern String GetHardwareID(bool HDD, bool NIC, bool CPU, bool BIOS, string sRegistrationCode); ``` And then the calling code is quite simple: ``` private void button1_Click(object sender, EventArgs e) { textBox1.Text = GetHardwareID(cb_HDD.Checked, cb_NIC.Checked, cb_CPU.Checked, cb_BIOS.Checked, "*Registration Code*"); } ``` When you create a sample application, it works, but inside my projectit doesn't. Under XP works fine. Any ideas about what should I do in Vista to make this work? As I've said, the folder and its sub-folders have Full Control for "Everybody". **UPDATE:** I do not have Vista SP 1 installed. **UPDATE 2:** I have installed Vista SP1 and now, with UAC disabled, not even the simple sample works!!! :( Damn Vista.
@[Martín](https://stackoverflow.com/questions/29284/windows-vista-unable-to-load-dll-xdll-invalid-access-to-memory-location-dllnotf#29400) The reason you were not getting the UAC prompt is because UAC can only change how a process is **started**, once the process is running it must stay at the same elevation level. The UAC will prompt will happen if: * Vista thinks it's an installer ([lots of rules here](http://msdn.microsoft.com/en-us/library/aa905330.aspx#wvduac_topic3), the simplest one is if it's called "setup.exe"), * If it's flagged as "Run as Administrator" (you can edit this by changing the properties of the shortcut or the exe), or * If the exe contains a manifest requesting admin privileges. The first two options are workarounds for 'legacy' applications that were around before UAC, the correct way to do it for new applications is to [embed a manifest resource](http://msdn.microsoft.com/en-us/library/bb756929.aspx) asking for the privileges that you need. Some program, such as [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) appear to elevate a running process (when you choose "Show details for all process" in the file menu in this case) but what they really do is start a new instance, and it's that new instance that gets elevated - not the one that was originally running. This is the recommend way of doing it if only some parts of your application need elevation (e.g. a special 'admin options' dialog).
> Unable to load DLL 'HardwareID.dll': > Invalid access to memory location. > (Exception from HRESULT: 0x800703E6) The name of DllNotFoundException is confusing you - this isn't a problem with finding or loading the DLL file, the problem is that when the DLL is loaded, it does an illegal memory access which causes the loading process to fail. Like another poster here, I think this is a DEP problem, and that your UAC, etc, changes have finally allowed you to disable DEP for this application.
Windows Vista: Unable to load DLL 'x.dll': Invalid access to memory location. (DllNotFoundException)
[ "", "c#", ".net", "windows-vista", "dllnotfoundexception", "" ]
Out of the box SSRS reports cannot have data exposed in the page header. Is there a way to get this data to show?
One of the things I want in my reports is to have nice headers for my reports. I like to have a logo and the user's report parameters along with other data to show to give more information for the business needs the report needs to clarify. One of the things that Microsoft SQL Server 2005 Reporting Services cannot do natively is show data from a Dataset in the header. This post will explain how to work around this and how easy it is. Create the Report Server Project in the Business Intelligence Projects section and call it AdventureWorksLTReports. I use the AdventureWorksLT sample database from CodePlex. [alt text http://www.cloudsocket.com/images/image-thumb.png](http://www.cloudsocket.com/images/image-thumb.png) Next show the Page Header by right clicking in the Report area with the designer. [alt text http://www.cloudsocket.com/images/image-thumb1.png](http://www.cloudsocket.com/images/image-thumb1.png) The Page Header will appear. If you want to show the Page Footer this can be accessed from the same menu as the Page Header. [alt text http://www.cloudsocket.com/images/image-thumb2.png](http://www.cloudsocket.com/images/image-thumb2.png) I created a stored procedure that returns data for the Sales Order to be presented in the Page Header. I will show the following information about the Sales Order in the Page Header: * Order Date * Sales Order Number * Company * Sales Person * Total Due I create a TextBox for each of my data fields in the Page Header along with a TextBox for the corresponding label. Do not change the Expression in the TextBoxes that you want the Sales Order data in. [alt text http://www.cloudsocket.com/images/image-thumb3.png](http://www.cloudsocket.com/images/image-thumb3.png) In the Report Body, place a TextBox for each data field needed in the Page Header. In the Visibility for each TextBox, select True for Hidden. This will be the placeholder for the data needed in the Page Header. [alt text http://www.cloudsocket.com/images/image-thumb4.png](http://www.cloudsocket.com/images/image-thumb4.png) Your report should look similar to the screenshot shown below. [alt text http://www.cloudsocket.com/images/image-thumb5.png](http://www.cloudsocket.com/images/image-thumb5.png) The last step and most important is to reference the Hidden TextBox in the TextBoxes located in the Page Header. We use the the following Expression to reference the needed TextBoxes: =ReportItems!.Value Your report should now look similar to the following: [alt text http://www.cloudsocket.com/images/image-thumb6.png](http://www.cloudsocket.com/images/image-thumb6.png) Your Report preview should now have the Sales Order Header data in the Report Header. [alt text http://www.cloudsocket.com/images/image-thumb7.png](http://www.cloudsocket.com/images/image-thumb7.png)
You have to do it through Parameters. Add a parameter for each piece of data you would like to display, then set the parameter to Hidden. Then set the default value to "From Query" and set the Dataset and Value field to the appropriate values.
How do I show data in the header of a SQL 2005 Reporting Services report?
[ "", "sql", "reporting-services", "header", "report", "" ]
I'm using a `Dictionary<string, int>` where the `int` is a count of the key. Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt: ``` int LastCount = mydict[mydict.keys[mydict.keys.Count]]; ``` does not work, because `Dictionary.Keys` does not implement a []-indexer. I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a `Stack<MyStruct>`, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?
As @Falanwe points out in a comment, doing something like this is ***incorrect***: ``` int LastCount = mydict.Keys.ElementAt(mydict.Count -1); ``` You **should not** depend on the order of keys in a Dictionary. If you need ordering, you should use an [OrderedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary), as suggested in this [answer](https://stackoverflow.com/a/5540/1724702). The other answers on this page are interesting as well.
You can use an [OrderedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary). > Represents a collection of key/value > pairs that are accessible by the key > or index.
Accessing a Dictionary.Keys Key through a numeric index
[ "", "c#", ".net", "dictionary", "" ]
My site has a drop-down menu built in CSS and JavaScript that drops down over a Flash animation. In IE (6&7) the drop-down menus drop over the Flash animation, however, in Firefox (2&3) the menus appear underneath the Flash animation. Is there any way to get this dynamic menu to flow OVER the Flash in Firefox? ![alt text](https://lh3.ggpht.com/guterl/SMnyzAeha6I/AAAAAAAAABI/BGWJes9d9FA/s288/ie_sample.gif) In IE 7 menu appears over the Flash: In Firefox the menu appears under the Flash: (How can I fix this?!) ![alt text](https://lh3.ggpht.com/guterl/SMnyzHYVLrI/AAAAAAAAABQ/924qQaD3K0o/s288/firefox_sample.gif)
Try setting wmode to transparent - see [here](http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_15523)
wmode=opaque seemed to work for me I did it here:www.toolgal.com, hover over the products menu on the top navigation Dan
CSS / JavaScript Navigation Menu on top of Flash in Firefox
[ "", "javascript", "css", "flash", "navigation", "" ]
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
Send the following headers before outputting the file: ``` header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/octet-stream"); header("Content-Length: " . filesize($File)); header("Connection: close"); ``` [@grom](https://stackoverflow.com/users/486/grom): Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)
Here is an example of sending back a pdf. ``` header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Content-Transfer-Encoding: binary'); readfile($filename); ``` [@Swish](https://stackoverflow.com/questions/40943/how-to-automatically-start-a-download-in-php#40947) I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type? Also in the PHP manual [Hayley Watson](http://au.php.net/manual/en/function.header.php#71993) posted: > If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046). Also according [IANA](http://www.iana.org/assignments/media-types/application/) there is no registered application/force-download type.
How to Automatically Start a Download in PHP?
[ "", "php", "automation", "download", "" ]
I'm programming WCF using the ChannelFactory which expects a type in order to call the CreateChannel method. For example: ``` IProxy proxy = ChannelFactory<IProxy>.CreateChannel(...); ``` In my case I'm doing routing so I don't know what type my channel factory will be using. I can parse a message header to determine the type but I hit a brick wall there because even if I have an instance of Type I can't pass that where ChannelFactory expects a generic type. Another way of restating this problem in very simple terms would be that I'm attempting to do something like this: ``` string listtype = Console.ReadLine(); // say "System.Int32" Type t = Type.GetType( listtype); List<t> myIntegers = new List<>(); // does not compile, expects a "type" List<typeof(t)> myIntegers = new List<typeof(t)>(); // interesting - type must resolve at compile time? ``` Is there an approach to this I can leverage within C#?
What you are looking for is MakeGenericType ``` string elementTypeName = Console.ReadLine(); Type elementType = Type.GetType(elementTypeName); Type[] types = new Type[] { elementType }; Type listType = typeof(List<>); Type genericType = listType.MakeGenericType(types); IProxy proxy = (IProxy)Activator.CreateInstance(genericType); ``` So what you are doing is getting the type-definition of the generic "template" class, then building a specialization of the type using your runtime-driving types.
You should look at this post from Ayende: [WCF, Mocking and IoC: Oh MY!](http://www.ayende.com/Blog/archive/2007/02/10/WCF-Mocking-and-IoC-Oh-MY.aspx). Somewhere near the bottom is a method called GetCreationDelegate which should help. It basically does this: ``` string typeName = ...; Type proxyType = Type.GetType(typeName); Type type = typeof (ChannelFactory<>).MakeGenericType(proxyType); object target = Activator.CreateInstance(type); MethodInfo methodInfo = type.GetMethod("CreateChannel", new Type[] {}); return methodInfo.Invoke(target, new object[0]); ```
Dynamically Create a generic type for template
[ "", "c#", "generics", "" ]
I want to have a "select-only" `ComboBox` that provides a list of items for the user to select from. Typing should be disabled in the text portion of the `ComboBox` control. My initial googling of this turned up an overly complex, misguided suggestion to capture the `KeyPress` event.
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: ``` stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList; ``` Link to the documentation for the [ComboBox DropDownStyle property](http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle.aspx) on MSDN.
To add a Visual Studio GUI reference, you can find the `DropDownStyle` options under the Properties of the selected ComboBox: ![enter image description here](https://i.stack.imgur.com/2K5dT.png) Which will automatically add the line mentioned in the first answer to the Form.Designer.cs `InitializeComponent()`, like so: ``` this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; ```
How can I make a ComboBox non-editable in .NET?
[ "", "c#", ".net", "winforms", "combobox", "" ]
I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?
Opening sockets in python is pretty simple. You really just need something like this: ``` import socket sock = socket.socket() sock.connect((address, port)) ``` and then you can `send()` and `recv()` like any other socket
OK, this code worked ``` s = socket.socket() s.connect((ip,port)) s.send("my request\r") print s.recv(256) s.close() ``` It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.
Best way to open a socket in Python
[ "", "python", "networking", "tcp", "" ]
Is there a free or open source library to read Excel files (.xls) directly from a C# program? It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.
``` var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory()); var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "anyNameHere"); DataTable data = ds.Tables["anyNameHere"]; ``` This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables: ``` var data = ds.Tables["anyNameHere"].AsEnumerable(); ``` as this lets me use LINQ to search and build structs from the fields. ``` var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x => new MyContact { firstName= x.Field<string>("First Name"), lastName = x.Field<string>("Last Name"), phoneNumber =x.Field<string>("Phone Number"), }); ```
If it is just simple data contained in the Excel file you can read the data via ADO.NET. See the connection strings listed here: <http://www.connectionstrings.com/?carrier=excel2007> or [http://www.connectionstrings.com/?carrier=excel](http://www.connectionstrings.com/?carrier=excel2007) -Ryan Update: then you can just read the worksheet via something like `select * from [Sheet1$]`
Reading Excel files from C#
[ "", "c#", ".net", "excel", "ms-office", "" ]
Say I have two strings, ``` String s1 = "AbBaCca"; String s2 = "bac"; ``` I want to perform a check returning that `s2` is contained within `s1`. I can do this with: ``` return s1.contains(s2); ``` I am pretty sure that `contains()` is case sensitive, however I can't determine this for sure from reading the documentation. If it is then I suppose my best method would be something like: ``` return s1.toLowerCase().contains(s2.toLowerCase()); ``` All this aside, is there another (possibly better) way to accomplish this without caring about case-sensitivity?
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE\_INSENSITIVE flag for case insensitive matching: ``` Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find(); ``` **EDIT:** If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
One problem with [the answer by Dave L.](https://stackoverflow.com/questions/86780/is-the-contains-method-in-java-lang-string-case-sensitive/86832#86832) is when s2 contains regex markup such as `\d`, etc. You want to call Pattern.quote() on s2: ``` Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find(); ```
How to check if a String contains another String in a case insensitive manner in Java?
[ "", "java", "string", "" ]
Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this. ``` // Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -> name = $name; $this -> height = $height; $this -> weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; ``` --- Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins. I've not idea which answer I should accept to I've just upvoted all of them. --- And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself. Thank you for helping to make me a better programmer.
The "class" that you've constructed above is what most people would use a *struct* for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit. That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion. I'm only saying the following based on the title and your question, but: Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the `weight` field private and provide some accessor methods, like `getWeight()` and `setWeight()`. Inside `setWeight()`, you could do some value checking, like so: ``` public function setWeight($weight) { if($weight >= 0) { $this->weight = $weight; } else { // Handle this scenario however you like } } ```
It depends exactly what you mean by 'better'. I'd go for the object oriented way (using classes) because I find it makes for cleaner code (at least in my opinion). However, I'm not sure what the speed penalties might be for that option.
Classes vs 2D arrays
[ "", "php", "arrays", "class", "" ]
How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time. *Edit: These users do want to be distracted when a new message arrives.*
this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab. ``` newExcitingAlerts = (function () { var oldTitle = document.title; var msg = "New!"; var timeoutId; var blink = function() { document.title = document.title == msg ? ' ' : msg; }; var clear = function() { clearInterval(timeoutId); document.title = oldTitle; window.onmousemove = null; timeoutId = null; }; return function () { if (!timeoutId) { timeoutId = setInterval(blink, 1000); window.onmousemove = clear; } }; }()); ``` --- *Update*: You may want to look at using [HTML5 notifications](https://paulund.co.uk/how-to-use-the-html5-notification-api).
I've made a [jQuery plugin](http://heyman.info/jquery-title-alert/ "jQuery Title Alert") for the purpose of blinking notification messages in the browser title bar. You can specify different options like blinking interval, duration, if the blinking should stop when the window/tab gets focused, etc. The plugin works in Firefox, Chrome, Safari, IE6, IE7 and IE8. Here is an example on how to use it: ``` $.titleAlert("New mail!", { requireBlur:true, stopOnFocus:true, interval:600 }); ``` If you're not using jQuery, you might still want to look at the [source code](http://github.com/heyman/jquery-titlealert "Source code at GitHub") (there are a few quirky bugs and edge cases that you need to work around when doing title blinking if you want to fully support all major browsers).
Make browser window blink in task Bar
[ "", "javascript", "browser", "" ]
So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google. ``` CLass Blah { [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); } } ``` As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? --- @Joel, thanks for the info. Here is what I tried based on your suggestion: ``` msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.Focus(); Application.DoEvents(); ``` The form still comes up *under* the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes. Thnks for all the ideas so far folks. --- Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling.
I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem. Basically, call ShowWindow() then SetForegroundWindow(). ``` using System.Diagnostics; using System.Runtime.InteropServices; // Sets the window to be foreground [DllImport("User32")] private static extern int SetForegroundWindow(IntPtr hwnd); // Activate or minimize a window [DllImportAttribute("User32.DLL")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); private const int SW_SHOW = 5; private const int SW_MINIMIZE = 6; private const int SW_RESTORE = 9; private void ActivateApplication(string briefAppName) { Process[] procList = Process.GetProcessesByName(briefAppName); if (procList.Length > 0) { ShowWindow(procList[0].MainWindowHandle, SW_RESTORE); SetForegroundWindow(procList[0].MainWindowHandle); } } ```
Here is some code that I've used on one form or another for a few years. There are a few gotchas to making a window in another app pop up. Once you have the window handle do this: ``` if (IsIconic(hWnd)) ShowWindowAsync(hWnd, SW_RESTORE); ShowWindowAsync(hWnd, SW_SHOW); SetForegroundWindow(hWnd); // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm // Converted to Delphi by Ray Lischner // Published in The Delphi Magazine 55, page 16 // Converted to C# by Kevin Gale IntPtr foregroundWindow = GetForegroundWindow(); IntPtr Dummy = IntPtr.Zero; uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindow, Dummy); uint thisThreadId = GetWindowThreadProcessId(hWnd, Dummy); if (AttachThreadInput(thisThreadId, foregroundThreadId, true)) { BringWindowToTop(hWnd); // IE 5.5 related hack SetForegroundWindow(hWnd); AttachThreadInput(thisThreadId, foregroundThreadId, false); } if (GetForegroundWindow() != hWnd) { // Code by Daniel P. Stasinski // Converted to C# by Kevin Gale IntPtr Timeout = IntPtr.Zero; SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, Timeout, 0); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Dummy, SPIF_SENDCHANGE); BringWindowToTop(hWnd); // IE 5.5 related hack SetForegroundWindow(hWnd); SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, Timeout, SPIF_SENDCHANGE); } ``` I won't post the whole unit since since it does other things that aren't relevant but here are the constants and imports for the above code. ``` //Win32 API calls necesary to raise an unowned processs main window [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true)] private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni); [DllImport("user32.dll", SetLastError = true)] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr lpdwProcessId); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr hWnd); [DllImport("user32.dll")] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, Int32 nMaxCount); [DllImport("user32.dll")] private static extern int GetWindowThreadProcessId(IntPtr hWnd, ref Int32 lpdwProcessId); [DllImport("User32.dll")] public static extern IntPtr GetParent(IntPtr hWnd); private const int SW_HIDE = 0; private const int SW_SHOWNORMAL = 1; private const int SW_NORMAL = 1; private const int SW_SHOWMINIMIZED = 2; private const int SW_SHOWMAXIMIZED = 3; private const int SW_MAXIMIZE = 3; private const int SW_SHOWNOACTIVATE = 4; private const int SW_SHOW = 5; private const int SW_MINIMIZE = 6; private const int SW_SHOWMINNOACTIVE = 7; private const int SW_SHOWNA = 8; private const int SW_RESTORE = 9; private const int SW_SHOWDEFAULT = 10; private const int SW_MAX = 10; private const uint SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000; private const uint SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001; private const int SPIF_SENDCHANGE = 0x2; ```
C# Force Form Focus
[ "", "c#", "winforms", "" ]
The problem: I have a class which contains a template method `execute` which calls another method `_execute`. Subclasses are supposed to overwrite `_execute` to implement some specific functionality. This functionality should be documented in the docstring of `_execute`. Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use `execute`, so he won't see the correct docstring if he uses `help(execute)`. Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of `execute` is automatically replaced with that of `_execute`. Any ideas how this might be done? I was thinking of metaclasses to do this, to make this completely transparent to the user.
Well, if you don't mind copying the original method in the subclass, you can use the following technique. ``` import new def copyfunc(func): return new.function(func.func_code, func.func_globals, func.func_name, func.func_defaults, func.func_closure) class Metaclass(type): def __new__(meta, name, bases, attrs): for key in attrs.keys(): if key[0] == '_': skey = key[1:] for base in bases: original = getattr(base, skey, None) if original is not None: copy = copyfunc(original) copy.__doc__ = attrs[key].__doc__ attrs[skey] = copy break return type.__new__(meta, name, bases, attrs) class Class(object): __metaclass__ = Metaclass def execute(self): '''original doc-string''' return self._execute() class Subclass(Class): def _execute(self): '''sub-class doc-string''' pass ```
Is there a reason you can't override the base class's `execute` function directly? ``` class Base(object): def execute(self): ... class Derived(Base): def execute(self): """Docstring for derived class""" Base.execute(self) ...stuff specific to Derived... ``` If you don't want to do the above: Method objects don't support writing to the `__doc__` attribute, so you have to change `__doc__` in the actual function object. Since you don't want to override the one in the base class, you'd have to give each subclass its own copy of `execute`: ``` class Derived(Base): def execute(self): return Base.execute(self) class _execute(self): """Docstring for subclass""" ... execute.__doc__= _execute.__doc__ ``` but this is similar to a roundabout way of redefining `execute`...
Using the docstring from one method to automatically overwrite that of another method
[ "", "python", "metaclass", "" ]
Does anyone have any recommendations for implementations of ActiveRecord in PHP? I've been using [CBL ActiveRecord](http://31tools.com/cbl_activerecord/), but I was wondering if there were any viable alternatives.
Depends! ;) For example there is [ADODB's Active Record implementation](http://phplens.com/lens/adodb/docs-active-record.htm), then there is Zend\_Db\_DataTable and [Doctrine](http://www.phpdoctrine.org/). Those are the ones I know of, I am sure there are more implementations. Out of those three I'd recommend Doctrine. Last time I checked Adodb carried a lot of extra weight for PHP4 and Zend\_Db\_\* is generally not known to be the best in terms of completeness and performance (most likely due to its young age). Doctrine aside from Active Table and the general database abstraction thing (aka DBAL) has so many things (e.g. migrations) which make it worth checking out, so if you haven't set your mind on a DBAL yet, you need to check it out.
I realize this is old, but there is an absolutely fabulous PHP Activecord library called, appropriately, PHP Activerecord. I've used it for several months and it blows away the other libraries. Check it out: <http://www.phpactiverecord.org/>
Recommendations for implementations of ActiveRecord
[ "", "php", "" ]
I am looking for a best practice for End to End Authentication for internal Web Applications to the Database layer. The most common scenario I have seen is to use a single SQL account with the permissions set to what is required by the application. This account is used by all application calls. Then when people require access over the database via query tools or such a separate Group is created with the query access and people are given access to that group. The other scenario I have seen is to use complete Windows Authentication End to End. So the users themselves are added to groups which have all the permissions set so the user is able to update and change outside the parameters of the application. This normally involves securing people down to the appropriate stored procedures so they aren't updating the tables directly. The first scenario seems relatively easily to maintain but raises concerns if there is a security hole in the application then the whole database is compromised. The second scenario seems more secure but has the opposite concern of having to much business logic in stored procedures on the database. This seems to limit the use of the some really cool technologies like Nhibernate and LINQ. However in this day and age where people can use data in so many different ways we don't foresee e.g. mash-ups etc is this the best approach.
Dale - That's it exactly. If you want to provide access to the underlying data store to those users then do it via services. And in my experience, it is those experienced computer users coming out of Uni/College that damage things the most. As the saying goes, they know just enough to be dangerous. If they want to automate part of their job, and they can display they have the requisite knowledge, then go ahead, grant their **domain account** access to the backend. That way anything they do via their little VBA automation is tied to their account and you know exactly who to go look at when the data gets hosed. My basic point is that the database is the proverbial holy grail of the application. You want as few fingers in that particular pie as possible. As a consultant, whenever I hear that someone has allowed normal users into the database, my eyes light up because I know it's going to end up being a big paycheck for me when I get called to fix it.
Personally, I don't want normal end users in the database. For an intranet application (especially one which resides on a Domain) I would provide a single account for application access to the database which only has those rights which are needed for the application to function. Access to the application would then be controlled via the user's domain account (turn off anonymous access in IIS, etc.). **IF** a user needs, and can justify, direct access to the database, then their **domain account** would be given access to the database, and they can log into the DBMS using the appropriate tools.
Database Authentication for Intranet Applications
[ "", "asp.net", "sql", "nhibernate", "" ]
What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this? And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?
``` Map map = new HashMap(); Hashtable ht = new Hashtable(); ``` Both classes can be found from the java.util package. The difference between the 2 is explained in the following [jGuru FAQ entry](http://www.jguru.com/faq/view.jsp?EID=430247).
You can use double-braces to set up the data. You still call add, or put, but it's less ugly: ``` private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{ put("foo", 1); put("bar", 256); put("data", 3); put("moredata", 27); put("hello", 32); put("world", 65536); }}; ```
How do I create a hash table in Java?
[ "", "java", "hash", "hashmap", "" ]
I have a need to close a parent form from within child form from a Windows application. What would be the best way to do this?
When you close form in WinForms it disposes all of it's children. So it's not a good idea. You need to do it asynchronously, for example you can send a message to parent form.
I ran across this blog entry that looks like it will work and it uses the Event Handler concept from D2VIANT Answer <http://www.dotnetcurry.com/ShowArticle.aspx?ID=125> Summary: Step 1: Create a new Windows application. Open Visual Studio 2005 or 2008. Go to File > New > Project > Choose Visual Basic or Visual C# in the ‘Project Types’ > Windows Application. Give the project a name and location > OK. Step 2: Add a n ew form to the project. Right click the project > Add > Windows Forms > Form2.cs > Add. Step 3: Now in the Form1, drag and drop a button ‘btnOpenForm’ and double click it to generate an event handler. Write the following code in it. Also add the frm2\_FormClosed event handler as shown below: ``` private void btnOpenForm_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(); frm2.FormClosed += new FormClosedEventHandler(frm2_FormClosed); frm2.Show(); this.Hide(); } private void frm2_FormClosed(object sender, FormClosedEventArgs e) { this.Close(); } ```
How do I close a parent Form from child form in Windows Forms 2.0?
[ "", "c#", "winforms", "" ]
I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state). Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better? For example: ``` function updateDOM(id) { // updates the id element based on form state } ``` should I invoke it via: ``` window.onload = function() { updateDOM("myElement"); }; ``` or: ``` <div id="myElement">...</div> <script language="javascript"> updateDOM("myElement"); </script> ``` The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it. Any thoughts? Is one version really better than the other?
Definitely use `onload`. Keep your scripts separate from your page, or you'll go mad trying to disentangle them later.
The onload event is considered the proper way to do it, but if you don't mind using a javascript library, jQuery's $(document).ready() is even better. ``` $(document).ready(function(){ // manipulate the DOM all you want here }); ``` The advantages are: 1. Call $(document).ready() as many times as you want to register additional code to run - you can only set window.onload once. 2. $(document).ready() actions happen as soon as the DOM is complete - window.onload has to wait for images and such. I hope I'm not becoming The Guy Who Suggests jQuery On Every JavaScript Question, but it really is great.
Should I use window.onload or script block?
[ "", "javascript", "dom", "" ]
After I was convinced that labeled breaks/continues are a total "nono" over [here](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501), I need help to remove the label out of my code. I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop. I hope, the code-fragment is basically understandable… ``` vectorLoop: for( int idx = 0; idx < vectorLength; idx++) { if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop; matrixLoop: for( rowIdx = 0; rowIdx < n; rowIdx++ ) { if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop; if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop; } setValueInVector( v, idx ); } ``` Please convince me, that there is a more readable/better version without the labels.
Looking at the solutions presented so far: * They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself * Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything. * Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly. * Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed. All of which makes me believe that, at least in the case of this question as phrased, the label is the correct solution and doesn't need to be refactored away. Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule.
This question was not about optimizing the algorithm - but thanks anyway ;-) At the time I wrote it, I considered the labeled continue as a readable solution. I asked SO a [question](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501) about the convention (having the label in all caps or not) for labels in Java. Basically every answer told me "do not use them - there is always a better way! refactor!". So I posted this question to ask for a more readable (and therefore better?) solution. Until now, I am not completely convinced by the alternatives presented so far. Please don't get me wrong. Labels are evil most of the time. But in my case, the conditional tests are pretty simple and the algorithm is taken from a mathematical paper and therefore very likely to not change in the near future. So I prefer having all the relevant parts visible at once instead of having to scroll to another method named something like checkMatrixAtRow(x). Especially at more complex mathematical algorithms, I find it pretty hard to find "good" function-names - but I guess that is yet another question
Refactoring away labeled loops
[ "", "java", "refactoring", "label", "" ]
Is there any way to get the ID of the element that fires an event? I'm thinking something like: ``` $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); }); ``` ``` <script type="text/javascript" src="starterkit/jquery.js"></script> <form class="item" id="aaa"> <input class="title"></input> </form> <form class="item" id="bbb"> <input class="title"></input> </form> ``` Except of course that the var `test` should contain the id `"aaa"`, if the event is fired from the first form, and `"bbb"`, if the event is fired from the second form.
In jQuery `event.target` always refers to the element that triggered the event, where `event` is the parameter passed to the function. <http://api.jquery.com/category/events/event-object/> ``` $(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); }); ``` Note also that `this` will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as `$(this)`, e.g.: ``` $(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); }); }); ```
For reference, try this! It works! ``` jQuery("classNameofDiv").click(function() { var contentPanelId = jQuery(this).attr("id"); alert(contentPanelId); }); ```
Getting the ID of the element that fired an event
[ "", "javascript", "jquery", "dom-events", "" ]
Is there a simple way to cache `MySQL queries` in `PHP` or failing that, is there a small class set that someone has written and made available that will do it? I can cache a whole page but that won't work as some data changes but some do not, I want to cache the part that does not.
This is a great overview of how to cache queries in MySQL: * [The MySQL Query Cache](http://www.petefreitag.com/item/390.cfm)
You can use [Zend Cache](http://framework.zend.com/manual/en/zend.cache.html) to cache results of your queries among other things.
Caching MySQL queries
[ "", "php", "mysql", "caching", "" ]
Does anyone have time to take a look at it? I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot
I have compared Mozilla Firefox 3.0.1 and Google Chrome 0.2.149.27 on [SunSpider JavaScript Benchmark](http://www2.webkit.org/perf/sunspider-0.9/sunspider.html) with the following results: * Firefox - total: 2900.0ms +/- 1.8% * Chrome - total: **1549.2ms +/- 1.7%** and on [V8 Benchmark Suite](http://code.google.com/apis/v8/benchmarks.html) with the following results (higher score is better): * Firefox - score: 212 * Chrome - score: **1842** and on [Web Browser Javascript Benchmark](http://celtickane.com/webdesign/jsspeedarchive.php) with the following results: * Firefox - total duration: 362 ms * Chrome - total duration: **349 ms** *Machine:* Windows XP SP2, Intel Core2 DUO T7500 @ 2.2 Ghz, 2 GB RAM All blog posts and articles that I've read so far also claim that V8 is clearly the fastest JavaScript engine out there. See for example - [V8, TraceMonkey, SquirrelFish, IE8 BenchMarks](http://waynepan.com/2008/09/02/v8-tracemonkey-squirrelfish-ie8-benchmarks/) > "... Needless to say, Chrome’s V8 blows away all the current builds of the next-generation of JavaScript VMs. Just to be clear, WebKit and FireFox engines haven’t even hit beta, but it looks like the performance bar has just been set to an astronomical height by the V8 Team."
Perhaps a bit anecdotal but comparing runs between Firefox and Chrome showed a significant difference in benchmarks. <http://www2.webkit.org/perf/sunspider-0.9/sunspider.html> Try for yourself.
Is Google Chrome's V8 engine really that good?
[ "", "javascript", "google-chrome", "v8", "" ]
Here's a quick question I've been banging my head against today. I'm trying to convert a .Net dataset into an XML stream, transform it with an xsl file in memory, then output the result to a new XML file. Here's the current solution: ``` string transformXML = @"pathToXslDocument"; XmlDocument originalXml = new XmlDocument(); XmlDocument transformedXml = new XmlDocument(); XslCompiledTransform transformer = new XslCompiledTransform(); DataSet ds = new DataSet(); string filepath; originalXml.LoadXml(ds.GetXml()); //data loaded prior StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); transformer.Load(transformXML); transformer.Transform(originalXml, writer); //no need to select the node transformedXml.LoadXml(sb.ToString()); transformedXml.Save(filepath); writer.Close(); ``` Here's the original code: ``` BufferedStream stream = new BufferedStream(new MemoryStream()); DataSet ds = new DataSet(); da.Fill(ds); ds.WriteXml(stream); StreamReader sr = new StreamReader(stream, true); stream.Position = 0; //I'm not certain if this is necessary, but for the StreamReader to read the text the position must be reset. XmlReader reader = XmlReader.Create(sr, null); //Problem is created here, the XmlReader is created with none of the data from the StreamReader XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(@"<path to xsl file>"); transformer.Transform(reader, null, writer); //Exception is thrown here, though the problem originates from the XmlReader.Create(sr, null) ``` For some reason in the transformer.Transform method, the reader has no root node, in fact the reader isn't reading anything from the StreamReader. My questions is what is wrong with this code? Secondarily, is there a better way to convert/transform/store a dataset into XML? Edit: Both answers were helpful and technically aku's was closer. However I am leaning towards a solution that more closely resembles Longhorn's after trying both solutions.
I'm not sure but it seems that you didn't reset position in stream before passing it to XmlReader. Try to seek at the beginning of your stream before trying to read from it. Also it may be necessary to close\flush stream after you wrote some data to it. **EDIT**: Just tried following code and it worked perfectly: ``` BufferedStream stream = new BufferedStream(new MemoryStream()); stream.Write(Encoding.ASCII.GetBytes("<xml>foo</xml>"), 0, "<xml>foo</xml>".Length); stream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(stream); XmlReader reader = XmlReader.Create(sr); while (reader.Read()) { Console.WriteLine(reader.Value); } stream.Close(); ```
You must select the root node. This doesn't use Datasets, but I use this function everyday and it works great. ``` System.Xml.XmlDocument orgDoc = new System.Xml.XmlDocument(); orgDoc.LoadXml(orgXML); // MUST SELECT THE ROOT NODE XmlNode transNode = orgDoc.SelectSingleNode("/"); System.Text.StringBuilder sb = new System.Text.StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); System.IO.StringReader stream = new System.IO.StringReader(transformXML); XmlReader reader = XmlReader.Create(stream); System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform(); trans.Load(reader); trans.Transform(transNode, writer); XmlDocument doc = new XmlDocument(); doc.LoadXml(sb.ToString()); return doc; ```
How to Convert a StreamReader into an XMLReader object in .Net 2.0/C#
[ "", "c#", ".net", "xml", "xslt", "stream", "" ]
I have an absolutely positioned `div` that I want to show when the user clicks a link. The `onclick` of the link calls a js function that sets the display of the div to block (also tried: "", `inline`, `table-cell`, `inline-table`, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari). I've tried adding alerts before and after the call, and they show that the display has changed from `none` to `block` but the `div` does not display. I can get the `div` to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc. I've tried everything I can think of, including: * Using a different doctype (XHTML 1, HTML 4, etc) * Using visibility visible/hidden instead of display block/none * Using inline javascript instead of a function call * Testing from different machines Any ideas about what could cause this?
Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup: ``` function openPopup(popupID) { var divs = getObjectsByTagAndClass('div','popupDiv'); if (divs != undefined && divs != null) { for (var i = 0; i < divs.length; i++) { if (divs[i].id == popupID) divs[i].style.display = 'block'; } } } ``` (utility function getObjectsByTagAndClass not listed) Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs. So when debugging issues like this, **remember to check for duplicate IDs in the DOM, which can break getElementById**. To everyone who answered, thanks for your help!
Can you provide some markup that reproduce the error? Your situation must have something to do with your code since I can get this to work on IE, FF3 and Opera 9.5: ``` function show() { var d = document.getElementById('testdiv'); d.style.display = 'block'; } ``` ``` #testdiv { position: absolute; height: 20px; width: 20px; display: none; background-color: red; } ``` ``` <div id="testdiv"></div> <a href="javascript:show();">Click me</a> ```
Style display not working in Firefox, Opera, Safari - (IE7 is OK)
[ "", "javascript", "html", "css", "" ]
So my company stores alot of data in a foxpro database and trying to get around the performance hit of touching it directly I was thinking of messaging anything that can be done asynchronously for a snappier user experience. I started looking at [ActiveMQ](http://activemq.apache.org/) but don't know how well C# will hook with it. Wanting to hear what all of you guys think. edit : It is going to be a web application. Anything touching this foxpro is kinda slow (probably because the person who set it up 10 years ago messed it all to hell, some of the table files are incredibly large). We replicate the foxpro to sql nightly and most of our data reads are ok being a day old so we are focusing on the writes. plus the write affects a critical part of the user experience (purchasing), we store it in sql and then just message to have it put into foxpro when it can. I wish we could just get rid of the foxpro, unfortunately the company doesn't want to get rid of a very old piece of software they bought that depends on it.
ActiveMQ works well with C# using the Spring.NET integrations and NMS. A post with some links to get you started in that direction [is here](http://thefreakparade.com/2008/04/15/two-message-exchange-patterns-using-activemq-and-nms-via-springnet/). Also consider using MSMQ (The System.Messaging namespace) or a .NET based asynchronous messaging solution, with [some options here](http://thefreakparade.com/2008/06/03/esbs-for-the-microsoft-net-platform/).
MSMQ (Microsoft Message Queueing) may be a great choice. It is part of the OS and present as an optional component (can be installed via Add/Remove Programs / Windows Components), meaning it's free (as long you already paid for Windows, of course). MSMQ provides Win32/COM and [System.Messaging](https://learn.microsoft.com/en-us/dotnet/api/system.messaging) APIs. More modern Windows Communication Foundation (aka Indigo) [queued channels](https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/queuing-in-wcf) also use MSMQ. Note that MSMQ is not supported on Home SKUs of Windows (XP Home and Vista Home)
What to use for Messaging with C#
[ "", "c#", "messaging", "" ]
I want to convert a primitive to a string, and I tried: ``` myInt.toString(); ``` This fails with the error: ``` int cannot be dereferenced ``` Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that. Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?
Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows `myInt` as a primitive. There's a paper about this issue at [jcp.org](http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html). Autoboxing is mainly useful during assignment or parameter passing -- allowing you to pass a primitive as an object (or vice versa), or assign a primitive to an object (or vice versa). So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way) ``` Integer.toString(myInt); ```
Ditto on what Justin said, but you should do this instead: ``` Integer.toString(myInt); ``` It saves an allocation or two and is more readable.
Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?
[ "", "java", "autoboxing", "" ]
I have a `byte[]` array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the `BinaryWriter` object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object) The problem I'm having is that the commonly accepted code for this task: ``` public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } ``` doesn't work for me. The second line of the above method where it calls the `Image.FromStream` method dies at runtime, saying ``` Parameter Not Valid ``` I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the `FromStream` method accept this fact. How do I turn a byte array of a TIFF image into an Image object? Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.
**Edit:** The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly. I think you need to write to your MemeoryStream first. As if my memory (no pun intended) serves me correctly this: ``` MemoryStream ms = new MemoryStream(byteArrayIn); ``` Creates a memory stream of that size. You then need to write your byte array contents to the memory stream: ``` ms.Write(byteArrayIn, 0, byteArrayIn.Length); ``` See if that fixes it.
OK, I found the issue, and it was from a part of the code unrelated to the part of the code I was asking about. The data was being passed as a string, I was converting it to a byte array (this was a test rig so I was trying to simulate the byte array that I get in the main app), then converting that to a MemoryStream, then making an Image from that. What I failed to realize was that the string was Base64 encoded. Calling `Convert.FromBase64String()` caused it to turn into a byte array which wouldn't kill the `Image.FromStream()` method. So basically it boiled down to a stupid mistake on my part. But hey, the code above is still useful and this page will probably serve as a Google result as to how to avoid this mistake to someone else. Also, I found an easy way to construct a Multi-Page TIFF from my byte arrays [here](http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-csharp/70308/Craete-tiff-Image-Page-by-Page).
How can I take a byte array of a TIFF image and turn it into a System.Drawing.Image object?
[ "", "c#", ".net", "image", "tiff", "" ]
I am facing problem with an Oracle Query in a .net 2.0 based windows application. I am using `System.Data.OracleClient` to connect to oracle database. Name of database is `myDB`. Below the the connection string I am using: ``` Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL))); User ID=myDB;Password=myDB;Unicode=True ``` If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB): ``` SELECT ID, NAME FROM MyTempTable WHERE ID IN (10780, 10760, 11890) ``` But if I append the database name along with it the it is giving correct result: ``` SELECT ID, NAME FROM "myDB".MyTempTable WHERE ID IN (10780, 10760, 11890) ``` My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.
This looks like an issue with name resolution, try creating a public synonym on the table: CREATE PUBLIC SYNONYM *MyTempTable* for *MyTempTable*; Also, what exactly do you mean by **wrong result**, incorrect data, error message? --- Edit: What is the name of the schema that the required table belongs to? It sounds like the table that you are trying to select from is in a different schema to the one that belongs to the user you are connecting as.
Upon connecting to the database issue am ``` ALTER SESSION SET CURRENT_SCHEMA=abc; ``` where abc is the user that owns the tables.
Referencing same table name in different schemas
[ "", ".net", "sql", "oracle", "" ]
I have a project where I would like to generate a report export in MS Word format. The report will include images/graphs, tables, and text. What is the best way to do this? Third party tools? What are your experiences?
The answer is going to depend slightly upon if the application is running on a server or if it is running on the client machine. If you are running on a server then you are going to want to use one of the XML based office generation formats as there are know issues when [using Office Automation on a server](http://support.microsoft.com/kb/257757). However, if you are working on the client machine then you have a choice of either [using Office Automation](http://msdn.microsoft.com/en-us/office/default.aspx) or using the Office Open XML format (see links below), which is supported by Microsoft Office 2000 and up either natively or through service packs. One draw back to this though is that you might not be able to embed some kinds of graphs or images that you wish to show. The best way to go about things will all depend sightly upon how much time you have to invest in development. If you go the route of Office Automation there are quite a few good tutorials out there that can be found via Google and is fairly simple to learn. However, the Open Office XML format is fairly new so you might find the learning curve to be a bit higher. Office Open XML Iinformation * Office Open XML - <http://en.wikipedia.org/wiki/Office_Open_XML> * OpenXML Developer - <http://openxmldeveloper.org/default.aspx> * Introducing the Office (2007) Open XML File Formats - <http://msdn.microsoft.com/en-us/library/aa338205.aspx>
[DocX free library](http://docx.codeplex.com/) for creating DocX documents, actively developed and very easy and intuitive to use. Since CodePlex is dying, project has moved to [github](https://github.com/WordDocX/DocX).
How can a Word document be created in C#?
[ "", "c#", ".net", "ms-word", "openxml", "" ]
I have a blogengine.net install that requires privatization. I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met. How can I privatize my blogEngine.net install so that readers must log in to read my posts?
I use this extension. Just save the file as RequireLogin.cs in your App\_Code\Extensions folder and make sure the extension is activated. ``` using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using BlogEngine.Core; using BlogEngine.Core.Web.Controls; using System.Collections.Generic; /// <summary> /// Summary description for PostSecurity /// </summary> [Extension("Checks to see if a user can see this blog post.", "1.0", "<a href=\"http://www.lavablast.com\">LavaBlast.com</a>")] public class RequireLogin { static protected ExtensionSettings settings = null; public RequireLogin() { Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving); ExtensionSettings s = new ExtensionSettings("RequireLogin"); // describe specific rules for entering parameters s.Help = "Checks to see if the user has any of those roles before displaying the post. "; s.Help += "You can associate a role with a specific category. "; s.Help += "All posts having this category will require that the user have the role. "; s.Help += "A parameter with only a role without a category will enable to filter all posts to this role. "; ExtensionManager.ImportSettings(s); settings = ExtensionManager.GetSettings("PostSecurity"); } protected void Post_Serving(object sender, ServingEventArgs e) { MembershipUser user = Membership.GetUser(); if(HttpContext.Current.Request.RawUrl.Contains("syndication.axd")) { return; } if (user == null) { HttpContext.Current.Response.Redirect("~/Login.aspx"); } } } ```
From: [BlogEngine.NET 2.5 - Private Blogs](http://blogengine.codeplex.com/discussions/267878) If you go into the control panel, Users tab, Roles sub-tab (right side), for "Anonymous" on the right-side Tools area, hover over that and select "Rights". You are now on the Rights page for the Anonymous role. Uncheck everything, in particular "View Public Posts". HOWEVER, you do need to keep at least one item checked, otherwise everything reverts back to the default. For example, you could keep "View Ratings on Posts" checked. Then Save. Then anyone who is not logged in should automatically be redirected to the Login page no matter where what page they try to enter the site at.
Privatizing a BlogEngine.Net Installation
[ "", "c#", ".net", "asp.net", "blogs", "" ]
Why in this millennium should Python [PEP-8](http://www.python.org/dev/peps/pep-0008/) specify a [maximum line length](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) of 79 characters? Pretty much every code editor under the sun can handle longer lines. What to do with wrapping should be the choice of the content consumer, not the responsibility of the content creator. Are there any (legitimately) good reasons for adhering to 79 characters in this age?
Much of the value of PEP-8 is to stop people arguing about inconsequential formatting rules, and get on with writing good, consistently formatted code. Sure, no one really thinks that 79 is optimal, but there's no obvious gain in changing it to 99 or 119 or whatever your preferred line length is. I think the choices are these: follow the rule and find a worthwhile cause to battle for, or provide some data that demonstrates how readability and productivity vary with line length. The latter would be extremely interesting, and would have a good chance of changing people's minds I think.
Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side. Readability is also one of the reasons for enforced line indentation.
Why does PEP-8 specify a maximum line length of 79 characters?
[ "", "python", "coding-style", "pep8", "" ]
When `{0}` is used to initialize an object, what does it mean? I can't find any references to `{0}` anywhere, and because of the curly braces Google searches are not helpful. Example code: ``` SHELLEXECUTEINFO sexi = {0}; // what does this do? sexi.cbSize = sizeof(SHELLEXECUTEINFO); sexi.hwnd = NULL; sexi.fMask = SEE_MASK_NOCLOSEPROCESS; sexi.lpFile = lpFile.c_str(); sexi.lpParameters = args; sexi.nShow = nShow; if(ShellExecuteEx(&sexi)) { DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE); if(wait == WAIT_OBJECT_0) GetExitCodeProcess(sexi.hProcess, &returnCode); } ``` Without it, the above code will crash on runtime.
What's happening here is called **aggregate** initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec: > An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions. Now, using `{0}` to initialize an aggregate like this is basically a trick to `0` the entire thing. This is because when using aggregate initialization **you don't have to specify all the members** and the spec requires that all unspecified members be default initialized, which means set to `0` for simple types. Here is the relevant quote from the spec: > If there are fewer initializers in the list than there are members in the > aggregate, then each member not > explicitly initialized shall be > default-initialized. > Example: > > ``` > struct S { int a; char* b; int c; }; > S ss = { 1, "asdf" }; > ``` > > initializes `ss.a` with `1`, `ss.b` with > `"asdf"`, and `ss.c` with the value of an > expression of the form `int()`, that is, > `0`. You can find the complete spec on this topic [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf#page=207)
One thing to be aware of is that this technique will not set padding bytes to zero. For example: ``` struct foo { char c; int i; }; foo a = {0}; ``` Is not the same as: ``` foo a; memset(&a,0,sizeof(a)); ``` In the first case, pad bytes between c and i are uninitialized. Why would you care? Well, if you're saving this data to disk or sending it over a network or whatever, you could have a security issue.
What does {0} mean when initializing an object?
[ "", "c++", "c", "" ]
I want to be able to get an estimate of how much code & static data is used by my C++ program? Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime? Will objdump & readelf help?
"size" is the traditional tool. "readelf" has a lot of options. ``` $ size /bin/sh text data bss dec hex filename 712739 37524 21832 772095 bc7ff /bin/sh ```
If you want to take the next step of identifying the functions and data structures to focus on for footprint reduction, the --size-sort argument to nm can show you: ``` $ nm --size-sort /usr/bin/fld | tail -10 000000ae T FontLoadFontx 000000b0 T CodingByRegistry 000000b1 t ShmFont 000000ec t FontLoadw 000000ef T LoadFontFile 000000f6 T FontLoadDFontx 00000108 D fSRegs 00000170 T FontLoadMinix 000001e7 T main 00000508 T FontLoadBdf ```
Linux: What is the best way to estimate the code & static data size of program?
[ "", "c++", "linux", "unix", "" ]
The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus. Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta. ``` using System; using Microsoft.Win32; namespace HowTo { class WebClickSound { /// <summary> /// Enables or disables the web browser navigating click sound. /// </summary> public static bool Enabled { get { RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current"); string keyValue = (string)key.GetValue(null); return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\""; } set { string keyValue; if (value) { keyValue = "%SystemRoot%\\Media\\"; if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0) { // XP keyValue += "Windows XP Start.wav"; } else if (Environment.OSVersion.Version.Major == 6) { // Vista keyValue += "Windows Navigation Start.wav"; } else { // Don't know the file name so I won't be able to re-enable it return; } } else { keyValue = "\"\""; } // Open and set the key that points to the file RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true); key.SetValue(null, keyValue, RegistryValueKind.ExpandString); isEnabled = value; } } } } ``` Then in the main form we use the above code in these 3 events: * Activated * Deactivated * FormClosing ``` private void Form1_Activated(object sender, EventArgs e) { // Disable the sound when the program has focus WebClickSound.Enabled = false; } private void Form1_Deactivate(object sender, EventArgs e) { // Enable the sound when the program is out of focus WebClickSound.Enabled = true; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Enable the sound on app exit WebClickSound.Enabled = true; } ``` The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that. What do you guys think? Is this a good solution? What improvements can be made?
I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen. So instead of this: ``` webBrowser1.DocumentText = "<h1>Hello, world!</h1>"; ``` try this: ``` webBrowser1.Document.OpenNew(true); webBrowser1.Document.Write("<h1>Hello, world!</h1>"); ```
``` const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21; const int SET_FEATURE_ON_PROCESS = 0x00000002; [DllImport("urlmon.dll")] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] static extern int CoInternetSetFeatureEnabled(int FeatureEntry, [MarshalAs(UnmanagedType.U4)] int dwFlags, bool fEnable); static void DisableClickSounds() { CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS, SET_FEATURE_ON_PROCESS, true); } ```
HowTo Disable WebBrowser 'Click Sound' in your app only
[ "", "c#", ".net", "winforms", "" ]